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

try {
    require_once __DIR__ . '/../core/api.php';
    
    if (isset($pdo)) $pdo->exec("SET NAMES 'utf8mb4'");

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

    if (!isset($data['id']) || !isset($data['status'])) {
        throw new Exception('Datos incompletos.');
    }

    $id = filter_var($data['id'], FILTER_VALIDATE_INT);
    $status = trim($data['status']); 
    $lost_reason = isset($data['lost_reason']) ? trim($data['lost_reason']) : null;

    $status_lower = mb_strtolower($status, 'UTF-8');
    
    // Si es pérdida, guardamos la razón.
    if ($status_lower === 'descartado' || strpos($status_lower, 'perdida') !== false || $status_lower === 'lost') {
        $stmt = $pdo->prepare("UPDATE leads SET status = ?, lost_reason = ?, updated_at = NOW() WHERE id = ?");
        $stmt->execute([$status, $lost_reason, $id]);
    } else {
        $stmt = $pdo->prepare("UPDATE leads SET status = ?, lost_reason = NULL, updated_at = NOW() WHERE id = ?");
        $stmt->execute([$status, $id]);
    }

    $response = ['success' => true, 'message' => 'ESTADO ACTUALIZADO'];

} catch (PDOException $e) {
    if (strpos($e->getMessage(), 'Unknown column') !== false && strpos($e->getMessage(), 'lost_reason') !== false) {
        $response = ['success' => false, 'message' => 'Error: Falta la columna "lost_reason" en la tabla leads.'];
    } else {
        error_log("Error PDO Funnel: " . $e->getMessage());
        $response = ['success' => false, 'message' => 'Error de Base de Datos.'];
    }
} catch (Exception $e) {
    $response = ['success' => false, 'message' => $e->getMessage()];
}

if (ob_get_length()) ob_clean();
echo json_encode($response);
exit;
?>