<?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: services.php');
    exit;
}

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

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

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

    // Then, delete the record from the database
    $deleteStmt = $pdo->prepare("DELETE FROM services WHERE id = ?");
    $deleteStmt->execute([$id]);

    header('Location: services.php?success=delete');
    exit;
} catch (PDOException $e) {
    // Optional: Log the error and redirect with an error message
    error_log("Error deleting service: " . $e->getMessage());
    header('Location: services.php?error=delete_failed');
    exit;
}