<?php
/**
 * Manage Vouchers & Coupons (Mobile Responsive & Premium Theme)
 */
require_once 'header.php';

$success = '';
$error = '';

// ১. কুপন যোগ করার লজিক
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_coupon'])) {
    $code = strtoupper(trim($_POST['code']));
    $discount_value = (float)$_POST['discount_value'];
    $is_percentage = isset($_POST['is_percentage']) ? 1 : 0;
    $valid_until = trim($_POST['valid_until']);

    if (empty($code) || $discount_value <= 0 || empty($valid_until)) {
        $error = "All fields are required and discount must be greater than 0.";
    } else {
        try {
            // কোড ডুপ্লিকেট কিনা চেক
            $stmt = $pdo->prepare("SELECT id FROM coupons WHERE code = ?");
            $stmt->execute([$code]);
            if ($stmt->fetch()) {
                $error = "This coupon code already exists!";
            } else {
                $insert = $pdo->prepare("INSERT INTO coupons (code, discount_value, is_percentage, valid_until, status) VALUES (?, ?, ?, ?, 'active')");
                $insert->execute([$code, $discount_value, $is_percentage, $valid_until]);
                $success = "Voucher code '$code' created successfully!";
            }
        } catch (PDOException $e) {
            $error = "Database Error: " . $e->getMessage();
        }
    }
}

// ২. কুপন ডিলিট করার লজিক
if (isset($_GET['delete'])) {
    $id = (int)$_GET['delete'];
    $pdo->prepare("DELETE FROM coupons WHERE id = ?")->execute([$id]);
    $success = "Voucher deleted successfully!";
}

// ৩. কুপন লিস্ট তুলে আনা
$coupons = $pdo->query("SELECT * FROM coupons ORDER BY id DESC")->fetchAll();
$currency = defined('CURRENCY_SYMBOL') ? CURRENCY_SYMBOL : 'BDT ';
?>

<style>
    .page-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 25px; flex-wrap: wrap; gap: 10px; }
    .page-title { font-size: 1.5rem; font-weight: 800; color: var(--text-dark); margin: 0; }
    
    .alert-box { padding: 15px 20px; border-radius: 8px; margin-bottom: 25px; font-weight: 600; font-size: 0.95rem; }
    .alert-success { background: #ecfdf5; border: 1px solid #a7f3d0; color: #065f46; }
    .alert-danger { background: #fee2e2; border: 1px solid #fecaca; color: #991b1b; }

    .grid-layout { display: grid; grid-template-columns: 350px 1fr; gap: 25px; align-items: start; }
    
    .admin-card { background: var(--bg-white); border-radius: 12px; padding: 25px; box-shadow: 0 1px 3px rgba(0,0,0,0.03); border: 1px solid var(--border-color); margin-bottom: 20px; min-width: 0; width: 100%; box-sizing: border-box; }

    .form-group { margin-bottom: 20px; }
    .form-label { display: block; font-size: 0.9rem; font-weight: 700; margin-bottom: 8px; color: var(--text-dark); }
    
    .btn-submit { background: var(--primary-orange); color: white; padding: 12px 20px; border: none; border-radius: 8px; font-weight: 700; font-size: 1rem; cursor: pointer; width: 100%; transition: 0.3s; }
    .btn-submit:hover { background: #ea580c; transform: translateY(-2px); }

    .table-responsive { width: 100%; overflow-x: auto; -webkit-overflow-scrolling: touch; display: block; }
    .data-table { width: 100%; border-collapse: collapse; text-align: left; min-width: 500px; }
    .data-table th { padding: 15px 12px; font-size: 0.8rem; color: var(--text-gray); font-weight: 700; border-bottom: 1px solid var(--border-color); text-transform: uppercase; white-space: nowrap; background: #f9fafb; }
    .data-table td { padding: 12px; border-bottom: 1px solid #f3f4f6; font-size: 0.9rem; color: var(--text-dark); font-weight: 600; vertical-align: middle; }
    
    .code-badge { font-family: monospace; font-size: 1rem; font-weight: 800; color: var(--primary-orange); background: var(--primary-light); padding: 4px 10px; border-radius: 6px; border: 1px dashed var(--primary-orange); display: inline-block; }
    
    .btn-delete { color: #ef4444; background: #fee2e2; padding: 6px 10px; border-radius: 6px; text-decoration: none; font-size: 0.75rem; font-weight: 700; display: inline-block; transition: 0.3s; white-space: nowrap; }
    .btn-delete:hover { background: #fecaca; }

    /* Checkbox toggle */
    .checkbox-wrap { display: flex; align-items: center; gap: 8px; font-size: 0.9rem; font-weight: 600; color: var(--text-gray); cursor: pointer; }
    .checkbox-wrap input { width: 18px; height: 18px; cursor: pointer; accent-color: var(--primary-orange); }

    @media (max-width: 992px) {
        .grid-layout { grid-template-columns: 1fr; gap: 20px; }
        .admin-card { padding: 20px 15px; }
    }
</style>

<div class="page-header">
    <h1 class="page-title">Vouchers / Coupons</h1>
</div>

<?php if($success): ?> <div class="alert-box alert-success">✓ <?php echo $success; ?></div> <?php endif; ?>
<?php if($error): ?> <div class="alert-box alert-danger">⚠ <?php echo $error; ?></div> <?php endif; ?>

<div class="grid-layout">
    
    <div class="admin-card">
        <h3 style="margin-top: 0; font-size: 1.1rem; border-bottom: 1px solid var(--border-color); padding-bottom: 15px; margin-bottom: 20px;">Generate New Voucher</h3>
        
        <form action="" method="POST">
            <input type="hidden" name="add_coupon" value="1">
            
            <div class="form-group">
                <label class="form-label">Coupon Code</label>
                <input type="text" name="code" class="form-control" placeholder="e.g. EID2026" style="text-transform: uppercase;" required>
            </div>

            <div class="form-group">
                <label class="form-label">Discount Value</label>
                <input type="number" step="0.01" name="discount_value" class="form-control" placeholder="0.00" required>
            </div>

            <div class="form-group">
                <label class="checkbox-wrap">
                    <input type="checkbox" name="is_percentage" value="1">
                    Calculate as Percentage (%)
                </label>
                <div style="font-size: 0.75rem; color: var(--text-muted); margin-top: 5px; margin-left: 26px;">If checked, it will deduct % instead of flat amount.</div>
            </div>

            <div class="form-group">
                <label class="form-label">Expiry Date</label>
                <input type="date" name="valid_until" class="form-control" required>
            </div>
            
            <button type="submit" class="btn-submit">Save Voucher</button>
        </form>
    </div>

    <div class="admin-card">
        <h3 style="margin-top: 0; font-size: 1.1rem; border-bottom: 1px solid var(--border-color); padding-bottom: 15px; margin-bottom: 20px;">Active Vouchers</h3>
        
        <div class="table-responsive">
            <table class="data-table">
                <thead>
                    <tr>
                        <th>Voucher Code</th>
                        <th>Discount</th>
                        <th>Expiry Date</th>
                        <th style="text-align: right;">Action</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach($coupons as $c): ?>
                    <tr>
                        <td>
                            <div class="code-badge"><?php echo htmlspecialchars($c['code']); ?></div>
                        </td>
                        <td>
                            <?php 
                                if($c['is_percentage']) {
                                    echo "<span style='color:#10b981;'>".floatval($c['discount_value'])."% OFF</span>";
                                } else {
                                    echo "<span style='color:#3b82f6;'>".$currency.number_format($c['discount_value'], 2)."</span>";
                                }
                            ?>
                        </td>
                        <td style="color: <?php echo (strtotime($c['valid_until']) < time()) ? '#ef4444' : 'var(--text-gray)'; ?>;">
                            <?php echo date('d M, Y', strtotime($c['valid_until'])); ?>
                            <?php if(strtotime($c['valid_until']) < time()) echo "<br><span style='font-size:10px; font-weight:800; color:#ef4444;'>(EXPIRED)</span>"; ?>
                        </td>
                        <td style="text-align: right;">
                            <a href="?delete=<?php echo $c['id']; ?>" onclick="return confirm('Delete this voucher?')" class="btn-delete">
                                Delete
                            </a>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                    
                    <?php if(count($coupons) == 0): ?>
                        <tr><td colspan="4" style="text-align: center; padding: 40px; color: var(--text-muted); font-weight: 500;">No vouchers created yet.</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>

</div>

<?php echo '</div></div></body></html>'; ?>