<?php
require_once __DIR__ . '/../functions.php';
requireAdmin();
$page_title = 'Offers';
$db = db();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $title = $_POST['title'] ?? '';
    $description = $_POST['description'] ?? '';
    $badgeText = $_POST['badge_text'] ?? '';
    $icon = $_POST['icon'] ?? 'fa-tag';
    $sortOrder = (int)($_POST['sort_order'] ?? 0);
    $isActive = isset($_POST['is_active']) ? 1 : 0;

    if (isset($_GET['edit'])) {
        $id = (int)$_GET['edit'];
        $db->prepare("UPDATE offers SET title=?, description=?, badge_text=?, icon=?, sort_order=?, is_active=? WHERE id=?")
            ->execute([$title, $description, $badgeText, $icon, $sortOrder, $isActive, $id]);
        flash('success', 'Offer updated!');
    } else {
        $db->prepare("INSERT INTO offers (title, description, badge_text, icon, sort_order, is_active) VALUES (?, ?, ?, ?, ?, ?)")
            ->execute([$title, $description, $badgeText, $icon, $sortOrder, $isActive]);
        flash('success', 'Offer created!');
    }
    header('Location: offers.php');
    exit;
}

if (isset($_GET['delete'])) {
    $db->prepare("DELETE FROM offers WHERE id = ?")->execute([(int)$_GET['delete']]);
    flash('success', 'Offer deleted!');
    header('Location: offers.php');
    exit;
}

$offers = $db->query("SELECT * FROM offers ORDER BY sort_order, id")->fetchAll();
$editOffer = null;
if (isset($_GET['edit'])) {
    $stmt = $db->prepare("SELECT * FROM offers WHERE id = ?");
    $stmt->execute([(int)$_GET['edit']]);
    $editOffer = $stmt->fetch();
}

require_once __DIR__ . '/../includes/admin-header.php';
?>
<div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
    <div class="lg:col-span-2">
        <div class="bg-white rounded-xl border border-gray-200 p-6">
            <h3 class="font-semibold text-gray-800 mb-4">All Offers</h3>
            <?php if (count($offers) === 0): ?>
            <p class="text-sm text-gray-500">No offers yet. Add one to display on product pages.</p>
            <?php else: ?>
            <div class="space-y-3">
                <?php foreach ($offers as $o): ?>
                <div class="flex items-center gap-4 p-3 border border-gray-200 rounded-lg <?= $o['is_active'] ? '' : 'opacity-60' ?>">
                    <div class="w-10 h-10 bg-green-50 rounded-lg flex items-center justify-center text-green-600 shrink-0"><i class="fas <?= h($o['icon'] ?: 'fa-tag') ?>"></i></div>
                    <div class="flex-1 min-w-0">
                        <p class="font-medium text-sm text-gray-800"><?= h($o['title']) ?></p>
                        <p class="text-xs text-gray-500 truncate"><?= h($o['description']) ?></p>
                        <?php if ($o['badge_text']): ?><span class="inline-block text-[10px] bg-green-100 text-green-700 px-1.5 py-0.5 rounded mt-0.5 font-medium"><?= h($o['badge_text']) ?></span><?php endif; ?>
                    </div>
                    <div class="flex items-center gap-1 shrink-0">
                        <a href="offers.php?edit=<?= $o['id'] ?>" class="text-xs text-primary-600 hover:underline"><i class="fas fa-edit"></i></a>
                        <a href="offers.php?delete=<?= $o['id'] ?>" class="text-xs text-red-500 hover:underline" onclick="return confirm('Delete this offer?')"><i class="fas fa-trash"></i></a>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
            <?php endif; ?>
        </div>
    </div>
    <div>
        <div class="bg-white rounded-xl border border-gray-200 p-6">
            <h3 class="font-semibold text-gray-800 mb-4"><?= $editOffer ? 'Edit' : 'Add' ?> Offer</h3>
            <form method="POST">
                <div class="space-y-3">
                    <div><label class="block text-sm font-medium text-gray-700 mb-1">Title *</label><input type="text" name="title" value="<?= h($editOffer['title'] ?? '') ?>" required class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-1 focus:ring-primary-500"></div>
                    <div><label class="block text-sm font-medium text-gray-700 mb-1">Description</label><textarea name="description" rows="2" class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-1 focus:ring-primary-500"><?= h($editOffer['description'] ?? '') ?></textarea></div>
                    <div><label class="block text-sm font-medium text-gray-700 mb-1">Badge Text <span class="text-gray-400 font-normal">(e.g. Bank Offer)</span></label><input type="text" name="badge_text" value="<?= h($editOffer['badge_text'] ?? '') ?>" class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-1 focus:ring-primary-500"></div>
                    <div><label class="block text-sm font-medium text-gray-700 mb-1">Icon</label>
                        <select name="icon" class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-1 focus:ring-primary-500">
                            <option value="fa-tag" <?= ($editOffer['icon'] ?? '') === 'fa-tag' ? 'selected' : '' ?>>🏷️ Tag</option>
                            <option value="fa-percent" <?= ($editOffer['icon'] ?? '') === 'fa-percent' ? 'selected' : '' ?>>💯 Percent</option>
                            <option value="fa-gift" <?= ($editOffer['icon'] ?? '') === 'fa-gift' ? 'selected' : '' ?>>🎁 Gift</option>
                            <option value="fa-bolt" <?= ($editOffer['icon'] ?? '') === 'fa-bolt' ? 'selected' : '' ?>>⚡ Bolt</option>
                            <option value="fa-star" <?= ($editOffer['icon'] ?? '') === 'fa-star' ? 'selected' : '' ?>>⭐ Star</option>
                            <option value="fa-credit-card" <?= ($editOffer['icon'] ?? '') === 'fa-credit-card' ? 'selected' : '' ?>>💳 Card</option>
                            <option value="fa-truck" <?= ($editOffer['icon'] ?? '') === 'fa-truck' ? 'selected' : '' ?>>🚚 Truck</option>
                            <option value="fa-shield" <?= ($editOffer['icon'] ?? '') === 'fa-shield' ? 'selected' : '' ?>>🛡️ Shield</option>
                        </select>
                    </div>
                    <div><label class="block text-sm font-medium text-gray-700 mb-1">Sort Order</label><input type="number" name="sort_order" value="<?= h($editOffer['sort_order'] ?? '0') ?>" class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-1 focus:ring-primary-500"></div>
                    <label class="flex items-center gap-2"><input type="checkbox" name="is_active" <?= !isset($editOffer['is_active']) || $editOffer['is_active'] ? 'checked' : '' ?> class="rounded border-gray-300"> <span class="text-sm">Active</span></label>
                </div>
                <div class="mt-4 flex gap-2">
                    <button type="submit" class="flex-1 bg-primary-600 text-white py-2 rounded-lg text-sm font-semibold hover:bg-primary-700"><?= $editOffer ? 'Update' : 'Create' ?> Offer</button>
                    <?php if ($editOffer): ?><a href="offers.php" class="px-4 py-2 border border-gray-300 rounded-lg text-sm hover:bg-gray-50">Cancel</a><?php endif; ?>
                </div>
            </form>
        </div>
    </div>
</div>
<?php require_once __DIR__ . '/../includes/admin-footer.php'; ?>
