<?php
/**
 * Admin - Coupons / Promo Codes
 */
require_once __DIR__ . '/../config.php';
require_admin_login();

$page_title = 'Coupons & Promo Codes';

// Handle bulk actions
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['bulk_action'])) {
    if (!verify_csrf_token($_POST['csrf_token'] ?? '')) {
        redirect(BASE_URL . 'admin/coupons.php', 'error', 'Invalid security token');
    }
    
    $ids = $_POST['selected_ids'] ?? [];
    $action = $_POST['bulk_action'];
    
    if (!empty($ids)) {
        $placeholders = implode(',', array_fill(0, count($ids), '?'));
        try {
            if ($action === 'delete') {
                $stmt = db()->prepare("DELETE FROM coupons WHERE id IN ($placeholders)");
                $stmt->execute($ids);
                redirect(BASE_URL . 'admin/coupons.php', 'success', count($ids) . ' coupons deleted');
            } elseif ($action === 'activate') {
                $stmt = db()->prepare("UPDATE coupons SET is_active = 1 WHERE id IN ($placeholders)");
                $stmt->execute($ids);
                redirect(BASE_URL . 'admin/coupons.php', 'success', count($ids) . ' coupons activated');
            } elseif ($action === 'deactivate') {
                $stmt = db()->prepare("UPDATE coupons SET is_active = 0 WHERE id IN ($placeholders)");
                $stmt->execute($ids);
                redirect(BASE_URL . 'admin/coupons.php', 'success', count($ids) . ' coupons deactivated');
            }
        } catch (PDOException $e) {
            redirect(BASE_URL . 'admin/coupons.php', 'error', 'Action failed');
        }
    }
}

// Get coupons
$coupons = [];
$search = sanitize($_GET['search'] ?? '');
$status = $_GET['status'] ?? '';

$conditions = [];
$params = [];

if ($search) {
    $conditions[] = '(code LIKE ? OR description LIKE ?)';
    $params[] = '%' . $search . '%';
    $params[] = '%' . $search . '%';
}
if ($status !== '') {
    $conditions[] = 'is_active = ?';
    $params[] = $status;
}

$sql = "SELECT * FROM coupons";
if ($conditions) {
    $sql .= " WHERE " . implode(' AND ', $conditions);
}
$sql .= " ORDER BY created_at DESC";

try {
    $stmt = db()->prepare($sql);
    $stmt->execute($params);
    $coupons = $stmt->fetchAll();
} catch (PDOException $e) {}

$csrf_token = generate_csrf_token();
include __DIR__ . '/includes/header.php';
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <h2 class="fw-bold mb-0">Coupons & Promo Codes</h2>
    <a href="coupon-add.php" class="btn btn-primary"><i class="bi bi-plus-lg me-2"></i>Add Coupon</a>
</div>

<form method="GET" class="row g-3 mb-4">
    <div class="col-md-4">
        <input type="text" name="search" class="form-control" placeholder="Search coupons..." value="<?php echo $search; ?>">
    </div>
    <div class="col-md-3">
        <select name="status" class="form-select">
            <option value="">All Status</option>
            <option value="1" <?php echo $status === '1' ? 'selected' : ''; ?>>Active</option>
            <option value="0" <?php echo $status === '0' ? 'selected' : ''; ?>>Inactive</option>
        </select>
    </div>
    <div class="col-md-2">
        <button type="submit" class="btn btn-outline-primary w-100">Filter</button>
    </div>
    <div class="col-md-2">
        <a href="coupons.php" class="btn btn-outline-secondary w-100">Clear</a>
    </div>
</form>

<form method="POST">
    <input type="hidden" name="csrf_token" value="<?php echo $csrf_token; ?>">
    
    <div class="card border-0 shadow-sm">
        <div class="card-header bg-white d-flex justify-content-between align-items-center">
            <span class="fw-bold">Coupons</span>
            <div class="d-flex gap-2">
                <select name="bulk_action" class="form-select form-select-sm" style="width: auto;">
                    <option value="">Bulk Actions</option>
                    <option value="activate">Activate</option>
                    <option value="deactivate">Deactivate</option>
                    <option value="delete">Delete</option>
                </select>
                <button type="submit" class="btn btn-sm btn-outline-secondary">Apply</button>
            </div>
        </div>
        <div class="table-responsive">
            <table class="table table-hover mb-0">
                <thead class="table-light">
                    <tr>
                        <th><input type="checkbox" class="form-check-input" id="selectAll"></th>
                        <th>Code</th>
                        <th>Discount</th>
                        <th>Uses</th>
                        <th>Expires</th>
                        <th>Status</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($coupons as $coupon): 
                        $discount = $coupon['discount_type'] === 'percentage' 
                            ? $coupon['discount_value'] . '%' 
                            : format_currency($coupon['discount_value']);
                        $uses = $coupon['used_count'] . '/' . ($coupon['max_uses'] ?? '∞');
                        $expired = $coupon['expires_at'] && strtotime($coupon['expires_at']) < time();
                    ?>
                    <tr>
                        <td><input type="checkbox" name="selected_ids[]" value="<?php echo $coupon['id']; ?>" class="form-check-input row-checkbox"></td>
                        <td><strong><?php echo $coupon['code']; ?></strong></td>
                        <td><?php echo $discount; ?></td>
                        <td><?php echo $uses; ?></td>
                        <td>
                            <?php if ($coupon['expires_at']): ?>
                                <span class="text-<?php echo $expired ? 'danger' : 'success'; ?>">
                                    <?php echo date('d M Y', strtotime($coupon['expires_at'])); ?>
                                    <?php if ($expired) echo '(Expired)'; ?>
                                </span>
                            <?php else: ?>
                                <span class="text-muted">No expiry</span>
                            <?php endif; ?>
                        </td>
                        <td>
                            <span class="badge bg-<?php echo ($coupon['is_active'] && !$expired) ? 'success' : 'secondary'; ?>">
                                <?php echo ($coupon['is_active'] && !$expired) ? 'Active' : 'Inactive'; ?>
                            </span>
                        </td>
                        <td>
                            <a href="coupon-edit.php?id=<?php echo $coupon['id']; ?>" class="btn btn-sm btn-outline-primary">
                                <i class="bi bi-pencil"></i>
                            </a>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                    <?php if (empty($coupons)): ?>
                    <tr><td colspan="7" class="text-center py-4 text-muted">No coupons found</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</form>

<script>
document.getElementById('selectAll').addEventListener('change', function() {
    document.querySelectorAll('.row-checkbox').forEach(cb => cb.checked = this.checked);
});
</script>

<?php include __DIR__ . '/includes/footer.php'; ?>
