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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $title = $_POST['title'] ?? '';
    $subtitle = $_POST['subtitle'] ?? '';
    $link = $_POST['link'] ?? '';
    $btnText = $_POST['btn_text'] ?? '';
    $sortOrder = (int)($_POST['sort_order'] ?? 0);
    $isActive = isset($_POST['is_active']) ? 1 : 0;
    
    $image = '';
    if (!empty($_FILES['image']['name']) && $_FILES['image']['error'] === 0) {
        $ext = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
        $filename = 'banner_' . uniqid() . '.' . $ext;
        move_uploaded_file($_FILES['image']['tmp_name'], __DIR__ . '/../assets/uploads/banners/' . $filename);
        $image = 'assets/uploads/banners/' . $filename;
    }
    
    if (isset($_GET['edit'])) {
        $id = (int)$_GET['edit'];
        if ($image) {
            $db->prepare("UPDATE banners SET title=?, subtitle=?, image=?, link=?, btn_text=?, sort_order=?, is_active=? WHERE id=?")
                ->execute([$title, $subtitle, $image, $link, $btnText, $sortOrder, $isActive, $id]);
        } else {
            $db->prepare("UPDATE banners SET title=?, subtitle=?, link=?, btn_text=?, sort_order=?, is_active=? WHERE id=?")
                ->execute([$title, $subtitle, $link, $btnText, $sortOrder, $isActive, $id]);
        }
        flash('success', 'Banner updated!');
    } else {
        $db->prepare("INSERT INTO banners (title, subtitle, image, link, btn_text, sort_order, is_active) VALUES (?, ?, ?, ?, ?, ?, ?)")
            ->execute([$title, $subtitle, $image ?: 'assets/uploads/banners/placeholder.svg', $link, $btnText, $sortOrder, $isActive]);
        flash('success', 'Banner created!');
    }
    header('Location: banners.php');
    exit;
}

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

$banners = $db->query("SELECT * FROM banners ORDER BY sort_order")->fetchAll();
$editBanner = null;
if (isset($_GET['edit'])) {
    $stmt = $db->prepare("SELECT * FROM banners WHERE id = ?");
    $stmt->execute([(int)$_GET['edit']]);
    $editBanner = $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 overflow-hidden">
            <table class="w-full text-sm">
                <thead><tr class="text-left bg-gray-50 text-gray-500"><th class="px-4 py-3 font-medium">Image</th><th class="px-4 py-3 font-medium">Title</th><th class="px-4 py-3 font-medium">Link</th><th class="px-4 py-3 font-medium">Order</th><th class="px-4 py-3 font-medium">Status</th><th class="px-4 py-3 font-medium"></th></tr></thead>
                <tbody>
                    <?php foreach ($banners as $b): ?>
                    <tr class="border-t">
                        <td class="px-4 py-3"><div class="w-16 h-10 bg-gray-50 rounded overflow-hidden"><img src="../<?= h($b['image']) ?>" alt="" class="w-full h-full object-cover"></div></td>
                        <td class="px-4 py-3 font-medium"><?= h($b['title']) ?></td>
                        <td class="px-4 py-3 text-xs text-gray-500"><?= h($b['link'] ?: '-') ?></td>
                        <td class="px-4 py-3"><?= $b['sort_order'] ?></td>
                        <td class="px-4 py-3"><?= $b['is_active'] ? '<span class="text-green-600 text-xs font-medium">Active</span>' : '<span class="text-gray-400 text-xs font-medium">Inactive</span>' ?></td>
                        <td class="px-4 py-3"><a href="banners.php?edit=<?= $b['id'] ?>" class="text-primary-600 hover:underline text-xs mr-2">Edit</a><a href="banners.php?delete=<?= $b['id'] ?>" class="text-red-500 hover:underline text-xs" onclick="return confirm('Delete?')">Delete</a></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
    <div>
        <form method="POST" enctype="multipart/form-data" class="bg-white rounded-xl border border-gray-200 p-6">
            <h3 class="font-semibold text-gray-800 mb-4"><?= $editBanner ? 'Edit Banner' : 'Add Banner' ?></h3>
            <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($editBanner['title'] ?? '') ?>" class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm"></div>
                <div><label class="block text-sm font-medium text-gray-700 mb-1">Subtitle</label><input type="text" name="subtitle" value="<?= h($editBanner['subtitle'] ?? '') ?>" class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm"></div>
                <div><label class="block text-sm font-medium text-gray-700 mb-1">Image</label><input type="file" name="image" accept="image/*" class="w-full text-sm"></div>
                <div><label class="block text-sm font-medium text-gray-700 mb-1">Link URL</label><input type="text" name="link" value="<?= h($editBanner['link'] ?? '') ?>" class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm"></div>
                <div><label class="block text-sm font-medium text-gray-700 mb-1">Button Text</label><input type="text" name="btn_text" value="<?= h($editBanner['btn_text'] ?? '') ?>" class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm"></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($editBanner['sort_order'] ?? '0') ?>" class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm"></div>
                <label class="flex items-center gap-2"><input type="checkbox" name="is_active" <?= !isset($editBanner) || $editBanner['is_active'] ? 'checked' : '' ?> class="rounded border-gray-300"> <span class="text-sm">Active</span></label>
                <button type="submit" class="w-full bg-primary-600 text-white py-2 rounded-lg text-sm font-semibold hover:bg-primary-700"><?= $editBanner ? 'Update Banner' : 'Add Banner' ?></button>
                <?php if ($editBanner): ?><a href="banners.php" class="block text-center text-sm text-gray-500 mt-2 hover:underline">Cancel</a><?php endif; ?>
            </div>
        </form>
    </div>
</div>
<?php require_once __DIR__ . '/../includes/admin-footer.php'; ?>
