<?php
// ------------------------------------------------------------
// 1. Load DB + helpers BEFORE any HTML
// ------------------------------------------------------------
require_once '../config/database.php';
require_once '../includes/functions.php';
require_once '../includes/auth.php';
requireLogin();

// ---------- Base URL for uploaded images ----------
$baseImageUrl = 'https://admin.vocabpanda.com/admin_panel/assets/uploads/';

$errors = [];

// ------------------------------------------------------------
// 2. Handle POST – redirect on success
// ------------------------------------------------------------
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $link_type  = $_POST['link_type'] ?? 'none';
    $link_value = trim($_POST['link_value'] ?? '');
    $sort_order = (int)($_POST['sort_order'] ?? 0);
    $is_active  = isset($_POST['is_active']) ? 1 : 0;

    // Image upload (required)
    $image_url = null;
    if (!empty($_FILES['image']['name'])) {
        $uploadedName = uploadFile(
            'image',
            ['image/jpeg', 'image/png', 'image/gif', 'image/webp'],
            '../assets/uploads/'
        );
        if ($uploadedName === false) {
            $errors[] = 'Image upload failed.';
        } else {
            $image_url = $baseImageUrl . $uploadedName;
        }
    } else {
        $errors[] = 'Banner image is required.';
    }

    if (empty($errors)) {
        $stmt = $pdo->prepare("INSERT INTO banners (image_url, link_type, link_value, sort_order, is_active)
                              VALUES (:img, :ltype, :lval, :sort, :active)");
        $stmt->execute([
            ':img'   => $image_url,
            ':ltype' => $link_type,
            ':lval'  => $link_value ?: null,
            ':sort'  => $sort_order,
            ':active'=> $is_active,
        ]);
        setFlash('success', 'Banner added successfully.');
        header('Location: banners.php');
        exit;
    }
    // If errors, continue to display the form (after the layout)
}
?>

<?php
// ------------------------------------------------------------
// 3. Now include the full layout (header + sidebar)
// ------------------------------------------------------------
require_once '../includes/header.php';
?>

<h1 class="h2 mb-4">Add Banner</h1>

<?php if ($errors): ?>
<div class="alert alert-danger"><ul class="mb-0"><?php foreach ($errors as $e) echo '<li>'.htmlspecialchars($e).'</li>'; ?></ul></div>
<?php endif; ?>

<div class="card shadow-sm">
    <div class="card-body">
        <form method="POST" enctype="multipart/form-data">
            <div class="row">
                <div class="col-md-6 mb-3">
                    <label class="form-label">Image *</label>
                    <input type="file" name="image" class="form-control" accept="image/*" required>
                </div>

                <div class="col-md-4 mb-3">
                    <label class="form-label">Link Type</label>
                    <select name="link_type" class="form-select">
                        <option value="none" <?= ($_POST['link_type'] ?? '') === 'none' ? 'selected' : '' ?>>None</option>
                        <option value="product" <?= ($_POST['link_type'] ?? '') === 'product' ? 'selected' : '' ?>>Product</option>
                        <option value="category" <?= ($_POST['link_type'] ?? '') === 'category' ? 'selected' : '' ?>>Category</option>
                        <option value="url" <?= ($_POST['link_type'] ?? '') === 'url' ? 'selected' : '' ?>>External URL</option>
                    </select>
                </div>

                <div class="col-md-4 mb-3">
                    <label class="form-label">Link Value (id/slug/url)</label>
                    <input type="text" name="link_value" class="form-control" value="<?= htmlspecialchars($_POST['link_value'] ?? '') ?>">
                </div>

                <div class="col-md-2 mb-3">
                    <label class="form-label">Sort Order</label>
                    <input type="number" name="sort_order" class="form-control" value="<?= htmlspecialchars($_POST['sort_order'] ?? '0') ?>">
                </div>

                <div class="col-md-2 mb-3 d-flex align-items-end">
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" name="is_active" id="is_active" <?= isset($_POST['is_active']) ? 'checked' : '' ?>>
                        <label class="form-check-label" for="is_active">Active</label>
                    </div>
                </div>
            </div>
            <button type="submit" class="btn btn-primary"><i class="bi bi-save"></i> Save Banner</button>
            <a href="banners.php" class="btn btn-secondary">Cancel</a>
        </form>
    </div>
</div>

<?php require_once '../includes/footer.php'; ?>