<?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/';

// ------------------------------------------------------------
// 2. Fetch the banner (and redirect if invalid)
// ------------------------------------------------------------
$id = $_GET['id'] ?? null;
if (!$id) {
    setFlash('danger', 'No banner ID provided.');
    header('Location: banners.php');
    exit;
}

$stmt = $pdo->prepare("SELECT * FROM banners WHERE id = :id");
$stmt->execute([':id' => $id]);
$banner = $stmt->fetch();
if (!$banner) {
    setFlash('danger', 'Banner not found.');
    header('Location: banners.php');
    exit;
}

$errors = [];

// ------------------------------------------------------------
// 3. Handle POST – update & 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;

    // Start with current full image URL
    $image_url = $banner['image_url'];

    // If a new file is uploaded
    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 {
            // Delete old file if it exists (extract filename from full URL)
            if ($image_url) {
                $filename = basename(parse_url($image_url, PHP_URL_PATH));
                deleteFile('../assets/uploads/' . $filename);
            }
            // Build full URL for storage
            $image_url = $baseImageUrl . $uploadedName;
        }
    }
    // Remove image if requested
    elseif (isset($_POST['remove_image']) && $_POST['remove_image'] == '1') {
        if ($image_url) {
            $filename = basename(parse_url($image_url, PHP_URL_PATH));
            deleteFile('../assets/uploads/' . $filename);
        }
        $image_url = null;
    }

    if (empty($errors)) {
        $upd = $pdo->prepare("UPDATE banners
            SET image_url=:img, link_type=:ltype,
                link_value=:lval, sort_order=:sort, is_active=:active
            WHERE id=:id");
        $upd->execute([
            ':img'    => $image_url,
            ':ltype'  => $link_type,
            ':lval'   => $link_value ?: null,
            ':sort'   => $sort_order,
            ':active' => $is_active,
            ':id'     => $id,
        ]);
        setFlash('success', 'Banner updated successfully.');
        header('Location: banners.php');
        exit;
    }

    // If errors, continue to display the form (after layout)
}
?>

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

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

<?php if ($errors): ?>
<div class="alert alert-danger">
    <ul class="mb-0">
        <?php foreach ($errors as $e): ?>
            <li><?= htmlspecialchars($e) ?></li>
        <?php endforeach; ?>
    </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>
                    <?php if ($banner['image_url']): ?>
                        <div class="mb-2">
                            <img src="<?= htmlspecialchars($banner['image_url']) ?>" width="120" class="rounded">
                            <div class="form-check mt-1">
                                <input class="form-check-input" type="checkbox" name="remove_image" value="1" id="remove_image">
                                <label class="form-check-label" for="remove_image">Remove image</label>
                            </div>
                        </div>
                    <?php endif; ?>
                    <input type="file" name="image" class="form-control" accept="image/*">
                    <small class="text-muted">Leave empty to keep current image</small>
                </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'] ?? $banner['link_type']) === 'none')     ? 'selected' : '' ?>>None</option>
                        <option value="product"  <?= (($_POST['link_type'] ?? $banner['link_type']) === 'product')  ? 'selected' : '' ?>>Product</option>
                        <option value="category" <?= (($_POST['link_type'] ?? $banner['link_type']) === 'category') ? 'selected' : '' ?>>Category</option>
                        <option value="url"      <?= (($_POST['link_type'] ?? $banner['link_type']) === 'url')      ? 'selected' : '' ?>>External URL</option>
                    </select>
                </div>

                <div class="col-md-4 mb-3">
                    <label class="form-label">Link Value</label>
                    <input type="text" name="link_value" class="form-control"
                           value="<?= htmlspecialchars($_POST['link_value'] ?? $banner['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'] ?? $banner['sort_order']) ?>">
                </div>

                <div class="col-md-2 mb-3 d-flex align-items-end">
                    <div class="form-check">
                        <?php $checked = ($_POST['is_active'] ?? $banner['is_active']) ? true : false; ?>
                        <input class="form-check-input" type="checkbox" name="is_active" id="is_active"
                               <?= $checked ? '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> Update Banner</button>
            <a href="banners.php" class="btn btn-secondary">Cancel</a>
        </form>
    </div>
</div>

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