<?php
include 'db_connection.php'; // Your database connection script

header('Content-Type: application/json');

// Check if the request method is POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405); // Method Not Allowed
    echo json_encode(['success' => false, 'message' => 'Método no permitido. Se esperaba POST.']);
    exit;
}

// Get the raw POST data
$inputJSON = file_get_contents('php://input');
// Decode the JSON data
$data = json_decode($inputJSON, true);

// Check if 'id' is provided and is a valid integer
if (!isset($data['id']) || !is_numeric($data['id']) || intval($data['id']) <= 0) {
    http_response_code(400); // Bad Request
    echo json_encode(['success' => false, 'message' => 'ID de producto no proporcionado o no válido.']);
    exit;
}

$id = intval($data['id']);

// Prepare SQL statement to prevent SQL injection
$sql = "DELETE FROM productos WHERE id = ?";
$stmt = $conn->prepare($sql);

if (!$stmt) {
    http_response_code(500); // Internal Server Error
    echo json_encode(['success' => false, 'message' => 'Error al preparar la consulta de eliminación: ' . $conn->error]);
    exit;
}

// Bind the product ID to the statement
$stmt->bind_param('i', $id);

// Execute the statement
if ($stmt->execute()) {
    if ($stmt->affected_rows > 0) {
        echo json_encode(['success' => true, 'message' => 'Producto eliminado exitosamente.']);
    } else {
        // No rows affected could mean the product ID didn't exist
        http_response_code(404); // Not Found
        echo json_encode(['success' => false, 'message' => 'Producto no encontrado o ya había sido eliminado.']);
    }
} else {
    http_response_code(500); // Internal Server Error
    echo json_encode(['success' => false, 'message' => 'Error al eliminar el producto: ' . $stmt->error]);
}

// Close statement and connection
$stmt->close();
$conn->close();
?>