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

try {
    require_once __DIR__ . '/../core/api.php';

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

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

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

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

    $stmt = $pdo->prepare("DELETE FROM leads WHERE id = ?");
    $stmt->execute([$id]);

    if ($stmt->rowCount() > 0) {
        $response = ['success' => true, 'message' => 'PROSPECTO ELIMINADO'];
    } else {
        $response = ['success' => false, 'message' => 'EL PROSPECTO NO EXISTIA O YA FUE BORRADO'];
    }

} catch (PDOException $e) {
    error_log("Error PDO en leads-delete.php: " . $e->getMessage());
    $response = ['success' => false, 'message' => 'ERROR DE BASE DE DATOS'];
} catch (Exception $e) {
    $response = ['success' => false, 'message' => $e->getMessage()];
}

if (ob_get_level() > 0) {
    ob_end_clean();
}
echo json_encode($response);
exit;
?>