<?php
// delete_product.php - Deletes a product using centralized connection

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

// --- 1. & 2. INCLUDE DATABASE CONNECTION ---
// This file provides the $pdo object
require_once 'db_connect.php'; 

// --- 3. GET PRODUCT ID FROM APP ---
if (!isset($_POST['id'])) {
    die(json_encode(['status' => 'error', 'message' => 'Product ID is missing.']));
}
$product_id = $_POST['id'];

// --- 4. DELETE FROM DATABASE ---
try {
    // Using a prepared statement to prevent SQL Injection
    $sql = "DELETE FROM products WHERE id = ?";
    $stmt = $pdo->prepare($sql);
    
    if ($stmt->execute([$product_id])) {
        // rowCount() tells us if the ID actually existed and was removed
        if ($stmt->rowCount() > 0) {
            echo json_encode(['status' => 'success', 'message' => 'Product deleted successfully.']);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'Product not found or already deleted.']);
        }
    }
} catch (PDOException $e) {
    // This catches SQL errors (like foreign key constraint violations)
    echo json_encode(['status' => 'error', 'message' => 'Database Error: ' . $e->getMessage()]);
}
?>