<?php
session_start();
header('Content-Type: application/json');
include '../../config/db.php';

if(!isset($_SESSION['user_id'])){ echo json_encode(['success'=>false]); exit; }

$lead_id     = intval($_POST['lead_id'] ?? 0);
$log_id      = intval($_POST['log_id'] ?? 0);
$code        = $conn->real_escape_string($_POST['code'] ?? '');
$campaign_id = intval($_POST['campaign_id'] ?? 0);
$user_id     = intval($_SESSION['user_id']);

// Actualizar call_log
if($log_id){
    $conn->query("UPDATE call_logs SET disposition='$code' WHERE id='$log_id'");
}

// Guardar nota autom¨˘tica
$note = $conn->real_escape_string("Tipificaci¨Žn: $code");
$conn->query("INSERT INTO lead_notes (lead_id, user_id, note) VALUES ('$lead_id','$user_id','$note')");

// Marcar como gestionado
$conn->query("
CREATE TABLE IF NOT EXISTS lead_managed (
    id INT AUTO_INCREMENT PRIMARY KEY,
    lead_id INT, user_id INT, campaign_id INT,
    disposition VARCHAR(20), managed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)");
$conn->query("INSERT INTO lead_managed (lead_id, user_id, campaign_id, disposition)
VALUES ('$lead_id','$user_id','$campaign_id','$code')");

// Si es SALE marcar in_cartera=1 y asignar al agente
if(in_array($code, ['SALE','VENTA','sale','venta']) && $lead_id){
    $conn->query("UPDATE leads SET in_cartera=1, assigned_user_id='$user_id', advisor_id='$user_id', status='Vendido' WHERE id='$lead_id'");
}

echo json_encode(['success'=>true]);