<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Content-Type");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Content-Type: application/json");
header("Access-Control-Max-Age: 86400");

require_once(__DIR__ . '/../../config.php');

 $data = json_decode(file_get_contents('php://input'), true);
 $id = $data['id'] ?? '';

if (empty($id)) {
    echo json_encode(['success' => false, 'message' => 'ID de orden requerido.']);
    exit;
}

// Primero verificamos que la orden exista
 $sql_check = "SELECT id FROM ordenes_pendientes WHERE id = ?";
 $stmt_check = $mysqli->prepare($sql_check);
 $stmt_check->bind_param("i", $id);
 $stmt_check->execute();
 $result_check = $stmt_check->get_result();

if ($result_check->num_rows === 0) {
    echo json_encode(['success' => false, 'message' => 'La orden no existe.']);
    exit;
}

// Eliminamos la orden
 $sql = "DELETE FROM ordenes_pendientes WHERE id = ?";
 $stmt = $mysqli->prepare($sql);
 $stmt->bind_param("i", $id);

if ($stmt->execute()) {
    echo json_encode(['success' => true, 'message' => 'Orden eliminada correctamente.']);
} else {
    echo json_encode(['success' => false, 'message' => 'Error al eliminar la orden: ' . $stmt->error]);
}

 $stmt->close();
 $stmt_check->close();
 $mysqli->close();
?>