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

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

$agent   = $_SESSION['vici_agent'] ?? ('agente'.intval($_SESSION['user_id']));
$user_id = intval($_SESSION['user_id']);

// Consultar VICIdial si hay llamada activa para el agente
$result = vicidial_api([
    'function'   => 'agent_status',
    'agent_user' => $agent,
]);

// Parsear respuesta: lead_id, phone, status
$response = $result['response'] ?? '';
$lead_id  = null;

if(preg_match('/lead_id=(\d+)/i', $response, $m)){
    $lead_id = intval($m[1]);
}

if(!$lead_id){
    echo json_encode(['success'=>true, 'lead'=>null]);
    exit;
}

$lead = $conn->query("
SELECT l.id, l.full_name, l.phone, l.email, l.document_number, c.campaign_name
FROM leads l
LEFT JOIN campaigns c ON c.id = l.campaign_id
WHERE l.id = '$lead_id'
LIMIT 1
")->fetch_assoc();

// Crear log
$log_id = null;
if($lead){
    $phone = $conn->real_escape_string($lead['phone']);
    $conn->query("
    INSERT INTO call_logs (lead_id, user_id, phone, type)
    VALUES ('$lead_id','$user_id','$phone','predictive')
    ");
    $log_id = $conn->insert_id;
}

echo json_encode(['success'=>true, 'lead'=>$lead, 'log_id'=>$log_id]);
