<?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);

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

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

    if (
        !isset($data['id']) || empty(trim($data['id'])) ||
        !isset($data['status']) || empty(trim($data['status']))
    ) {
        throw new Exception('DATOS INCOMPLETOS');
    }

    $lead_id = filter_var($data['id'], FILTER_VALIDATE_INT);
    $new_status = filter_var($data['status'], FILTER_SANITIZE_FULL_SPECIAL_CHARS);

    if ($lead_id === false) {
        throw new Exception('ID INVALIDO');
    }

    $stmt = $pdo->prepare("
        UPDATE leads SET
            status = :status,
            updated_at = NOW()
        WHERE id = :id
    ");

    $stmt->bindParam(':status', $new_status);
    $stmt->bindParam(':id', $lead_id);

    if ($stmt->execute()) {
        $response['success'] = true;
        $response['message'] = 'ESTADO ACTUALIZADO';
    } else {
        error_log("Error al actualizar estado de leads en leads-update-status.php: " . implode(" ", $stmt->errorInfo()));
        $response['message'] = 'FALLO AL ACTUALIZAR ESTADO';
    }

} catch (PDOException $e) {
    error_log("PDOException en leads-update-status.php: " . $e->getMessage());
    $response['message'] = 'ERROR DE BASE DE DATOS';
} catch (Exception $e) {
    error_log("General Error en leads-update-status.php: " . $e->getMessage());
    $response['message'] = strtoupper($e->getMessage());
}

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