<?php
require_once '../config.php';

session_start();

if (!isset($_SESSION['admin_logged_in'])) {
    header('Location: login.php');
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['id'])) {
    $conn = getDBConnection();
    $id = intval($_POST['id']);
    
    $sql = "SELECT filename FROM images WHERE id = $id";
    $result = $conn->query($sql);
    
    if ($result->num_rows === 1) {
        $row = $result->fetch_assoc();
        $filePath = "../uploads/" . $row['filename'];
        
        $deleteSql = "DELETE FROM images WHERE id = $id";
        if ($conn->query($deleteSql)) {
            if (file_exists($filePath)) {
                unlink($filePath);
            }
            $_SESSION['delete_success'] = true;
        }
    }
    
    $conn->close();
}

header('Location: index.php');
exit;