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

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

$campaign_id = intval($_GET['campaign_id'] ?? 0);
$user_id     = intval($_SESSION['user_id']);

// Lead con teléfono que no haya sido llamado hoy por este agente
$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
LEFT JOIN call_logs cl ON cl.lead_id = l.id
    AND cl.user_id = '$user_id'
    AND DATE(cl.created_at) = CURDATE()
WHERE l.campaign_id = '$campaign_id'
  AND l.phone IS NOT NULL AND l.phone != ''
  AND l.in_cartera = 0
  AND cl.id IS NULL
ORDER BY l.id ASC
LIMIT 1
")->fetch_assoc();

$extra = [];
if(!empty($lead['extra_data'])){
    $extra = json_decode($lead['extra_data'], true) ?: [];
}
$lead['extra_fields'] = $extra;
unset($lead['extra_data']);

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