
<?php

// This block of PHP code, which handles the delete action and a subsequent redirect,
// must be executed before any HTML is sent to the browser.
session_start();
include_once("../config/db.php");

// Security: Ensure user is an admin before performing any action.
if(!isset($_SESSION['admin'])){
    header("Location: login.php");
    exit();
}

if(isset($_GET['delete'])){
    $id = $_GET['delete'];

    // First, get the image filename to delete the file from the server
    $select_stmt = mysqli_prepare($conn, "SELECT image FROM gallery WHERE id=?");
    mysqli_stmt_bind_param($select_stmt, "i", $id);
    mysqli_stmt_execute($select_stmt);
    $result = mysqli_stmt_get_result($select_stmt);
    if($row = mysqli_fetch_assoc($result)){
        $image_path = "uploads/" . $row['image'];
        if(file_exists($image_path)){
            unlink($image_path); // Delete the file
        }
    }

    // Security: Use prepared statements to prevent SQL injection
    $stmt = mysqli_prepare($conn, "DELETE FROM gallery WHERE id=?");
    mysqli_stmt_bind_param($stmt, "i", $id);
    mysqli_stmt_execute($stmt);
    header("Location: manage_gallery.php"); // Redirect to avoid re-deleting on refresh
    exit();
}

include 'admin_header.php';

$result = mysqli_query($conn,"SELECT * FROM gallery ORDER BY id DESC");
?>
<div class="page-header">
    <h1>Manage Gallery</h1>
    <a href="add_gallery.php" class="btn">Add New Image</a>
</div>

<?php if(mysqli_num_rows($result) > 0): ?>
    <div class="item-grid">
        <?php while($row = mysqli_fetch_assoc($result)): ?>
            <div class="item-card">
                <img src="uploads/<?php echo htmlspecialchars($row['image']); ?>" alt="Gallery Image" class="item-card-image">
                <div class="item-card-actions">
                    <a href="?delete=<?php echo $row['id']; ?>" class="delete" onclick="return confirm('Are you sure you want to delete this image?');">
                        <i class="fas fa-trash"></i> Delete
                    </a>
                </div>
            </div>
        <?php endwhile; ?>
    </div>
<?php else: ?>
    <div class="item-card" style="padding: 40px; text-align: center; color: var(--text-secondary);">
        <i class="fas fa-images" style="font-size: 48px; margin-bottom: 15px; opacity: 0.3;"></i>
        <p>No images found in the gallery. <a href="add_gallery.php">Add one now</a>.</p>
    </div>
<?php endif; ?>
<?php include 'admin_footer.php'; ?>
