<?php
// team_leader/calls.php — Team Leader call queue assignment page
if (session_status() === PHP_SESSION_NONE) session_start();
if (!isset($_SESSION['csr_id'])) { header('Location: ../login.php'); exit(); }

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/app_helpers.php';

$db = (new Database())->getConnection();
ensureAddressAndCallQueueTables($db);
ensureWebRtcCallWorkflow($db);
ensureCsrTeamTables($db);

$leaderId = (int)$_SESSION['csr_id'];
$scope = getCsrRequestScope($db, $leaderId);
if (($scope['role'] ?? '') !== 'team_leader') {
    header('Location: dashboard.php');
    exit();
}

$agents = [];
$memberIds = array_map('intval', $scope['member_ids'] ?? []);
if ($memberIds) {
    $params = [];
    $in = addInClauseParams($params, $memberIds, 'tl_agent');
    $stmt = $db->prepare("SELECT id, CONCAT(first_name, ' ', last_name) AS name
                          FROM csr_users
                          WHERE id IN ($in)
                            AND is_active = 1
                            AND COALESCE(role, 'csr') = 'csr'
                          ORDER BY first_name, last_name");
    foreach ($params as $k => $v) $stmt->bindValue($k, $v, PDO::PARAM_INT);
    $stmt->execute();
    $agents = $stmt->fetchAll(PDO::FETCH_ASSOC);
}

$title = 'Call Queue';
ob_start();
?>

<style>
.cm-table{width:100%;border-collapse:collapse}.cm-table th,.cm-table td{padding:12px;border-bottom:1px solid var(--cm-border);vertical-align:middle}.cm-table th{font-size:.72rem;text-transform:uppercase;letter-spacing:.06em;color:var(--cm-muted);font-weight:900}.cm-table-wrap{overflow-x:auto}.cm-badge{display:inline-flex;align-items:center;gap:6px;border-radius:999px;padding:5px 9px;font-size:.75rem;font-weight:900;white-space:nowrap}.cm-badge--blue{background:oklch(0.62 0.22 255/.18);color:var(--cm-blue);border:1px solid oklch(0.62 0.22 255/.35)}.cm-badge--green{background:oklch(0.72 0.18 155/.18);color:var(--cm-green);border:1px solid oklch(0.72 0.18 155/.35)}.cm-badge--yellow{background:oklch(0.82 0.16 85/.18);color:var(--cm-yellow);border:1px solid oklch(0.82 0.16 85/.35)}.cm-badge--red{background:oklch(0.68 0.22 27/.18);color:var(--cm-red);border:1px solid oklch(0.68 0.22 27/.35)}.cm-badge--muted{background:oklch(0.98 0.005 250/.08);color:var(--cm-muted);border:1px solid var(--cm-border)}
.cm-call-link{border:0!important;background:transparent!important;background-color:transparent!important;color:#dff7ff!important;font-weight:900;text-decoration:underline;text-underline-offset:3px;padding:0!important;margin:0!important;cursor:pointer;box-shadow:none!important;outline:none!important;border-radius:0!important;appearance:none;-webkit-appearance:none;display:inline;line-height:inherit;user-select:none;-webkit-user-select:none}.cm-call-link:hover,.cm-call-link:focus,.cm-call-link:active{color:#fff!important;background:transparent!important;background-color:transparent!important;box-shadow:none!important;outline:none!important}.cm-call-link::selection{background:transparent}.cm-detail-overlay{position:fixed;inset:0;background:rgba(2,6,23,.74);z-index:4600;display:none;align-items:center;justify-content:center;padding:18px}.cm-detail-modal{width:min(920px,100%);max-height:88vh;overflow:hidden;display:flex;flex-direction:column;background:linear-gradient(135deg,#17295e,#102448);border:1px solid rgba(56,189,248,.42);border-radius:18px;box-shadow:0 25px 80px rgba(0,0,0,.52)}.cm-detail-header,.cm-detail-footer{padding:14px 16px;border-bottom:1px solid var(--cm-border);display:flex;justify-content:space-between;gap:12px;align-items:center}.cm-detail-footer{border-top:1px solid var(--cm-border);border-bottom:0;justify-content:flex-end}.cm-detail-body{padding:16px;overflow-y:auto}.cm-detail-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px}.cm-detail-section{background:rgba(8,20,48,.46);border:1px solid var(--cm-border);border-radius:14px;padding:14px}.cm-detail-section.full{grid-column:1/-1}.cm-detail-section h5{color:#fff;font-weight:900;font-size:.98rem;margin:0 0 10px}.cm-detail-row{display:grid;grid-template-columns:150px 1fr;gap:8px;padding:6px 0;border-bottom:1px solid rgba(96,165,250,.12)}.cm-detail-row:last-child{border-bottom:0}.cm-detail-row span:first-child{color:var(--cm-muted);font-weight:800}.cm-detail-row span:last-child{color:#f8fafc;font-weight:700;word-break:break-word}.cm-detail-notes{white-space:pre-wrap;color:#f8fafc;line-height:1.55}@media(max-width:720px){.cm-detail-grid{grid-template-columns:1fr}.cm-detail-row{grid-template-columns:1fr}}
</style>

<div class="d-flex justify-content-between align-items-center flex-wrap gap-2 mb-4">
  <div>
    <h2 style="font-family:'Space Grotesk',system-ui,sans-serif;font-weight:800;margin:0;">
      <i class="fas fa-phone-volume me-2" style="color:var(--cm-blue);"></i>Team Call Queue
    </h2>
    <small style="color:var(--cm-muted);">Assign customer web calls to your team agents.</small>
  </div>
  <div style="display:flex;gap:8px;flex-wrap:wrap;align-items:center;">
    <select class="cm-select form-select" id="cmCallAgentFilter" style="min-width:180px;" onchange="cmCallsLoad()">
      <option value="">All Assigned Agents</option>
      <?php foreach ($agents as $a): ?>
        <option value="<?= (int)$a['id'] ?>"><?= htmlspecialchars($a['name'], ENT_QUOTES, 'UTF-8') ?></option>
      <?php endforeach; ?>
    </select>
    <select class="cm-select form-select" id="cmCallStatusFilter" style="min-width:160px;" onchange="cmCallsLoad()">
      <option value="">All Statuses</option>
      <option value="manager_queue">Manager Queue</option>
      <option value="assigned">Assigned</option>
      <option value="accepted">Active / Accepted</option>
      <option value="completed">Completed</option>
      <option value="missed">Missed</option>
      <option value="cancelled">Cancelled</option>
    </select>
    <button class="cm-btn cm-btn--primary" onclick="cmCallsLoad(true)"><i class="fas fa-sync-alt me-1"></i>Refresh</button>
  </div>
</div>

<?php if (!$agents): ?>
<div class="cm-card mb-3" style="border-color:rgba(250,204,21,.45)!important;">
  <strong style="color:var(--cm-yellow);"><i class="fas fa-triangle-exclamation me-1"></i>No active regular CSR agents found in your team.</strong>
  <div style="color:var(--cm-muted);margin-top:4px;">Ask Admin or CSR Manager to add agents to your team before assigning calls.</div>
</div>
<?php endif; ?>

<div class="cm-card">
  <div class="d-flex justify-content-between align-items-center flex-wrap gap-2 mb-3">
    <div class="cm-card__title mb-0"><i class="fas fa-list-check me-1"></i>Live Call Requests</div>
    <small style="color:var(--cm-muted);">Manager Queue → assign to CSR → CSR answers → WebRTC call room.</small>
  </div>
  <div class="cm-table-wrap">
    <table class="cm-table">
      <thead>
        <tr>
          <th>Queued</th>
          <th>Request #</th>
          <th>Customer</th>
          <th>Type</th>
          <th>Phone</th>
          <th>Team</th>
          <th>Status</th>
          <th>Assigned CSR</th>
          <th style="min-width:260px;">Action</th>
        </tr>
      </thead>
      <tbody id="cmCallQueueTbody">
        <tr><td colspan="9" style="text-align:center;padding:24px;color:var(--cm-muted);">Loading…</td></tr>
      </tbody>
    </table>
  </div>
</div>

<div class="cm-detail-overlay" id="cmCallDetailOverlay">
  <div class="cm-detail-modal">
    <div class="cm-detail-header">
      <div>
        <h4 class="mb-0"><i class="fas fa-circle-info me-2"></i>Call / Request Details</h4>
        <small style="color:var(--cm-muted);">Caller info, linked request details, and saved call room notes.</small>
      </div>
      <button class="cm-btn" onclick="cmCloseCallDetails()"><i class="fas fa-times"></i></button>
    </div>
    <div class="cm-detail-body" id="cmCallDetailBody">
      <div style="text-align:center;padding:28px;color:var(--cm-muted);"><i class="fas fa-spinner fa-spin"></i> Loading details…</div>
    </div>
    <div class="cm-detail-footer"><button class="cm-btn" onclick="cmCloseCallDetails()">Close</button></div>
  </div>
</div>

<script>
const CM_CALL_AGENTS = <?= json_encode($agents, JSON_HEX_TAG|JSON_HEX_APOS|JSON_HEX_AMP|JSON_HEX_QUOT) ?>;
function cmLocalEsc(v) { if (typeof cmEsc === 'function') return cmEsc(v); return String(v ?? '').replace(/[&<>"']/g, s => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#039;'}[s])); }
function cmCallToast(message, type='info') { if (typeof cmToast === 'function') cmToast(message, type); else alert(message); }
function cmFmtDate(d) { if (!d) return '—'; try { return new Date(String(d).replace(' ', 'T')).toLocaleString('en-US',{month:'short',day:'numeric',hour:'2-digit',minute:'2-digit'}); } catch(e) { return d; } }
function cmStatusBadge(status) { const map={manager_queue:['cm-badge--yellow','Manager Queue'],assigned:['cm-badge--blue','Assigned'],accepted:['cm-badge--green','Active'],completed:['cm-badge--blue','Completed'],missed:['cm-badge--red','Missed'],cancelled:['cm-badge--muted','Cancelled']}; const item=map[status]||['cm-badge--muted',status||'—']; return `<span class="cm-badge ${item[0]}">${cmLocalEsc(item[1])}</span>`; }
function cmDirectionBadge(direction) {
  const normalized = String(direction || 'inbound').toLowerCase();
  const icon = normalized === 'outbound' ? 'fa-arrow-up-right-from-square' : 'fa-arrow-down-left';
  const label = normalized === 'outbound' ? 'Outbound' : 'Inbound';
  return `<span class="cm-badge cm-badge--blue"><i class="fas ${icon} me-1"></i>${label}</span>`;
}
function cmDuration(sec) { sec = parseInt(sec || 0, 10); if (!sec) return 'N/A'; const m = Math.floor(sec / 60); const s = sec % 60; return `${m}:${String(s).padStart(2,'0')}`; }
function cmDetailRow(label, value) { const text = value === null || value === undefined || value === '' ? '—' : value; return `<div class="cm-detail-row"><span>${cmLocalEsc(label)}</span><span>${cmLocalEsc(text)}</span></div>`; }
function cmCloseCallDetails() { $('#cmCallDetailOverlay').hide(); }
function cmOpenCallDetails(callId) {
  if (!callId) return;
  $('#cmCallDetailBody').html('<div style="text-align:center;padding:28px;color:var(--cm-muted);"><i class="fas fa-spinner fa-spin"></i> Loading details…</div>');
  $('#cmCallDetailOverlay').css('display','flex');
  $.ajax({url:'../csr/ajax/get_call_details.php',method:'GET',data:{call_id:callId,_:Date.now()},dataType:'json',success:function(res){
    if (!res.success || !res.call) { $('#cmCallDetailBody').html(`<div style="text-align:center;padding:28px;color:var(--cm-red);">${cmLocalEsc(res.message || 'Unable to load call details.')}</div>`); return; }
    cmRenderCallDetails(res.call);
  },error:function(){ $('#cmCallDetailBody').html('<div style="text-align:center;padding:28px;color:var(--cm-red);">Unable to load call details.</div>'); }});
}
function cmRenderCallDetails(c) {
  const phone = c.phone_number || c.request_phone || c.customer_account_phone || '';
  const email = c.customer_email || c.request_customer_email || c.customer_account_email || '';
  const state = c.request_state || c.city_state || '';
  const region = c.request_region || c.city_region || '';
  const notes = c.combined_notes || c.notes || 'No call notes saved yet.';
  const recording = c.recording_path ? `<audio controls src="../${cmLocalEsc(c.recording_path)}" style="width:100%;max-width:360px;"></audio>` : '<span style="color:var(--cm-muted);">No recording saved</span>';
  $('#cmCallDetailBody').html(`<div class="cm-detail-grid">
    <div class="cm-detail-section"><h5><i class="fas fa-phone me-1"></i>Call Information</h5>${cmDetailRow('Request #', c.request_number || 'Manual Call')}${cmDetailRow('Call Type', String(c.call_direction || 'inbound').toLowerCase() === 'outbound' ? 'Outbound' : 'Inbound')}${cmDetailRow('Status', c.status || '')}${cmDetailRow('Queued', cmFmtDate(c.queued_at))}${cmDetailRow('Started', cmFmtDate(c.call_started_at || c.accepted_at))}${cmDetailRow('Ended', cmFmtDate(c.call_ended_at || c.completed_at))}${cmDetailRow('Duration', cmDuration(c.call_duration_seconds))}${cmDetailRow('Team', c.team_name || 'Queue')}${cmDetailRow('Assigned CSR', c.assigned_csr_name || 'Unassigned')}${cmDetailRow('Handled By', c.accepted_by_name || c.assigned_csr_name || 'CSR')}</div>
    <div class="cm-detail-section"><h5><i class="fas fa-user me-1"></i>Caller Information</h5>${cmDetailRow('Customer', c.customer_name || c.request_full_name || 'Customer')}${cmDetailRow('Phone', phone)}${cmDetailRow('Email', email)}${cmDetailRow('Address', c.service_address || '')}${cmDetailRow('Address Note', c.service_address_2 || '')}${cmDetailRow('City', c.city_name || '')}${cmDetailRow('State', state)}${cmDetailRow('ZIP', c.zip_code || '')}${cmDetailRow('Region', region)}</div>
    <div class="cm-detail-section"><h5><i class="fas fa-screwdriver-wrench me-1"></i>Product / Request</h5>${cmDetailRow('Appliance', c.appliance_name || '')}${cmDetailRow('Brand', c.brand_name || '')}${cmDetailRow('Model', c.model_number || '')}${cmDetailRow('Serial', c.serial_number || '')}${cmDetailRow('Model Version', c.product_model_version || '')}${cmDetailRow('Purchase Date', c.purchase_date || '')}${cmDetailRow('Warranty Type', c.warranty_type || '')}${cmDetailRow('CX Preferred Date', c.cx_preferred_date || '')}</div>
    <div class="cm-detail-section"><h5><i class="fas fa-volume-high me-1"></i>Replay</h5>${recording}</div>
    <div class="cm-detail-section full"><h5><i class="fas fa-clipboard me-1"></i>Problem / Special Request</h5>${cmDetailRow('Problem', c.issue_description || '')}${cmDetailRow('Special Request', c.special_request || '')}</div>
    <div class="cm-detail-section full"><h5><i class="fas fa-note-sticky me-1"></i>Call Room Notes</h5><div class="cm-detail-notes">${cmLocalEsc(notes)}</div></div>
  </div>`);
}
function cmAgentSelect(call) { const selectedId=Number(call.assigned_csr_id||0); const options=['<option value="">Select CSR</option>'].concat(CM_CALL_AGENTS.map(a=>`<option value="${Number(a.id)}" ${Number(a.id)===selectedId?'selected':''}>${cmLocalEsc(a.name)}</option>`)).join(''); return `<select class="form-select form-select-sm" id="assign-csr-${Number(call.id)}">${options}</select>`; }
function cmCallsLoad(manual=false) {
  const agentId=$('#cmCallAgentFilter').val()||''; const statusFilter=$('#cmCallStatusFilter').val()||''; const tbody=$('#cmCallQueueTbody');
  tbody.html('<tr><td colspan="9" style="text-align:center;padding:24px;color:var(--cm-muted);"><i class="fas fa-spinner fa-spin"></i> Loading…</td></tr>');
  $.ajax({url:'../csr/ajax/get_call_queue.php',method:'GET',data:{agent_filter:agentId,status_filter:statusFilter,limit:150,_:Date.now()},dataType:'json',cache:false,
    success:function(res){
      if(!res.success){tbody.html(`<tr><td colspan="9" style="text-align:center;padding:24px;color:var(--cm-red);">${cmLocalEsc(res.message||'Unable to load calls.')}</td></tr>`);return;}
      const statusFilter=$('#cmCallStatusFilter').val()||''; const calls=['completed','missed','cancelled'].includes(statusFilter)?(res.history||[]):(res.calls||[]);
      if(!calls.length){tbody.html('<tr><td colspan="9" style="text-align:center;padding:28px;color:var(--cm-muted);"><i class="fas fa-phone-slash me-1"></i>No active call requests found.</td></tr>');return;}
      tbody.html(calls.map(c=>{const id=Number(c.id); const phone=c.phone_number||c.request_phone||''; const canAssign=['manager_queue','assigned'].includes(String(c.status||''))&&CM_CALL_AGENTS.length>0; const assignBox=canAssign?`<div style="display:flex;gap:8px;align-items:center;flex-wrap:wrap;"><div style="min-width:170px;">${cmAgentSelect(c)}</div><button class="cm-btn cm-btn--primary" style="padding:6px 10px;" onclick="cmAssignCall(${id})"><i class="fas fa-user-check"></i>${c.assigned_csr_id?'Reassign':'Assign'}</button></div>`:`<span style="color:var(--cm-muted);">${String(c.status)==='accepted'?'CSR handling call':'No action'}</span>`; return `<tr id="call-row-${id}"><td>${cmFmtDate(c.queued_at||c.created_at)}</td><td><button type="button" class="cm-call-link" onclick="cmOpenCallDetails(${id})">${cmLocalEsc(c.request_number||'Manual Call')}</button></td><td>${cmLocalEsc(c.customer_name||c.full_name||'Customer')}</td><td>${cmDirectionBadge(c.call_direction)}</td><td>${phone?`<a href="tel:${cmLocalEsc(phone)}" class="cm-badge cm-badge--blue"><i class="fas fa-phone me-1"></i>${cmLocalEsc(phone)}</a>`:'—'}</td><td>${cmLocalEsc(c.team_name||'Queue')}</td><td>${cmStatusBadge(c.status)}</td><td>${cmLocalEsc(c.assigned_csr_name||c.accepted_by_name||'Unassigned')}</td><td>${assignBox}</td></tr>`;}).join(''));
      if(manual) cmCallToast('Call queue refreshed.','success');
    }, error:function(){tbody.html('<tr><td colspan="9" style="text-align:center;padding:24px;color:var(--cm-red);">Call queue data unavailable.</td></tr>');}
  });
}
function cmAssignCall(callId) { const csrId=$('#assign-csr-'+Number(callId)).val(); if(!csrId){cmCallToast('Please select a CSR first.','warning');return;} $.ajax({url:'../csr/ajax/assign_call_request.php',method:'POST',data:{call_id:callId,csr_id:csrId},dataType:'json',success:function(res){cmCallToast(res.message||(res.success?'Call assigned.':'Unable to assign call.'),res.success?'success':'error');cmCallsLoad();},error:function(){cmCallToast('Unable to assign call.','error');}}); }
$(document).ready(function(){ cmCallsLoad(); setInterval(cmCallsLoad,10000); });
</script>

<?php
$content = ob_get_clean();
include __DIR__ . '/layout.php';
?>
