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

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

$user_id     = intval($_SESSION['user_id']);
$lead_id     = intval($_POST['lead_id']     ?? 0);
$phone       = trim($_POST['phone']         ?? '');
$campaign_id = intval($_POST['campaign_id'] ?? 0);

if(empty($phone)){
    echo json_encode(['success'=>false,'error'=>'Telefono requerido']);
    exit;
}

$phone = preg_replace('/[^0-9]/', '', $phone);
if(substr($phone, 0, 2) !== '34' && substr($phone, 0, 2) !== '57'){
    $phone = '34' . $phone;
}

$vici_host = '164.132.41.206';
$url = 'http://' . $vici_host . '/originate.php?secret=wolfxell2026&phone=' . urlencode($phone);

$ch = curl_init($url);
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT        => 15,
    CURLOPT_CONNECTTIMEOUT => 10,
]);
$response = curl_exec($ch);
$error    = curl_error($ch);
curl_close($ch);

if($error){
    echo json_encode(['success'=>false,'error'=>'Error conexion VICIdial: '.$error]);
    exit;
}

$data = json_decode($response, true);
if($data === null){
    echo json_encode(['success'=>false,'error'=>'Respuesta invalida de VICIdial: '.$response]);
    exit;
}

$stmt = $conn->prepare("INSERT INTO call_logs (lead_id, user_id, campaign_id, phone, disposition, duration_sec, created_at) VALUES (?, ?, ?, ?, 'CALLING', 0, NOW())");
$stmt->bind_param("iiis", $lead_id, $user_id, $campaign_id, $phone);
$stmt->execute();
$log_id = $conn->insert_id;

// Registrar en activity_logs
$desc = $conn->real_escape_string("Llamada manual iniciada al número $phone");
$conn->query("INSERT INTO activity_logs (user_id, action_type, description, created_at) VALUES ('$user_id', 'call_manual', '$desc', NOW())");

echo json_encode([
    'success' => $data['success'] ?? false,
    'log_id'  => $log_id,
]);