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

require_once '../src/config/db.php';

if (!isset($_GET['id']) || empty($_GET['id'])) {
    header('Location: sliders.php');
    exit;
}

$id = (int)$_GET['id'];

try {
    // First, get the image URL to delete the file
    $stmt = $pdo->prepare("SELECT image_url FROM sliders WHERE id = ?");
    $stmt->execute([$id]);
    $slider = $stmt->fetch();

    if ($slider && !empty($slider['image_url'])) {
        $imagePath = '../public/' . $slider['image_url'];
        if (file_exists($imagePath)) {
            unlink($imagePath);
        }
    }

    $deleteStmt = $pdo->prepare('DELETE FROM sliders WHERE id = ?');
    $deleteStmt->execute([$id]);
    header('Location: sliders.php?success=delete');
    exit;
} catch (PDOException $e) {
    error_log("Error deleting slider: " . $e->getMessage());
    header('Location: sliders.php?error=delete_failed');
    exit;
}
