<?php 
ob_start();
header('Content-Type: application/json');
$response = ['success' => false, 'message' => 'ERROR DESCONOCIDO'];

try {
    include_once 'db_connection.php';
    require_once '../files/guardiankey.php';

    ini_set('display_errors', 0);
    ini_set('log_errors', 1);
    ini_set('error_log', __DIR__ . '/../logs/php_errors.log');
    error_reporting(E_ALL);

    $data = json_decode(file_get_contents('php://input'), true);

    if (json_last_error() !== JSON_ERROR_NONE) {
        error_log("Error al decodificar JSON en quote-delete.php: " . json_last_error_msg());
        throw new Exception('ERROR AL PROCESAR DATOS');
    }

    if (empty($data['id'])) {
        throw new Exception('ID REQUERIDO');
    }

    $estimate_id = filter_var($data['id'], FILTER_VALIDATE_INT);
    if ($estimate_id === false) {
        throw new Exception('ID INVALIDO');
    }

    $pdo->beginTransaction(); 

    $sql = "DELETE FROM estimates WHERE id = ?";
    $stmt = $pdo->prepare($sql);

    if ($stmt->execute([$estimate_id])) {
        if ($stmt->rowCount() > 0) {
            $pdo->commit(); 
            $response = ['success' => true, 'message' => 'ESTIMADO ELIMINADO'];
        } else {
            $pdo->rollBack(); 
            $response = ['success' => false, 'message' => 'NO ENCONTRADO'];
        }
    } else {
        throw new Exception('FALLO LA EJECUCION DE ELIMINACION');
    }
} catch (PDOException $e) {
    if (isset($pdo) && $pdo->inTransaction()) { $pdo->rollBack(); }
    error_log("PDO Error en quote-delete.php: " . $e->getMessage());
    $response = ['success' => false, 'message' => 'ERROR DE BASE DE DATOS'];
} catch (Exception $e) {
    if (isset($pdo) && $pdo->inTransaction()) { $pdo->rollBack(); }
    error_log("General Error en quote-delete.php: " . $e->getMessage());
    $response = ['success' => false, 'message' => strtoupper($e->getMessage())];
}

if (ob_get_level() > 0) {
    ob_end_clean();
}
header('Content-Type: application/json');
echo json_encode($response);
exit;
?>