<?php
require 'auth_check.php';
require '../config/db.php';

$msg = "";
$msgClass = "";

// 1. HANDLE ADD COUPON
if (isset($_POST['add_coupon'])) {
    $code = strtoupper(trim($_POST['code']));
    $type = $_POST['type'];
    $value = $_POST['value'];
    
    // Check if code exists
    $check = $pdo->prepare("SELECT id FROM coupons WHERE code = ?");
    $check->execute([$code]);
    
    if($check->rowCount() == 0) {
        $stmt = $pdo->prepare("INSERT INTO coupons (code, type, value) VALUES (?, ?, ?)");
        if($stmt->execute([$code, $type, $value])) {
            $msg = "Success! Coupon <strong>$code</strong> created.";
            $msgClass = "success";
        } else {
            $msg = "Error creating coupon.";
            $msgClass = "error";
        }
    } else {
        $msg = "Coupon code '$code' already exists.";
        $msgClass = "error";
    }
}

// 2. HANDLE DELETE COUPON
if (isset($_GET['delete'])) {
    $id = $_GET['delete'];
    $pdo->prepare("DELETE FROM coupons WHERE id = ?")->execute([$id]);
    header("Location: coupons.php?msg=deleted");
    exit();
}

// 3. FETCH COUPONS
$coupons = $pdo->query("SELECT * FROM coupons ORDER BY id DESC")->fetchAll();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Manage Coupons</title>
    <link rel="stylesheet" href="admin_style.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        .msg-box { padding: 10px; border-radius: 5px; margin-bottom: 20px; text-align: center; }
        .success { background: #d4edda; color: #155724; border: 1px solid #c3e6cb; }
        .error { background: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; }
        
        .form-card { background: white; padding: 20px; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.05); margin-bottom: 30px; }
        .input-group { margin-right: 10px; flex: 1; }
        .input-group input, .input-group select { width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 4px; box-sizing: border-box; }
        
        .tag { padding: 4px 8px; border-radius: 4px; font-size: 12px; font-weight: bold; }
        .tag-fixed { background: #e8f4fd; color: #2980b9; border: 1px solid #bce0fd; }
        .tag-percent { background: #fff4e5; color: #d35400; border: 1px solid #ffe0b2; }
    </style>
</head>
<body>

   <?php include 'sidebar.php'; ?>

    <div class="content">
        <h1>Coupon Manager</h1>
        
        <?php if($msg): ?>
            <div class="msg-box <?php echo $msgClass; ?>"><?php echo $msg; ?></div>
        <?php endif; ?>
        <?php if(isset($_GET['msg']) && $_GET['msg']=='deleted'): ?>
            <div class="msg-box success">Coupon deleted successfully.</div>
        <?php endif; ?>

        <div class="form-card">
            <h3 style="margin-top:0;">Create New Coupon</h3>
            <form method="POST" style="display: flex; align-items: flex-end; flex-wrap: wrap; gap: 10px;">
                
                <div class="input-group" style="flex: 2; min-width: 200px;">
                    <label style="font-weight: bold; font-size: 12px; display: block; margin-bottom: 5px;">Coupon Code</label>
                    <input type="text" name="code" placeholder="e.g. SALE50" required style="text-transform: uppercase; font-weight: bold;">
                </div>

                <div class="input-group" style="flex: 1; min-width: 150px;">
                    <label style="font-weight: bold; font-size: 12px; display: block; margin-bottom: 5px;">Discount Type</label>
                    <select name="type">
                        <option value="fixed">Flat Amount (₹)</option>
                        <option value="percent">Percentage (%)</option>
                    </select>
                </div>

                <div class="input-group" style="flex: 1; min-width: 100px;">
                    <label style="font-weight: bold; font-size: 12px; display: block; margin-bottom: 5px;">Value</label>
                    <input type="number" name="value" placeholder="e.g. 100" required>
                </div>

                <button type="submit" name="add_coupon" class="btn btn-primary" style="padding: 10px 20px; height: 38px;">Create</button>
            </form>
        </div>

        <h3>Active Coupons</h3>
        <table style="background: white; width: 100%; border-collapse: collapse;">
            <thead>
                <tr style="background: #f1f1f1;">
                    <th style="padding: 10px; text-align: left;">Code</th>
                    <th style="padding: 10px; text-align: left;">Discount Type</th>
                    <th style="padding: 10px; text-align: left;">Value</th>
                    <th style="padding: 10px; text-align: left;">Created At</th>
                    <th style="padding: 10px; text-align: left;">Action</th>
                </tr>
            </thead>
            <tbody>
                <?php if(count($coupons) > 0): ?>
                    <?php foreach ($coupons as $c): ?>
                    <tr style="border-bottom: 1px solid #eee;">
                        <td style="padding: 10px;">
                            <strong style="color: #2c3e50; letter-spacing: 1px;"><?php echo htmlspecialchars($c['code']); ?></strong>
                        </td>
                        <td style="padding: 10px;">
                            <?php if($c['type'] == 'fixed'): ?>
                                <span class="tag tag-fixed">Flat Amount</span>
                            <?php else: ?>
                                <span class="tag tag-percent">Percentage</span>
                            <?php endif; ?>
                        </td>
                        <td style="padding: 10px; font-weight: bold; color: #27ae60;">
                            <?php echo $c['type'] == 'fixed' ? '₹' . $c['value'] : $c['value'] . '% OFF'; ?>
                        </td>
                        <td style="padding: 10px; color: #777; font-size: 13px;">
                            <?php echo date('d M Y', strtotime($c['created_at'])); ?>
                        </td>
                        <td style="padding: 10px;">
                            <a href="coupons.php?delete=<?php echo $c['id']; ?>" style="color: #e74c3c; text-decoration: none; font-weight: bold;" onclick="return confirm('Delete this coupon permanently?');">
                                <i class="fas fa-trash"></i> Delete
                            </a>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                <?php else: ?>
                    <tr>
                        <td colspan="5" style="padding: 20px; text-align: center; color: #777;">No coupons created yet.</td>
                    </tr>
                <?php endif; ?>
            </tbody>
        </table>

    </div>

</body>
</html>