<?php
// Endpoint para actualizar el estado de un lead
session_start();
define('BASE_PATH', dirname(__DIR__, 2));
require_once BASE_PATH . '/database/config.php';
require_once BASE_PATH . '/database/connection.php';

function isLoggedIn() {
    return isset($_SESSION['user_id']) && !empty($_SESSION['user_id']);
}

header('Content-Type: application/json; charset=utf-8');

if (!isLoggedIn()) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'No autorizado']);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Método no permitido']);
    exit;
}

$lead_id = isset($_POST['lead_id']) ? intval($_POST['lead_id']) : 0;
$new_status = $_POST['status'] ?? '';
if ($lead_id <= 0 || $new_status === '') {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Parámetros inválidos']);
    exit;
}

$db = getDB();
// Migración defensiva: asegurar que leads.status no sea ENUM
try {
    $pdo = $db->getConnection();
    $stmtCol = $pdo->prepare("SELECT DATA_TYPE, COLUMN_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = ? AND TABLE_NAME = 'leads' AND COLUMN_NAME = 'status' LIMIT 1");
    $stmtCol->execute([DB_NAME]);
    $col = $stmtCol->fetch(PDO::FETCH_ASSOC);
    if ($col && (strtolower($col['DATA_TYPE'] ?? '') === 'enum' || stripos($col['COLUMN_TYPE'] ?? '', 'enum(') === 0)) {
        $pdo->exec("ALTER TABLE leads MODIFY status VARCHAR(50) NOT NULL DEFAULT 'new'");
    }
} catch (Exception $e) { /* continuar */ }

// Obtener estado actual
$lead = $db->selectOne("SELECT id, status, desk_id FROM leads WHERE id = ?", [$lead_id]);
if (!$lead) {
    http_response_code(404);
    echo json_encode(['success' => false, 'message' => 'Lead no encontrado']);
    exit;
}

$old_status = $lead['status'];
// Validar que el nuevo estado esté permitido para el desk del lead
$desk_id = intval($lead['desk_id'] ?? 0);
if ($desk_id <= 0) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'El lead no tiene desk asignado; no hay estados disponibles']);
    exit;
}

$allowedRows = $db->select("SELECT status FROM desk_allowed_statuses WHERE desk_id = ?", [$desk_id]);
$allowed = array_map(function($r){ return $r['status']; }, $allowedRows ?: []);
// Validar formato seguro de clave de estado
if (!is_string($new_status) || !preg_match('/^[a-z0-9_\-]{2,50}$/', $new_status)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Formato de estado inválido']);
    exit;
}
if (empty($allowed) || !in_array($new_status, $allowed, true)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Estado no permitido para el desk del lead']);
    exit;
}

try {
    // Actualizar estado del lead
    $db->execute("UPDATE leads SET status = ?, updated_at = NOW() WHERE id = ?", [$new_status, $lead_id]);

    // Registrar historial de cambios
    $db->execute(
        "INSERT INTO lead_status_history (lead_id, old_status, new_status, changed_by, notes) VALUES (?, ?, ?, ?, ?)",
        [$lead_id, $old_status, $new_status, $_SESSION['user_id'], null]
    );

    echo json_encode([
        'success' => true,
        'message' => 'Estado actualizado correctamente',
        'data' => [
            'lead_id' => $lead_id,
            'old_status' => $old_status,
            'new_status' => $new_status
        ]
    ]);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Error al actualizar estado', 'error' => $e->getMessage()]);
}
?>