<?php
require_once('../config/db.php');

$ProductID = $_POST['ProductID'] ?? '';

if (!$ProductID) {
    header("Location: ../products.php?error=no_id");
    exit;
}

// Check if product exists in sales
$stmt = $pdo->prepare("SELECT COUNT(*) FROM sale_items WHERE ProductID = ?");
$stmt->execute([$ProductID]);
$usedCount = $stmt->fetchColumn();

if ($usedCount > 0) {
    header("Location: ../products.php?error=in_use");
    exit;
}

// Get photo to delete
$stmt = $pdo->prepare("SELECT Photo FROM products WHERE ProductID = ?");
$stmt->execute([$ProductID]);
$photo = $stmt->fetchColumn();

// Delete product
$stmt = $pdo->prepare("DELETE FROM products WHERE ProductID = ?");
$stmt->execute([$ProductID]);

// Delete photo file
if ($photo && file_exists("../uploads/" . $photo)) {
    unlink("../uploads/" . $photo);
}

header("Location: ../products.php?success=deleted");
exit;
