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

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

// Obtener config de la campaña
$cfg = $conn->query("SELECT * FROM vici_campaign_config WHERE campaign_id='$campaign_id' LIMIT 1")->fetch_assoc();
if(!$cfg){ echo json_encode(['success'=>false,'error'=>'Sin configuración VICIdial']); exit; }

$result = vicidial_api([
    'function'    => 'agent_login',
    'agent_user'  => $agent,
    'campaign_id' => $cfg['vici_campaign'],
    'dial_method' => strtoupper($cfg['dial_mode']),
]);

echo json_encode(['success'=>$result['success'], 'response'=>$result['response']??'']);
