<?php
// csr_manager/calls.php — Manager 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';
require_once __DIR__ . '/../includes/csr_report_helpers.php';

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

$managerId = (int)$_SESSION['csr_id'];
if (getCsrRoleForReport($db, $managerId) !== 'csr_manager') {
    header('Location: dashboard.php');
    exit();
}

// CSR Manager can assign queued calls to any active regular CSR.
$agents = $db->query("SELECT id, CONCAT(first_name, ' ', last_name) AS name
                      FROM csr_users
                      WHERE is_active = 1
                        AND COALESCE(role, 'csr') = 'csr'
                      ORDER BY first_name, last_name")->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)}
</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>Manager Call Queue
    </h2>
    <small style="color:var(--cm-muted);">Assign customer web calls to regular CSR agents. ER/TypeScript will not handle this queue.</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.</strong>
  <div style="color:var(--cm-muted);margin-top:4px;">Create or activate at least one regular CSR account before assigning calls.</div>
</div>
<?php endif; ?>

<div style="display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:12px;margin-bottom:20px;" id="cmCallStats">
  <div class="cm-card" style="text-align:center;"><div style="font-size:.7rem;font-weight:800;text-transform:uppercase;color:var(--cm-muted);">Manager Queue</div><div id="cmCallQueued" style="font-size:1.8rem;font-weight:900;color:var(--cm-yellow);">—</div></div>
  <div class="cm-card" style="text-align:center;"><div style="font-size:.7rem;font-weight:800;text-transform:uppercase;color:var(--cm-muted);">Assigned</div><div id="cmCallAssigned" style="font-size:1.8rem;font-weight:900;color:var(--cm-blue);">—</div></div>
  <div class="cm-card" style="text-align:center;"><div style="font-size:.7rem;font-weight:800;text-transform:uppercase;color:var(--cm-muted);">Active</div><div id="cmCallActive" style="font-size:1.8rem;font-weight:900;color:var(--cm-green);">—</div></div>
  <div class="cm-card" style="text-align:center;"><div style="font-size:.7rem;font-weight:800;text-transform:uppercase;color:var(--cm-muted);">Missed</div><div id="cmCallMissed" style="font-size:1.8rem;font-weight:900;color:var(--cm-red);">—</div></div>
</div>

<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 → both join WebRTC room.</small>
  </div>
  <div class="cm-table-wrap">
    <table class="cm-table">
      <thead>
        <tr>
          <th>Queued</th>
          <th>Request #</th>
          <th>Customer</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="8" style="text-align:center;padding:24px;color:var(--cm-muted);">Loading…</td></tr>
      </tbody>
    </table>
  </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 cmAgentSelect(call) {
  const selectedId = Number(call.assigned_csr_id || 0);
  const options = ['<option value="">Select CSR</option>'].concat(CM_CALL_AGENTS.map(a => {
    const selected = Number(a.id) === selectedId ? 'selected' : '';
    return `<option value="${Number(a.id)}" ${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="8" 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="8" style="text-align:center;padding:24px;color:var(--cm-red);">${cmLocalEsc(res.message || 'Unable to load calls.')}</td></tr>`);
        return;
      }
      const counts = res.counts || {};
      $('#cmCallQueued').text(counts.manager_queue ?? counts.queued ?? 0);
      $('#cmCallAssigned').text(counts.assigned ?? 0);
      $('#cmCallActive').text(counts.accepted ?? counts.active ?? 0);
      $('#cmCallMissed').text(counts.missed ?? 0);

      const statusFilter = $('#cmCallStatusFilter').val() || '';
      const calls = ['completed','missed','cancelled'].includes(statusFilter) ? (res.history || []) : (res.calls || []);
      if (!calls.length) {
        tbody.html('<tr><td colspan="8" 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><strong>${cmLocalEsc(c.request_number || 'Manual Call')}</strong></td>
          <td>${cmLocalEsc(c.customer_name || c.full_name || 'Customer')}</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(xhr) {
      tbody.html(`<tr><td colspan="8" 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';
?>
