<?php
// banner_delete.php – delete a banner (redirect-friendly version)

// Load only the database, helpers, and auth – no HTML output yet
require_once '../config/database.php';
require_once '../includes/functions.php';
require_once '../includes/auth.php';
requireLogin();

$id = $_GET['id'] ?? null;
if ($id) {
    // Fetch banner to get image_url
    $stmt = $pdo->prepare("SELECT image_url FROM banners WHERE id = :id");
    $stmt->execute([':id' => $id]);
    $banner = $stmt->fetch();

    if ($banner) {
        // Delete the banner record
        $pdo->prepare("DELETE FROM banners WHERE id = :id")->execute([':id' => $id]);

        // Delete the image file if it exists
        if (!empty($banner['image_url'])) {
            $imagePath = $banner['image_url'];

            // If it's a full URL, extract the filename; otherwise treat as simple filename
            if (filter_var($imagePath, FILTER_VALIDATE_URL)) {
                $filename = basename(parse_url($imagePath, PHP_URL_PATH));
            } else {
                $filename = $imagePath;
            }

            if (!empty($filename)) {
                deleteFile('../assets/uploads/' . $filename);
            }
        }

        setFlash('success', 'Banner deleted.');
    } else {
        setFlash('danger', 'Banner not found.');
    }
} else {
    setFlash('danger', 'Invalid request.');
}

// Now redirect – no output has been sent yet, so this will always work
header('Location: banners.php');
exit;