<?php
header("Content-Type: application/json");
error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once 'auth_guard.php';
require_once '../config/database.php';
$db = getDB();

$data = json_decode(file_get_contents("php://input"), true);
$product_id = isset($data['id']) ? intval($data['id']) : 0;

if ($product_id <= 0) {
    echo json_encode(["success" => false, "message" => "Invalid product reference identifier"]);
    exit;
}

// Safely delete relational section tags first, then clear core product record
$db->query("DELETE FROM section_products WHERE product_id = $product_id");
$delete = $db->query("DELETE FROM products WHERE id = $product_id");

if ($delete) {
    echo json_encode(["success" => true, "message" => "Product deleted from inventory catalog cleanly"]);
} else {
    echo json_encode(["success" => false, "message" => "Deletion failed: " . $db->error]);
}