<?php
session_start();
require_once __DIR__ . '/../includes/config.php';
requireAdminLogin();

$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if (!$id) { header('Location: ' . SITE_URL . '/admin/products.php'); exit; }

$db = getDB();
$product = $db->prepare("SELECT * FROM products WHERE id = ?");
$product->execute([$id]);
$product = $product->fetch();

if ($product) {
    // Delete all associated images from disk
    $images = $db->prepare("SELECT image_path FROM product_images WHERE product_id = ?");
    $images->execute([$id]);
    foreach ($images->fetchAll() as $img) {
        $filepath = UPLOAD_DIR . $img['image_path'];
        if (file_exists($filepath)) {
            @unlink($filepath);
        }
    }
    // Delete from DB (images cascade via FK)
    $db->prepare("DELETE FROM products WHERE id = ?")->execute([$id]);
    $_SESSION['flash'] = 'Product "' . $product['name'] . '" deleted successfully.';
} else {
    $_SESSION['flash'] = 'Product not found.';
}

header('Location: ' . SITE_URL . '/admin/products.php');
exit;
