<?php

session_start();

if(!isset($_SESSION['user_id'])){
    header("Location: /login.php");
    exit;
}

include("../config/db.php");
include("../includes/auth.php");

$user_id   = intval($_SESSION['user_id']);
$user_name = $_SESSION['name'] ?? 'Agente';

$mis_campanas = $conn->query("
SELECT
    c.id,
    c.campaign_name,
    COALESCE(vc.dial_mode,'manual')     AS dial_mode,
    COALESCE(vc.vici_campaign,'')       AS vici_campaign,
    COALESCE(vc.inbound,0)              AS inbound,
    COALESCE(t.sip_host,'')            AS sip_host,
    COALESCE(t.sip_user,'')            AS sip_user,
    COALESCE(t.sip_pass,'')            AS sip_pass,
    COALESCE(t.sip_port,8089)          AS sip_port
FROM campaigns c
INNER JOIN user_campaigns uc ON uc.campaign_id = c.id AND uc.user_id = '$user_id'
LEFT JOIN vici_campaign_config vc ON vc.campaign_id = c.id
LEFT JOIN vici_trunks t ON t.id = vc.trunk_id
ORDER BY c.campaign_name ASC
LIMIT 30
");

$campanas = [];
while($r = $mis_campanas->fetch_assoc()) $campanas[] = $r;

$hoy  = date('Y-m-d');
$kpis = $conn->query("
SELECT
    COUNT(*)                                            AS total,
    SUM(CASE WHEN disposition='SALE' THEN 1 ELSE 0 END) AS ventas,
    AVG(NULLIF(duration_sec,0))                         AS tmo,
    SUM(duration_sec)                                   AS tiempo_total
FROM call_logs
WHERE user_id='$user_id' AND DATE(created_at)='$hoy'
")->fetch_assoc();

?>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<title>Marcador — Wolfxell</title>
<link rel="stylesheet" href="/assets/css/style.css">
<link href="https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;600;700;800&family=DM+Mono:wght@400;500&display=swap" rel="stylesheet">
<script src="/assets/js/jssip.min.js"></script>
<style>
*{ box-sizing:border-box; margin:0; padding:0; }
:root{
    --green:#16a34a; --red:#dc2626; --amber:#f59e0b;
    --border:#e5e7eb; --bg:#f3f4f6; --muted:#6b7280; --text:#111827;
    --navy:#0f172a; --radius:10px;
    --font:'DM Sans',sans-serif; --mono:'DM Mono',monospace;
}
body{ font-family:var(--font); background:var(--bg); color:var(--text); }
.content-area{ margin-left:260px; display:flex; flex-direction:column; height:100vh; overflow:hidden; }
.marcador-topbar{ background:#fff; border-bottom:1px solid var(--border); height:56px; display:flex; align-items:center; padding:0 24px; gap:12px; flex-shrink:0; }
.btn-volver{ display:inline-flex; align-items:center; height:34px; padding:0 14px; border-radius:8px; background:var(--bg); color:var(--muted); text-decoration:none; font-weight:600; font-size:13px; border:1px solid var(--border); flex-shrink:0; }
.campaign-select-wrap{ position:relative; }
.campaign-select-wrap select{ height:34px; padding:0 32px 0 12px; border-radius:8px; border:1px solid var(--border); background:#fff; font-family:var(--font); font-size:14px; font-weight:600; color:var(--text); cursor:pointer; appearance:none; min-width:200px; }
.campaign-select-wrap::after{ content:'▾'; position:absolute; right:10px; top:50%; transform:translateY(-50%); font-size:11px; color:var(--muted); pointer-events:none; }
.topbar-tabs{ display:flex; margin-left:8px; }
.tab{ height:56px; padding:0 16px; font-size:13px; font-weight:500; color:var(--muted); cursor:pointer; border:none; background:none; border-bottom:2px solid transparent; transition:.15s; font-family:var(--font); }
.tab:hover{ color:var(--text); }
.tab.active{ color:var(--navy); border-bottom-color:var(--navy); font-weight:700; }
.topbar-right{ margin-left:auto; display:flex; align-items:center; gap:8px; }
.mode-pill{ display:flex; align-items:center; gap:6px; height:34px; padding:0 12px; border-radius:8px; border:1px solid var(--border); background:#fff; font-size:12px; font-weight:700; color:var(--muted); }
.mode-pill.ami{ color:#7c3aed; border-color:#ddd6fe; background:#faf5ff; }
.mode-pill.webrtc{ color:var(--green); border-color:#bbf7d0; background:#f0fdf4; }
.sip-pill{ display:flex; align-items:center; gap:6px; height:34px; padding:0 12px; border-radius:8px; border:1px solid var(--border); background:#fff; font-size:12px; font-weight:600; color:var(--muted); }
.sip-dot{ width:8px; height:8px; border-radius:50%; background:#d1d5db; }
.sip-pill.connected .sip-dot{ background:var(--green); animation:blink 2s infinite; }
.sip-pill.connected{ color:var(--green); border-color:#bbf7d0; }
.sip-pill.connecting .sip-dot{ background:var(--amber); animation:blink 1s infinite; }
.sip-pill.error .sip-dot{ background:var(--red); }
.sip-pill.error{ color:var(--red); border-color:#fecaca; }
@keyframes blink{ 0%,100%{ opacity:1; } 50%{ opacity:.4; } }
.btn-manual{ height:34px; padding:0 16px; border-radius:8px; border:1px solid var(--border); background:#fff; font-size:13px; font-weight:600; color:var(--text); cursor:pointer; font-family:var(--font); }
.agent-pill{ display:flex; align-items:center; gap:8px; height:34px; padding:0 12px; border-radius:8px; border:1px solid var(--border); background:#fff; font-size:13px; font-weight:600; cursor:pointer; }
.status-dot{ width:8px; height:8px; border-radius:50%; background:var(--green); }
.status-dot.pausa{ background:var(--amber); }
.status-dot.llamada{ background:var(--red); animation:blink 1s infinite; }
.marcador-content{ flex:1; overflow-y:auto; padding:20px 24px; background:var(--bg); }
.kpi-bar{ display:flex; gap:12px; margin-bottom:20px; }
.kpi{ background:#fff; border:1px solid var(--border); border-radius:var(--radius); padding:14px 18px; flex:1; }
.kpi-val{ font-size:28px; font-weight:800; color:var(--text); font-family:var(--mono); line-height:1; }
.kpi-val.green{ color:var(--green); }
.kpi-lbl{ font-size:11px; font-weight:600; color:var(--muted); text-transform:uppercase; letter-spacing:.6px; margin-top:4px; }
.empty-state{ display:flex; align-items:center; justify-content:center; min-height:300px; }
.empty-card{ background:#fff; border-radius:var(--radius); border:2px dashed var(--border); padding:48px 64px; text-align:center; color:var(--muted); font-size:14px; cursor:pointer; transition:.15s; max-width:480px; width:100%; }
.empty-card:hover{ border-color:var(--navy); color:var(--navy); }
.empty-card .icon{ font-size:36px; margin-bottom:12px; }
.empty-card strong{ display:block; font-size:16px; font-weight:700; color:var(--text); margin-bottom:6px; }
.white-card{ background:#fff; border-radius:var(--radius); border:1px solid var(--border); margin-bottom:16px; overflow:hidden; }
.lead-header{ padding:20px 24px; display:flex; align-items:center; justify-content:space-between; background:var(--navy); }
.lead-name{ font-size:20px; font-weight:800; color:#fff; }
.lead-phone-sub{ font-size:13px; color:rgba(255,255,255,.6); margin-top:2px; font-family:var(--mono); }
.call-timer-badge{ background:rgba(255,255,255,.15); color:#fff; font-size:22px; font-weight:700; padding:8px 20px; border-radius:8px; letter-spacing:3px; font-family:var(--mono); border:1px solid rgba(255,255,255,.2); }
.call-timer-badge.active{ background:var(--red); border-color:var(--red); }
.lead-fields{ padding:16px 24px; display:grid; grid-template-columns:repeat(auto-fit,minmax(160px,1fr)); gap:12px; border-bottom:1px solid var(--border); }
.lead-field label{ font-size:10px; font-weight:700; color:var(--muted); text-transform:uppercase; letter-spacing:.6px; display:block; margin-bottom:3px; }
.lead-field span{ font-size:14px; font-weight:600; color:var(--text); }
.call-controls{ padding:14px 24px; display:flex; align-items:center; gap:8px; border-bottom:1px solid var(--border); }
.ctrl-btn{ height:38px; padding:0 16px; border-radius:8px; border:1px solid var(--border); background:#fff; font-size:13px; font-weight:600; cursor:pointer; display:flex; align-items:center; gap:6px; font-family:var(--font); }
.ctrl-btn.red{ background:var(--red); color:#fff; border-color:var(--red); }
.ctrl-btn.muted-btn{ background:var(--amber); color:#fff; border-color:var(--amber); }
.disp-area{ padding:16px 24px; border-bottom:1px solid var(--border); }
.disp-label{ font-size:11px; font-weight:700; color:var(--muted); text-transform:uppercase; letter-spacing:.6px; margin-bottom:10px; }
.disp-grid{ display:flex; flex-wrap:wrap; gap:8px; }
.disp-btn{ height:36px; padding:0 16px; border-radius:20px; border:1.5px solid; font-size:13px; font-weight:600; cursor:pointer; background:#fff; font-family:var(--font); }
.disp-btn:hover{ transform:translateY(-1px); box-shadow:0 4px 12px rgba(0,0,0,.1); }
.nota-area{ padding:14px 24px; display:flex; gap:8px; }
.nota-input{ flex:1; height:38px; border:1px solid var(--border); border-radius:8px; padding:0 14px; font-size:14px; font-family:var(--font); background:#fff; color:var(--text); }
.nota-input:focus{ outline:none; border-color:var(--navy); }
.btn-nota{ height:38px; padding:0 16px; border-radius:8px; border:none; background:var(--navy); color:#fff; font-size:13px; font-weight:600; cursor:pointer; font-family:var(--font); }
.seg-table-wrap{ background:#fff; border-radius:var(--radius); border:1px solid var(--border); overflow:hidden; }
.seg-table-wrap table{ width:100%; border-collapse:collapse; }
.seg-table-wrap th{ background:var(--navy); color:#fff; text-align:left; padding:12px 16px; font-size:11px; font-weight:700; text-transform:uppercase; letter-spacing:.6px; }
.seg-table-wrap td{ padding:12px 16px; font-size:13px; border-bottom:1px solid var(--border); color:var(--text); }
.seg-table-wrap tr:last-child td{ border-bottom:none; }
.seg-table-wrap tr:hover td{ background:#f9fafb; }
.modal-overlay{ position:fixed; inset:0; background:rgba(0,0,0,.5); display:none; align-items:center; justify-content:center; z-index:1000; backdrop-filter:blur(4px); }
.modal-overlay.open{ display:flex; }
.modal-box{ background:#fff; border-radius:16px; padding:24px; width:340px; box-shadow:0 24px 64px rgba(0,0,0,.2); animation:modalIn .2s ease; }
@keyframes modalIn{ from{ transform:scale(.95) translateY(8px); opacity:0; } to{ transform:scale(1) translateY(0); opacity:1; } }
.modal-title{ font-size:16px; font-weight:800; margin-bottom:16px; color:var(--text); }
.dial-input-wrap{ position:relative; margin-bottom:14px; }
.dial-input{ width:100%; height:52px; border:2px solid var(--border); border-radius:10px; padding:0 44px 0 16px; font-size:22px; font-weight:700; font-family:var(--mono); color:var(--text); background:#fff; text-align:center; letter-spacing:2px; }
.dial-input:focus{ outline:none; border-color:var(--navy); }
.dial-input::placeholder{ color:#d1d5db; font-size:16px; letter-spacing:0; }
.dial-clear{ position:absolute; right:12px; top:50%; transform:translateY(-50%); background:none; border:none; font-size:18px; color:var(--muted); cursor:pointer; }
.dialpad{ display:grid; grid-template-columns:repeat(3,1fr); gap:8px; margin-bottom:14px; }
.dial-key{ height:52px; border-radius:10px; border:1px solid var(--border); background:#fff; font-size:20px; font-weight:700; cursor:pointer; color:var(--text); font-family:var(--mono); display:flex; flex-direction:column; align-items:center; justify-content:center; gap:2px; }
.dial-key:hover{ background:var(--bg); border-color:var(--navy); }
.dial-key:active{ transform:scale(.95); }
.dial-key .sub{ font-size:8px; color:var(--muted); font-family:var(--font); font-weight:600; letter-spacing:.5px; }
.modal-actions{ display:grid; grid-template-columns:1fr 1fr; gap:8px; }
.btn-call-now{ height:46px; border-radius:10px; border:none; background:var(--green); color:#fff; font-size:14px; font-weight:700; cursor:pointer; font-family:var(--font); }
.btn-cancel-modal{ height:46px; border-radius:10px; border:1px solid var(--border); background:#fff; font-size:14px; font-weight:700; cursor:pointer; color:var(--text); font-family:var(--font); }
.pausa-options{ display:flex; flex-direction:column; gap:6px; }
.pausa-opt{ height:42px; border-radius:8px; border:1px solid var(--border); background:#fff; font-size:14px; font-weight:600; cursor:pointer; text-align:left; padding:0 16px; color:var(--text); font-family:var(--font); }
.pausa-opt.continue{ color:var(--green); border-color:var(--green); }
.inbound-alert{ position:fixed; bottom:24px; right:24px; background:#fff; border-radius:14px; padding:18px 20px; box-shadow:0 20px 60px rgba(0,0,0,.2); z-index:2000; display:none; min-width:260px; border-left:4px solid var(--green); }
.inbound-label{ font-size:10px; font-weight:700; color:var(--muted); text-transform:uppercase; margin-bottom:4px; }
.inbound-number{ font-size:22px; font-weight:800; color:var(--text); margin-bottom:14px; font-family:var(--mono); }
.inbound-btns{ display:flex; gap:8px; }
.btn-answer{ flex:1; height:38px; border-radius:8px; border:none; background:var(--green); color:#fff; font-weight:700; font-size:13px; cursor:pointer; font-family:var(--font); }
.btn-reject{ flex:1; height:38px; border-radius:8px; border:none; background:var(--red); color:#fff; font-weight:700; font-size:13px; cursor:pointer; font-family:var(--font); }
.ami-notice{ background:#faf5ff; border:1px solid #ddd6fe; border-radius:8px; padding:10px 14px; font-size:12px; color:#7c3aed; font-weight:600; margin-bottom:4px; display:flex; align-items:center; gap:6px; }
.toast{ position:fixed; top:70px; right:24px; background:var(--navy); color:#fff; border-radius:10px; padding:12px 18px; font-size:13px; font-weight:600; z-index:3000; display:none; animation:toastIn .2s ease; max-width:300px; }
.toast.show{ display:block; }
.toast.success{ background:var(--green); }
.toast.error{ background:var(--red); }
@keyframes toastIn{ from{ transform:translateY(-10px); opacity:0; } to{ transform:translateY(0); opacity:1; } }
#remoteAudio{ display:none; }
</style>
</head>
<body>
<audio id="remoteAudio" autoplay></audio>
<div class="toast" id="toast"></div>
<?php include("../includes/sidebar.php"); ?>
<div class="content-area">
    <div class="marcador-topbar">
        <a href="/pages/dashboard.php" class="btn-volver">← Volver</a>
        <div class="campaign-select-wrap">
            <select id="campaign-select" onchange="cambiarCampana(this)">
                <option value="">— Seleccionar campaña —</option>
                <?php foreach($campanas as $c): ?>
                <option value="<?= $c['id'] ?>"
                    data-mode="<?= $c['dial_mode'] ?>"
                    data-host="<?= htmlspecialchars($c['sip_host']) ?>"
                    data-user="<?= htmlspecialchars($c['sip_user']) ?>"
                    data-pass="<?= htmlspecialchars($c['sip_pass']) ?>"
                    data-port="<?= $c['sip_port'] ?>"
                ><?= htmlspecialchars($c['campaign_name']) ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="topbar-tabs">
            <button class="tab active" onclick="cambiarTab('general')">Vista general</button>
            <button class="tab" onclick="cambiarTab('seguimiento')">Seguimiento</button>
            <button class="tab" onclick="cambiarTab('entrante')">Entrante</button>
        </div>
        <div class="topbar-right">
            <div class="mode-pill" id="mode-pill">— Sin campaña</div>
            <div class="sip-pill" id="sip-indicator">
                <span class="sip-dot"></span>
                <span id="sip-label">Desconectado</span>
            </div>
            <button class="btn-manual" onclick="abrirMarcadorManual()">📞 Llamada manual</button>
            <div class="agent-pill" onclick="abrirPausa()">
                <span class="status-dot" id="status-dot"></span>
                <span><?= htmlspecialchars($user_name) ?></span>
                <span style="color:var(--muted);font-size:10px;margin-left:2px">▾</span>
            </div>
        </div>
    </div>
    <div class="marcador-content">
        <div id="tab-general">
            <div class="kpi-bar">
                <div class="kpi"><div class="kpi-val" id="kpi-llamadas"><?= intval($kpis['total'] ?? 0) ?></div><div class="kpi-lbl">Llamadas hoy</div></div>
                <div class="kpi"><div class="kpi-val green" id="kpi-ventas"><?= intval($kpis['ventas'] ?? 0) ?></div><div class="kpi-lbl">Ventas</div></div>
                <div class="kpi"><div class="kpi-val" id="kpi-tmo"><?= gmdate('i:s', intval($kpis['tmo'] ?? 0)) ?></div><div class="kpi-lbl">TMO</div></div>
                <div class="kpi"><div class="kpi-val" id="kpi-tiempo"><?= gmdate('H:i', intval($kpis['tiempo_total'] ?? 0)) ?></div><div class="kpi-lbl">Tiempo total</div></div>
            </div>
            <div class="empty-state" id="empty-state">
                <div class="empty-card" onclick="abrirMarcadorManual()">
                    <div class="icon">📞</div>
                    <strong>Sin llamada activa</strong>
                    Haz clic para marcar un número manualmente
                </div>
            </div>
            <div id="lead-card-wrap" style="display:none">
                <div class="white-card">
                    <div class="lead-header">
                        <div>
                            <div class="lead-name" id="lead-nombre">—</div>
                            <div class="lead-phone-sub" id="lead-tel">—</div>
                        </div>
                        <div style="display:flex;align-items:center;gap:12px">
                            <a id="lead-link" href="#" target="_blank" style="font-size:13px;color:rgba(255,255,255,.7);font-weight:600;text-decoration:none">Ver perfil →</a>
                            <div class="call-timer-badge" id="call-timer">00:00</div>
                        </div>
                    </div>
                    <div class="lead-fields" id="lead-fields"></div>
                    <div class="call-controls">
                        <button class="ctrl-btn red" id="btn-colgar" onclick="colgar()" style="display:none">📵 Colgar</button>
                        <button class="ctrl-btn" id="btn-mute" onclick="toggleMute()" style="display:none">🔇 Silenciar</button>
                        <button class="ctrl-btn" onclick="abrirMarcadorManual()">📞 Nueva llamada</button>
                    </div>
                    <div class="disp-area">
                        <div class="disp-label">Resultado de la llamada</div>
                        <div class="disp-grid" id="disp-grid"></div>
                    </div>
                    <div class="nota-area">
                        <input type="text" class="nota-input" id="nota-input" placeholder="Añadir nota rápida...">
                        <button class="btn-nota" onclick="guardarNota()">Guardar</button>
                    </div>
                </div>
            </div>
        </div>
        <div id="tab-seguimiento" style="display:none">
            <div class="seg-table-wrap">
                <table>
                    <thead><tr><th>Fecha y hora</th><th>Nombre</th><th>Teléfono</th><th>Duración</th><th>Resultado</th></tr></thead>
                    <tbody id="seg-tbody"><tr><td colspan="5" style="text-align:center;color:var(--muted);padding:30px">Cargando...</td></tr></tbody>
                </table>
            </div>
        </div>
        <div id="tab-entrante" style="display:none">
            <div style="background:#fff;border-radius:var(--radius);border:1px solid var(--border);padding:24px;max-width:480px;">
                <p style="font-size:14px;color:var(--muted)">Las llamadas entrantes aparecerán aquí automáticamente cuando estés conectado a JsSIP.</p>
            </div>
        </div>
    </div>
</div>
<!-- MODAL LLAMADA MANUAL -->
<div class="modal-overlay" id="modal-manual">
    <div class="modal-box">
        <div class="modal-title">📞 Marcar número</div>
        <div id="ami-notice-box" style="display:none" class="ami-notice">📡 Modo AMI — la llamada sonará en tu softphone (Zoiper)</div>
        <div class="dial-input-wrap">
            <input type="tel" class="dial-input" id="dial-input" placeholder="Ej: 644361406" inputmode="numeric" autocomplete="off">
            <button class="dial-clear" onclick="borrarUltimo()">⌫</button>
        </div>
        <div class="dialpad">
            <button class="dial-key" onclick="tecla('1')">1<span class="sub">&nbsp;</span></button>
            <button class="dial-key" onclick="tecla('2')">2<span class="sub">ABC</span></button>
            <button class="dial-key" onclick="tecla('3')">3<span class="sub">DEF</span></button>
            <button class="dial-key" onclick="tecla('4')">4<span class="sub">GHI</span></button>
            <button class="dial-key" onclick="tecla('5')">5<span class="sub">JKL</span></button>
            <button class="dial-key" onclick="tecla('6')">6<span class="sub">MNO</span></button>
            <button class="dial-key" onclick="tecla('7')">7<span class="sub">PRS</span></button>
            <button class="dial-key" onclick="tecla('8')">8<span class="sub">TUV</span></button>
            <button class="dial-key" onclick="tecla('9')">9<span class="sub">WXY</span></button>
            <button class="dial-key" onclick="tecla('*')">*</button>
            <button class="dial-key" onclick="tecla('0')">0</button>
            <button class="dial-key" onclick="tecla('#')">#</button>
        </div>
        <div class="modal-actions">
            <button class="btn-call-now" onclick="llamarManual()">📞 Llamar</button>
            <button class="btn-cancel-modal" onclick="cerrarModal()">Cancelar</button>
        </div>
    </div>
</div>

<!-- MODAL PAUSA -->
<div class="modal-overlay" id="modal-pausa">
    <div class="modal-box">
        <div class="modal-title">Motivo de pausa</div>
        <div class="pausa-options">
            <button class="pausa-opt" onclick="setPausa('Pasivo')">☕ Pasivo</button>
            <button class="pausa-opt" onclick="setPausa('Descanso')">🕐 Descanso</button>
            <button class="pausa-opt" onclick="setPausa('Formación')">📚 Formación</button>
            <button class="pausa-opt" onclick="setPausa('Gestión de ventas')">📋 Gestión de ventas</button>
            <button class="pausa-opt continue" onclick="setPausa(null)">▶ Continuar trabajando</button>
        </div>
    </div>
</div>

<!-- INBOUND ALERT -->
<div class="inbound-alert" id="inbound-alert">
    <div class="inbound-label">📞 Llamada entrante</div>
    <div class="inbound-number" id="inbound-number">—</div>
    <div class="inbound-btns">
        <button class="btn-answer" onclick="contestar()">✅ Contestar</button>
        <button class="btn-reject" onclick="rechazar()">❌ Rechazar</button>
    </div>
</div>

<script>
const STATE = {
    campanaId:null, leadId:null, logId:null,
    enLlamada:false, muted:false,
    timerSecs:0, timerInt:null,
    sipSession:null, ua:null, sipHost:'',
    dialMode:'manual',
    disposiciones:[],
    amiPhone:null,
};

let toastTimer;
function showToast(msg, type='', duration=3000){
    const t = document.getElementById('toast');
    t.textContent = msg;
    t.className = 'toast show' + (type?' '+type:'');
    clearTimeout(toastTimer);
    toastTimer = setTimeout(()=>{ t.className='toast'; }, duration);
}

document.addEventListener('keydown', e => {
    const modal = document.getElementById('modal-manual');
    if(!modal.classList.contains('open')) return;
    if(document.activeElement === document.getElementById('dial-input')) return;
    if(/^[0-9\*\#]$/.test(e.key)) tecla(e.key);
    if(e.key === 'Backspace') borrarUltimo();
    if(e.key === 'Enter') llamarManual();
    if(e.key === 'Escape') cerrarModal();
});

function setSipStatus(status, text){
    const ind = document.getElementById('sip-indicator');
    const lbl = document.getElementById('sip-label');
    ind.className = 'sip-pill ' + status;
    lbl.textContent = text || {idle:'Desconectado',connecting:'Conectando...',connected:'Conectado',error:'Sin conexión'}[status] || status;
}

function cambiarTab(tab){
    ['general','seguimiento','entrante'].forEach(t => document.getElementById('tab-'+t).style.display = t===tab?'':'none');
    document.querySelectorAll('.tab').forEach((b,i) => b.classList.toggle('active',['general','seguimiento','entrante'][i]===tab));
    if(tab==='seguimiento') cargarSeguimiento();
}

function cambiarCampana(sel){
    const opt = sel.options[sel.selectedIndex];
    if(!opt.value) return;
    STATE.campanaId = opt.value;
    STATE.dialMode  = opt.dataset.mode || 'manual';
    const pill = document.getElementById('mode-pill');
    if(STATE.dialMode === 'webrtc'){
        pill.className = 'mode-pill webrtc';
        pill.textContent = '🎙 WebRTC';
        document.getElementById('ami-notice-box').style.display = 'none';
    } else {
        pill.className = 'mode-pill ami';
        pill.textContent = '📡 Modo AMI';
        document.getElementById('ami-notice-box').style.display = '';
    }
    cargarDisposiciones();
    if(opt.dataset.host){
        iniciarSIP(opt.dataset.host, opt.dataset.user, opt.dataset.pass, opt.dataset.port);
    }
}

function abrirMarcadorManual(){
    if(!STATE.campanaId){ alert('Selecciona una campaña primero'); return; }
    document.getElementById('dial-input').value = '';
    document.getElementById('modal-manual').classList.add('open');
    setTimeout(()=>document.getElementById('dial-input').focus(), 100);
}

function cerrarModal(){ document.getElementById('modal-manual').classList.remove('open'); }

function tecla(k){
    document.getElementById('dial-input').value += k;
    if(STATE.sipSession && STATE.enLlamada){ try{ STATE.sipSession.sendDTMF(k); }catch(e){} }
}

function borrarUltimo(){
    const i = document.getElementById('dial-input');
    i.value = i.value.slice(0,-1);
}

function llamarManual(){
    let phone = document.getElementById('dial-input').value.trim();
    if(!phone){ alert('Introduce un número'); return; }
    phone = phone.replace(/[^0-9]/g,'');
    if(!phone.startsWith('34') && !phone.startsWith('57') && !phone.startsWith('1')) phone = '34' + phone;
    cerrarModal();
    if(STATE.dialMode === 'webrtc' && STATE.ua){
        iniciarLlamadaWebRTC(phone);
    } else {
        iniciarLlamadaAMI(phone);
    }
}

async function iniciarLlamadaAMI(phone){
    setStatus('llamada');
    STATE.amiPhone = phone;
    mostrarTarjetaLlamada(phone);
    showToast('⏳ Originando llamada a +' + phone + '…', '', 5000);
    try{
        const body = new URLSearchParams({
            phone:       phone,
            campaign_id: STATE.campanaId || 0,
            lead_id:     STATE.leadId    || 0,
        });
        const res  = await fetch('/api/telefonia/call_manual.php', { method:'POST', body });
        const data = await res.json();
        if(data.success){
            STATE.logId = data.log_id || null;
            iniciarTimer();
            document.getElementById('btn-colgar').style.display = '';
            document.getElementById('btn-mute').style.display = 'none';
            showToast('✅ Llamada originada — espera en Zoiper', 'success', 4000);
        } else {
            showToast('❌ Error: ' + (data.error || 'No se pudo originar la llamada'), 'error', 6000);
            terminarLlamadaLocal();
        }
    } catch(err){
        showToast('❌ Error de conexión con el servidor', 'error', 6000);
        terminarLlamadaLocal();
    }
}

function iniciarLlamadaWebRTC(phone){
    if(!STATE.ua){ showToast('SIP no conectado', 'error'); return; }
    try{
        const target = 'sip:' + phone + '@' + STATE.sipHost;
        STATE.sipSession = STATE.ua.call(target, {
            mediaConstraints:{ audio:true, video:false },
            pcConfig:{ iceServers:[{urls:'stun:stun.l.google.com:19302'}] }
        });
        STATE.sipSession.on('progress', ()=>{
            setStatus('llamada'); iniciarTimer(); mostrarTarjetaLlamada(phone);
            document.getElementById('btn-colgar').style.display='';
            document.getElementById('btn-mute').style.display='';
            showToast('📞 Llamando a +' + phone + '…');
        });
        STATE.sipSession.on('confirmed', e=>{
            const remoteAudio = document.getElementById('remoteAudio');
            const conn = STATE.sipSession.connection;
            if(conn){ conn.getReceivers().forEach(r=>{ if(r.track.kind==='audio'){ remoteAudio.srcObject = new MediaStream([r.track]); } }); }
            showToast('✅ Llamada conectada', 'success');
        });
        STATE.sipSession.on('ended', ()=>{
            detenerTimer(); setStatus('libre');
            document.getElementById('btn-colgar').style.display='none';
            document.getElementById('btn-mute').style.display='none';
            guardarLog(phone);
        });
        STATE.sipSession.on('failed', e=>{
            showToast('❌ Llamada fallida: ' + (e.cause||''), 'error', 6000);
            detenerTimer(); setStatus('libre');
            document.getElementById('btn-colgar').style.display='none';
            document.getElementById('btn-mute').style.display='none';
        });
    }catch(e){ showToast('Error SIP: ' + e.message, 'error'); }
}

function mostrarTarjetaLlamada(phone){
    document.getElementById('lead-card-wrap').style.display = '';
    document.getElementById('empty-state').style.display    = 'none';
    document.getElementById('lead-nombre').textContent = phone;
    document.getElementById('lead-tel').textContent    = '+' + phone;
}

async function colgar(){
    if(STATE.sipSession){ try{ STATE.sipSession.terminate(); }catch(e){} STATE.sipSession=null; }
    const phone = STATE.amiPhone || '';
    await guardarLog(phone);
    terminarLlamadaLocal();
    showToast('📵 Llamada finalizada', '', 2500);
}

function terminarLlamadaLocal(){
    detenerTimer(); setStatus('libre');
    document.getElementById('btn-colgar').style.display = 'none';
    document.getElementById('btn-mute').style.display   = 'none';
    STATE.amiPhone = null;
}

async function guardarLog(phone){
    if(!STATE.campanaId) return;
    await fetch('/api/telefonia/call_hangup.php',{
        method:'POST', headers:{'Content-Type':'application/x-www-form-urlencoded'},
        body:'log_id='+(STATE.logId||0)+'&duration='+STATE.timerSecs+'&phone='+encodeURIComponent(phone)+'&campaign_id='+STATE.campanaId
    });
    STATE.logId = null;
}

function toggleMute(){
    STATE.muted = !STATE.muted;
    const btn = document.getElementById('btn-mute');
    btn.textContent = STATE.muted ? '🔊 Activar' : '🔇 Silenciar';
    if(STATE.muted) btn.classList.add('muted-btn'); else btn.classList.remove('muted-btn');
    if(STATE.sipSession){ try{ STATE.muted?STATE.sipSession.mute():STATE.sipSession.unmute(); }catch(e){} }
}

function abrirPausa(){ document.getElementById('modal-pausa').classList.add('open'); }

function setPausa(motivo){
    document.getElementById('modal-pausa').classList.remove('open');
    setStatus(motivo?'pausa':'libre');
    fetch('/api/telefonia/agent_pause.php',{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body:'pausa='+(motivo?1:0)+'&motivo='+encodeURIComponent(motivo||'')});
}

function setStatus(s){
    document.getElementById('status-dot').className = 'status-dot'+(s==='pausa'?' pausa':s==='llamada'?' llamada':'');
    STATE.enLlamada = s==='llamada';
    const timer = document.getElementById('call-timer');
    if(s==='llamada') timer.classList.add('active'); else timer.classList.remove('active');
}

function iniciarTimer(){
    STATE.timerSecs=0; clearInterval(STATE.timerInt);
    STATE.timerInt = setInterval(()=>{
        STATE.timerSecs++;
        document.getElementById('call-timer').textContent =
            String(Math.floor(STATE.timerSecs/60)).padStart(2,'0')+':'+String(STATE.timerSecs%60).padStart(2,'0');
    },1000);
}

function detenerTimer(){
    clearInterval(STATE.timerInt);
    document.getElementById('call-timer').textContent='00:00';
    STATE.timerSecs=0;
}

async function cargarDisposiciones(){
    if(!STATE.campanaId) return;
    try{
        const res = await fetch('/api/telefonia/dispositions.php?campaign_id='+STATE.campanaId);
        const d   = await res.json();
        STATE.disposiciones = d.dispositions||[];
        renderDisposiciones();
    }catch(e){}
}

function renderDisposiciones(){
    const grid = document.getElementById('disp-grid');
    if(!grid) return;
    const defaults=[
        {code:'SALE',label:'Venta',color:'#16a34a'},
        {code:'NI',label:'No interesado',color:'#dc2626'},
        {code:'NA',label:'No contestó',color:'#6b7280'},
        {code:'CALLBACK',label:'Rellamar',color:'#ea580c'},
    ];
    const disps = STATE.disposiciones.length ? STATE.disposiciones : defaults;
    grid.innerHTML = disps.map(d=>`<button class="disp-btn" style="color:${d.color};border-color:${d.color}55;background:${d.color}08" onclick="tipificar('${d.code}','${d.label}')">${d.label}</button>`).join('');
}

async function tipificar(code, label){
    if(STATE.enLlamada) await colgar();
    if(STATE.leadId){
        await fetch('/api/telefonia/disposition.php',{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body:`lead_id=${STATE.leadId}&log_id=${STATE.logId||0}&code=${code}&campaign_id=${STATE.campanaId||0}`});
    }
    if(code==='SALE'){ const v=document.getElementById('kpi-ventas'); v.textContent=parseInt(v.textContent)+1; }
    document.getElementById('kpi-llamadas').textContent = parseInt(document.getElementById('kpi-llamadas').textContent)+1;
    document.getElementById('lead-card-wrap').style.display = 'none';
    document.getElementById('empty-state').style.display    = '';
    STATE.leadId = null;
    showToast('Tipificado: ' + label, 'success', 2000);
}

async function guardarNota(){
    const nota = document.getElementById('nota-input').value.trim();
    if(!nota||!STATE.leadId) return;
    await fetch('/api/telefonia/save_note.php',{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body:`lead_id=${STATE.leadId}&note=${encodeURIComponent(nota)}`});
    document.getElementById('nota-input').value='';
    showToast('Nota guardada', 'success', 1500);
}

async function cargarSeguimiento(){
    try{
        const res = await fetch('/api/telefonia/lead_history.php?user_id=<?= $user_id ?>');
        const d   = await res.json();
        const tbody = document.getElementById('seg-tbody');
        const logs  = d.logs||[];
        if(!logs.length){ tbody.innerHTML='<tr><td colspan="5" style="text-align:center;color:var(--muted);padding:30px">Sin registros</td></tr>'; return; }
        tbody.innerHTML = logs.map(l=>{
            const dur = l.duration_sec>0 ? new Date(l.duration_sec*1000).toISOString().substr(14,5) : '—';
            return `<tr><td>${l.created_at}</td><td>${l.full_name||'—'}</td><td>${l.phone||'—'}</td><td>${dur}</td><td>${l.disposition||'—'}</td></tr>`;
        }).join('');
    }catch(e){}
}

function iniciarSIP(host, user, pass, port){
    if(STATE.ua){ try{ STATE.ua.stop(); }catch(e){} }
    STATE.sipHost = host;
    setSipStatus('connecting');
    const wsPort = port || 8089;
    const socket = new JsSIP.WebSocketInterface('wss://'+host+':'+wsPort+'/ws');
    STATE.ua = new JsSIP.UA({
        sockets:  [socket],
        uri:      'sip:'+user+'@'+host,
        password: pass,
        register: true,
        log:      { builtinEnabled: false }
    });
    STATE.ua.on('registered',          ()=> setSipStatus('connected', 'Registrado'));
    STATE.ua.on('unregistered',        ()=> setSipStatus('error', 'Sin registro'));
    STATE.ua.on('registrationFailed', e=>{ setSipStatus('error', 'Error SIP'); console.warn('SIP fail:', e.cause); });
    STATE.ua.on('disconnected',        ()=> setSipStatus('error', 'Desconectado'));
    STATE.ua.on('newRTCSession', e=>{
        const session = e.session;
        if(e.originator === 'remote'){
            STATE.sipSession = session;
            document.getElementById('inbound-number').textContent = e.request.from.uri.user;
            document.getElementById('inbound-alert').style.display = '';
            session.on('ended', ()=>{ document.getElementById('inbound-alert').style.display = 'none'; setStatus('libre'); detenerTimer(); });
            session.on('confirmed', ()=>{ iniciarTimer(); setStatus('llamada'); });
        }
    });
    STATE.ua.start();
}

function contestar(){
    if(STATE.sipSession){
        STATE.sipSession.answer({ mediaConstraints:{audio:true,video:false}, pcConfig:{iceServers:[{urls:'stun:stun.l.google.com:19302'}]} });
        STATE.sipSession.on('confirmed', ()=>{
            const remoteAudio = document.getElementById('remoteAudio');
            const conn = STATE.sipSession.connection;
            if(conn){ conn.getReceivers().forEach(r=>{ if(r.track.kind==='audio'){ remoteAudio.srcObject = new MediaStream([r.track]); } }); }
        });
    }
    document.getElementById('inbound-alert').style.display='none';
    setStatus('llamada'); iniciarTimer();
}

function rechazar(){
    if(STATE.sipSession){ try{ STATE.sipSession.terminate(); }catch(e){} STATE.sipSession=null; }
    document.getElementById('inbound-alert').style.display='none';
}
</script>
</body>
</html>