<?php
session_start();
include("includes/db.php");

// Add Banner
if (isset($_POST['upload'])) {
    $image = $_FILES['banner']['name'];
    $tmp = $_FILES['banner']['tmp_name'];
    $path = "images/banners/" . basename($image);

    if (move_uploaded_file($tmp, $path)) {
        $insert = $con->prepare("INSERT INTO banners (image) VALUES (?)");
        $insert->bind_param("s", $image);
        $insert->execute();
    }
}

// Delete Banner
if (isset($_GET['delete'])) {
    $id = intval($_GET['delete']);
    $get = $con->prepare("SELECT image FROM banners WHERE id=?");
    $get->bind_param("i", $id);
    $get->execute();
    $result = $get->get_result()->fetch_assoc();
    if ($result) {
        unlink("images/banners/" . $result['image']);
        $con->query("DELETE FROM banners WHERE id=$id");
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Manage Banners</title>
    <style>
        body { font-family: Arial; padding: 20px; }
        form { margin-bottom: 30px; }
        .banner-list { display: grid; grid-template-columns: repeat(auto-fill,minmax(250px,1fr)); gap:20px; }
        .banner-card { border:1px solid #ccc; padding:10px; text-align:center; }
        img { max-width:100%; height:150px; object-fit:cover; border-radius:8px; }
        a.delete { color: red; font-weight: bold; text-decoration:none; }
    </style>
</head>
<body>
    <h1>Manage Banners</h1>

    <form action="" method="post" enctype="multipart/form-data">
        <input type="file" name="banner" required>
        <button type="submit" name="upload">Upload Banner</button>
    </form>

    <div class="banner-list">
        <?php
        $res = $con->query("SELECT * FROM banners ORDER BY id DESC");
        while ($row = $res->fetch_assoc()) {
            echo "<div class='banner-card'>
                    <img src='images/banners/{$row['image']}' alt='Banner'>
                    <br><a href='?delete={$row['id']}' class='delete'>Delete</a>
                  </div>";
        }
        ?>
    </div>
</body>
</html>
