<?php
require_once '../config/database.php';
require_once '../includes/functions.php';
require_once '../includes/auth.php';
requireLogin();

$id = $_GET['id'] ?? null;
if ($id) {
    $stmt = $pdo->prepare("SELECT thumbnail_url FROM products WHERE id = :id");
    $stmt->execute([':id' => $id]);
    $product = $stmt->fetch();

    if ($product) {
        // Delete additional images
        $imgStmt = $pdo->prepare("SELECT image_url FROM product_images WHERE product_id = :pid");
        $imgStmt->execute([':pid' => $id]);
        $urls = $imgStmt->fetchAll(PDO::FETCH_COLUMN);

        foreach ($urls as $url) {
            $filename = basename(parse_url($url, PHP_URL_PATH));
            if ($filename) deleteFile('../assets/uploads/' . $filename);
        }
        $pdo->prepare("DELETE FROM product_images WHERE product_id = :pid")->execute([':pid' => $id]);

        // Delete thumbnail
        if (!empty($product['thumbnail_url'])) {
            $thumbFile = basename(parse_url($product['thumbnail_url'], PHP_URL_PATH));
            if ($thumbFile) deleteFile('../assets/uploads/' . $thumbFile);
        }

        // Delete product
        $pdo->prepare("DELETE FROM products WHERE id = :id")->execute([':id' => $id]);

        setFlash('success', 'Product deleted.');
    } else {
        setFlash('danger', 'Product not found.');
    }
} else {
    setFlash('danger', 'Invalid request.');
}
header('Location: products.php');
exit;