<?php
require_once __DIR__ . '/../includes/config.php';

if (!isLoggedIn()) {
    redirectWithMessage(APP_URL . '/login.php', 'Unauthorized', 'error');
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    redirectWithMessage(APP_URL . '/admin/products.php', 'Invalid request', 'error');
}

$id = (int)($_POST['id'] ?? 0);

if ($id <= 0) {
    redirectWithMessage(APP_URL . '/admin/products.php', 'Invalid product ID', 'error');
}

// Get product name before deleting
$product_result = $db->query("SELECT name FROM products WHERE id = $id");
$product_name = $product_result ? $product_result->fetch_assoc()['name'] : "Product #$id";

// Delete product
$query = "DELETE FROM products WHERE id = $id";

if ($db->query($query)) {
    auditLog('delete', 'products', $id, $product_name);
    redirectWithMessage(APP_URL . '/admin/products.php', 'Produs șters cu succes', 'success');
} else {
    redirectWithMessage(APP_URL . '/admin/products.php', 'Eroare la ștergere: ' . $db->error, 'error');
}
?>
