<?php
// csr_manager/tickets.php — Tickets (same data as csr/requests.php, manager scope)
if (session_status() === PHP_SESSION_NONE) session_start();
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/app_helpers.php';
require_once __DIR__ . '/../includes/csr_report_helpers.php';

if (!isset($_SESSION['csr_id'])) { header('Location: ../login.php'); exit(); }
$db = (new Database())->getConnection();
ensureCsrRoleSchema($db);
if (getCsrRoleForReport($db, (int)$_SESSION['csr_id']) !== 'csr_manager') {
    header('Location: ../csr/requests.php'); exit();
}

$title = 'Tickets';

$extra_styles = <<<'CSS'
<style>
.cm-filter-bar { display:flex; gap:8px; flex-wrap:wrap; margin-bottom:16px; align-items:center; }
.cm-filter-bar .cm-input, .cm-filter-bar .cm-select { width:auto; min-width:140px; }
</style>
CSS;

ob_start();
?>
<div class="cm-card mb-3">
  <div class="d-flex justify-content-between align-items-center flex-wrap gap-2 mb-3">
    <div>
      <h2 style="font-family:'Space Grotesk',system-ui,sans-serif;font-weight:800;margin:0;">
        <i class="fas fa-clipboard-list me-2" style="color:var(--cm-blue);"></i>Tickets
      </h2>
      <small style="color:var(--cm-muted);">All service requests visible to CSR Manager</small>
    </div>
    <a href="manual_ticket.php" class="cm-btn cm-btn--primary">
      <i class="fas fa-plus"></i> New Manual Ticket
    </a>
  </div>

  <div class="cm-filter-bar">
    <input type="text"   class="cm-input" id="cmTicketSearch"  placeholder="Search request #, name…" style="min-width:200px;">
    <select class="cm-select" id="cmTicketView" style="min-width:160px;">
      <option value="active" selected>Active Tickets</option>
      <option value="all">All Tickets</option>
      <option value="new">New Request</option>
      <option value="assigned">Assigned</option>
      <option value="in_progress">In Progress</option>
      <option value="completed">Completed</option>
      <option value="cancelled">Cancelled</option>
    </select>
    <select class="cm-select" id="cmTicketStatus" style="min-width:160px;">
      <option value="">All Statuses</option>
    </select>
    <button class="cm-btn cm-btn--primary" onclick="cmTicketsLoad()"><i class="fas fa-search"></i> Filter</button>
    <button class="cm-btn" onclick="cmTicketsClear()"><i class="fas fa-times"></i> Clear</button>
  </div>

  <div class="cm-table-wrap">
    <table class="cm-table" id="cmTicketsTable">
      <thead>
        <tr>
          <th>Request #</th>
          <th>Customer</th>
          <th>Appliance</th>
          <th>Status</th>
          <th>City</th>
          <th>Requested</th>
          <th>Action</th>
        </tr>
      </thead>
      <tbody id="cmTicketsTbody">
        <tr><td colspan="7" style="text-align:center;padding:24px;color:var(--cm-muted);">Loading…</td></tr>
      </tbody>
    </table>
  </div>
  <div id="cmTicketsPager" style="margin-top:12px;display:flex;gap:8px;flex-wrap:wrap;align-items:center;"></div>
</div>

<!-- Ticket detail modal -->
<div class="modal fade" id="cmTicketModal" tabindex="-1">
  <div class="modal-dialog modal-xl">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title"><i class="fas fa-clipboard-list me-2" style="color:var(--cm-blue);"></i>Ticket Details</h5>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body" id="cmTicketModalBody" style="min-height:200px;">
        <div style="text-align:center;padding:32px;color:var(--cm-muted);">Loading…</div>
      </div>
      <div class="modal-footer">
        <button type="button" class="cm-btn" data-bs-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>

<script>
let _cmTicketPage = 1;

function cmTicketsLoad(page) {
  page = page || 1;
  _cmTicketPage = page;
  const search = document.getElementById('cmTicketSearch').value.trim();
  const status = document.getElementById('cmTicketStatus').value;
  const view = document.getElementById('cmTicketView').value;
  const tbody  = document.getElementById('cmTicketsTbody');
  tbody.innerHTML = '<tr><td colspan="7" style="text-align:center;padding:24px;color:var(--cm-muted);">Loading…</td></tr>';

  $.ajax({
    url: '../csr/ajax/get_requests_list.php',
    method: 'POST',
    data: { search: search, status: status || '', ticket_view: view || 'active', page: page, per_page: 20 },
    dataType: 'json',
    success: function(res) {
      if (!res.success || !res.requests || !res.requests.length) {
        tbody.innerHTML = '<tr><td colspan="7" style="text-align:center;padding:24px;color:var(--cm-muted);">No tickets found.</td></tr>';
        document.getElementById('cmTicketsPager').innerHTML = '';
        return;
      }
      tbody.innerHTML = res.requests.map(r => `
        <tr>
          <td><span style="font-weight:700;color:var(--cm-blue);cursor:pointer;" onclick="cmViewTicket(${r.id})">${cmEsc(r.request_number||r.manual_ticket_number||'#'+r.id)}</span></td>
          <td>${cmEsc(r.full_name||'—')}</td>
          <td>${cmEsc(r.appliance_type||'—')}</td>
          <td><span class="cm-badge" style="background:${r.status_color||'#444'}22;color:${r.status_color||'#aaa'};border:1px solid ${r.status_color||'#444'}55;">${cmEsc(r.status_name||'—')}</span></td>
          <td>${cmEsc(r.city_name||'—')}</td>
          <td style="font-size:.8rem;color:var(--cm-muted);">${cmFmtDate(r.requested_at)}</td>
          <td>
            <button class="cm-btn" style="padding:5px 10px;" onclick="cmViewTicket(${r.id})">
              <i class="fas fa-eye"></i>
            </button>
          </td>
        </tr>`).join('');

      // Pager using pagination object
      const pager = document.getElementById('cmTicketsPager');
      const pg = res.pagination || {};
      const total = parseInt(pg.total_pages) || 1;
      const current = parseInt(pg.current_page) || page;
      const startP = parseInt(pg.start_page) || Math.max(1, current - 2);
      const endP   = parseInt(pg.end_page)   || Math.min(total, current + 2);
      pager.innerHTML = '';

      if (startP > 1) {
        const btn = document.createElement('button');
        btn.className = 'cm-btn'; btn.textContent = '« First';
        btn.onclick = () => cmTicketsLoad(1); pager.appendChild(btn);
      }
      for (let p = startP; p <= endP; p++) {
        const btn = document.createElement('button');
        btn.className = 'cm-btn' + (p === current ? ' cm-btn--active' : '');
        btn.textContent = p;
        btn.onclick = (function(pp){ return function(){ cmTicketsLoad(pp); }; })(p);
        pager.appendChild(btn);
      }
      if (endP < total) {
        const btn = document.createElement('button');
        btn.className = 'cm-btn'; btn.textContent = 'Last »';
        btn.onclick = () => cmTicketsLoad(total); pager.appendChild(btn);
      }
      if (total > 1) {
        const info = document.createElement('span');
        info.style.cssText = 'color:var(--cm-muted);font-size:.78rem;align-self:center;margin-left:4px;';
        info.textContent = `${pg.start||''}–${pg.end||''} of ${pg.total||''}`;
        pager.appendChild(info);
      }
    },
    error: function() {
      tbody.innerHTML = '<tr><td colspan="7" style="text-align:center;padding:24px;color:var(--cm-red);">Failed to load tickets. Please try again.</td></tr>';
    }
  });
}

function cmTicketsClear() {
  document.getElementById('cmTicketSearch').value = '';
  document.getElementById('cmTicketView').value = 'active';
  document.getElementById('cmTicketStatus').value = '';
  cmTicketsLoad(1);
}

function cmViewTicket(id) {
  const body = document.getElementById('cmTicketModalBody');
  body.innerHTML = '<div style="text-align:center;padding:32px;color:var(--cm-muted);"><i class="fas fa-spinner fa-spin" style="font-size:1.5rem;"></i></div>';
  bootstrap.Modal.getOrCreateInstance(document.getElementById('cmTicketModal')).show();

  $.ajax({
    url: '../csr/ajax/get_request_details.php',
    method: 'GET',
    data: { request_id: id },
    dataType: 'json',
    success: function(res) {
      if (!res.success || !res.request) {
        body.innerHTML = '<div style="color:var(--cm-red);padding:20px;text-align:center;"><i class="fas fa-exclamation-triangle me-2"></i>Error loading ticket details.</div>';
        return;
      }
      const r = res.request;
      const sc = r.status_color || '#4fc3f7';

      // ── urgency badge ──
      const urgId = parseInt(r.urgency_level_id || r.urgency_id || 1);
      let urgBadge = `<span class="cm-badge cm-badge--blue">${cmEsc(r.urgency_name||'Normal')}</span>`;
      if (urgId === 3) urgBadge = `<span class="cm-badge cm-badge--red"><i class="fas fa-exclamation-triangle me-1"></i>${cmEsc(r.urgency_name||'Emergency')}</span>`;
      else if (urgId === 2) urgBadge = `<span class="cm-badge cm-badge--yellow">${cmEsc(r.urgency_name||'Urgent')}</span>`;

      // ── manual flags ──
      const brandDisplay    = cmEsc(r.brand||'—') + (r.is_manual_brand    == 1 ? ' <span class="cm-badge cm-badge--yellow" style="font-size:.6rem;">manual</span>' : '');
      const applianceDisplay= cmEsc(r.appliance_type||'—') + (r.is_manual_appliance == 1 ? ' <span class="cm-badge cm-badge--yellow" style="font-size:.6rem;">manual</span>' : '');

      // ── sections ──
      let html = `
        <div class="row g-3">
          <!-- Request Info -->
          <div class="col-md-6">
            <div class="cm-card">
              <div class="cm-card__title">Request Information</div>
              <table style="width:100%;font-size:.85rem;border-collapse:collapse;">
                <tr><td class="_ml" style="color:var(--cm-muted);padding:5px 0;width:44%;">Request #</td><td><strong style="color:var(--cm-blue);">${cmEsc(r.request_number||r.manual_ticket_number||'—')}</strong></td></tr>
                ${r.manual_ticket_number && r.manual_ticket_number !== r.request_number ? `<tr><td style="color:var(--cm-muted);padding:5px 0;">Manual #</td><td>${cmEsc(r.manual_ticket_number)}</td></tr>` : ''}
                <tr><td style="color:var(--cm-muted);padding:5px 0;">Source</td><td><span class="cm-badge cm-badge--muted" style="font-size:.7rem;">${cmEsc(r.ticket_source_label||'Customer Online')}</span></td></tr>
                <tr><td style="color:var(--cm-muted);padding:5px 0;">Status</td><td><span class="cm-badge" style="background:${sc}22;color:${sc};border:1px solid ${sc}55;">${cmEsc(r.status_name||'—')}</span></td></tr>
                <tr><td style="color:var(--cm-muted);padding:5px 0;">Urgency</td><td>${urgBadge}</td></tr>
                <tr><td style="color:var(--cm-muted);padding:5px 0;">Requested</td><td>${cmEsc(r.requested_at_formatted||cmFmtDate(r.requested_at))}</td></tr>
                <tr><td style="color:var(--cm-muted);padding:5px 0;">Preferred</td><td>${cmEsc(r.preferred_date_formatted||cmFmtDate(r.preferred_date)||'Not specified')}</td></tr>
                <tr><td style="color:var(--cm-muted);padding:5px 0;">Preferred Time</td><td>${cmEsc(r.preferred_time||'—')}</td></tr>
                ${r.managing_csr ? `<tr><td style="color:var(--cm-muted);padding:5px 0;">Managed by</td><td>${cmEsc(r.managing_csr)}</td></tr>` : ''}
                ${r.created_by_csr_name ? `<tr><td style="color:var(--cm-muted);padding:5px 0;">Created by</td><td>${cmEsc(r.created_by_csr_name)}</td></tr>` : ''}
              </table>
            </div>
          </div>

          <!-- Customer -->
          <div class="col-md-6">
            <div class="cm-card">
              <div class="cm-card__title">Customer Information</div>
              <table style="width:100%;font-size:.85rem;border-collapse:collapse;">
                <tr><td style="color:var(--cm-muted);padding:5px 0;width:44%;">Name</td><td><strong>${cmEsc(r.full_name||'—')}</strong></td></tr>
                <tr><td style="color:var(--cm-muted);padding:5px 0;">Phone</td><td>${cmEsc(r.phone_number||'—')}</td></tr>
                ${r.secondary_phone ? `<tr><td style="color:var(--cm-muted);padding:5px 0;">Alt. Phone</td><td>${cmEsc(r.secondary_phone)}</td></tr>` : ''}
                <tr><td style="color:var(--cm-muted);padding:5px 0;">Email</td><td>${cmEsc(r.email||r.customer_email||'—')}</td></tr>
                <tr><td style="color:var(--cm-muted);padding:5px 0;">Address</td><td>${cmEsc(r.service_address||'—')}</td></tr>
                ${r.service_address_2 ? `<tr><td style="color:var(--cm-muted);padding:5px 0;">Address 2</td><td>${cmEsc(r.service_address_2)}</td></tr>` : ''}
                <tr><td style="color:var(--cm-muted);padding:5px 0;">City</td><td>${cmEsc(r.city_name||'—')}</td></tr>
                <tr><td style="color:var(--cm-muted);padding:5px 0;">State / ZIP</td><td>${cmEsc(r.state||'—')} ${cmEsc(r.zip_code||'')}</td></tr>
                ${r.landmark ? `<tr><td style="color:var(--cm-muted);padding:5px 0;">Landmark</td><td>${cmEsc(r.landmark)}</td></tr>` : ''}
              </table>
            </div>
          </div>

          <!-- Appliance -->
          <div class="col-md-6">
            <div class="cm-card">
              <div class="cm-card__title">Appliance Details</div>
              <table style="width:100%;font-size:.85rem;border-collapse:collapse;">
                <tr><td style="color:var(--cm-muted);padding:5px 0;width:44%;">Brand</td><td>${brandDisplay}</td></tr>
                <tr><td style="color:var(--cm-muted);padding:5px 0;">Appliance</td><td>${applianceDisplay}</td></tr>
                <tr><td style="color:var(--cm-muted);padding:5px 0;">Model #</td><td>${cmEsc(r.model_number||'—')}</td></tr>
                <tr><td style="color:var(--cm-muted);padding:5px 0;">Serial #</td><td>${cmEsc(r.serial_number||'—')}</td></tr>
                ${r.product_model_version ? `<tr><td style="color:var(--cm-muted);padding:5px 0;">Version</td><td>${cmEsc(r.product_model_version)}</td></tr>` : ''}
                ${r.warranty_type ? `<tr><td style="color:var(--cm-muted);padding:5px 0;">Warranty</td><td>${cmEsc(r.warranty_type)}</td></tr>` : ''}
                ${r.purchase_date ? `<tr><td style="color:var(--cm-muted);padding:5px 0;">Purchased</td><td>${cmEsc(r.purchase_date)}</td></tr>` : ''}
              </table>
            </div>
          </div>

          <!-- Issue Description -->
          <div class="col-md-6">
            <div class="cm-card">
              <div class="cm-card__title">Issue Description</div>
              <p style="margin:0;font-size:.86rem;line-height:1.6;white-space:pre-wrap;">${cmEsc(r.issue_description||'No description provided.')}</p>
              ${r.special_request ? `<hr style="border-color:var(--cm-border);margin:10px 0;"><div class="cm-card__title">Special Request</div><p style="margin:0;font-size:.84rem;color:var(--cm-muted);">${cmEsc(r.special_request)}</p>` : ''}
            </div>
          </div>`;

      // ── Current Technician Assignments ──
      const assignments = r.current_assignments || (r.current_assignment ? [r.current_assignment] : []);
      if (assignments.length) {
        html += `<div class="col-12"><div class="cm-card"><div class="cm-card__title">Assigned Technician${assignments.length > 1 ? 's' : ''}</div><div class="cm-table-wrap"><table class="cm-table"><thead><tr><th>Technician</th><th>Role</th><th>Phone</th><th>Status</th><th>Assigned</th></tr></thead><tbody>`;
        assignments.forEach(a => {
          html += `<tr><td><strong>${cmEsc(a.technician_name||'—')}</strong></td><td>${cmEsc(a.role_display||a.assignment_type||'—')}</td><td>${cmEsc(a.technician_phone||'—')}</td><td>${cmEsc(a.technician_status||a.status||'—')}</td><td style="font-size:.78rem;">${cmFmtDate(a.assigned_at)}</td></tr>`;
        });
        html += `</tbody></table></div></div></div>`;
      }

      // ── Notes ──
      if (r.notes && r.notes.length) {
        html += `<div class="col-12"><div class="cm-card"><div class="cm-card__title">Notes & Updates (${r.notes.length})</div>`;
        r.notes.forEach(n => {
          html += `<div style="padding:10px 0;border-bottom:1px solid var(--cm-border);">
            <div style="display:flex;justify-content:space-between;gap:8px;margin-bottom:4px;">
              <span class="cm-badge cm-badge--muted" style="font-size:.65rem;">${cmEsc(n.note_type_label||n.note_type||'Note')}</span>
              <span style="font-size:.72rem;color:var(--cm-muted);">${cmEsc(n.created_by_name||'—')} · ${cmFmtDate(n.created_at)}</span>
            </div>
            <p style="margin:0;font-size:.84rem;line-height:1.5;white-space:pre-wrap;">${cmEsc(n.note_content||n.message||'')}</p>
          </div>`;
        });
        html += `</div></div>`;
      }

      // ── Status History ──
      if (r.status_history && r.status_history.length) {
        html += `<div class="col-12"><div class="cm-card"><div class="cm-card__title">Status History</div><div class="cm-table-wrap"><table class="cm-table"><thead><tr><th>Status</th><th>Changed</th><th>By</th><th>Notes</th></tr></thead><tbody>`;
        r.status_history.forEach(h => {
          const hc = h.color_code || '#4fc3f7';
          html += `<tr>
            <td><span class="cm-badge" style="background:${hc}22;color:${hc};border:1px solid ${hc}55;">${cmEsc(h.status_name||'—')}</span></td>
            <td style="font-size:.78rem;">${cmFmtDate(h.changed_at)}</td>
            <td>${cmEsc(h.updated_by_name||'System')}</td>
            <td style="font-size:.78rem;color:var(--cm-muted);">${cmEsc(h.notes||'')}</td>
          </tr>`;
        });
        html += `</tbody></table></div></div></div>`;
      }

      // ── Images ──
      if (r.images && r.images.length) {
        html += `<div class="col-12"><div class="cm-card"><div class="cm-card__title">Uploaded Images (${r.images.length})</div><div style="display:flex;flex-wrap:wrap;gap:8px;">`;
        r.images.forEach(img => {
          html += `<a href="${cmEsc(img.image_path)}" target="_blank" style="display:block;">
            <img src="${cmEsc(img.image_path)}" style="width:90px;height:70px;object-fit:cover;border-radius:10px;border:1px solid var(--cm-border);" loading="lazy">
          </a>`;
        });
        html += `</div></div></div>`;
      }

      html += `</div>`; // close row

      body.innerHTML = html;
    },
    error: function() {
      body.innerHTML = '<div style="color:var(--cm-red);padding:20px;text-align:center;">Network error. Please try again.</div>';
    }
  });
}

// Load statuses for filter dropdown
function cmLoadStatuses() {
  $.ajax({
    url: 'ajax/get_statuses.php',
    dataType: 'json',
    success: function(res) {
      if (!res.success || !res.statuses) return;
      const sel = document.getElementById('cmTicketStatus');
      res.statuses.forEach(s => {
        const opt = document.createElement('option');
        opt.value = s.id;
        opt.textContent = s.status_name;
        sel.appendChild(opt);
      });
    }
  });
}

function cmFmtDate(d) {
  if (!d) return '—';
  try {
    return new Date(d).toLocaleDateString('en-US', { month:'short', day:'numeric', year:'numeric' });
  } catch(e) { return d; }
}

// Allow Enter key in search
document.getElementById('cmTicketSearch').addEventListener('keydown', function(e) {
  if (e.key === 'Enter') cmTicketsLoad(1);
});

document.getElementById('cmTicketView').addEventListener('change', function() {
  cmTicketsLoad(1);
});
document.getElementById('cmTicketStatus').addEventListener('change', function() {
  cmTicketsLoad(1);
});

$(document).ready(function () {
  cmLoadStatuses();
  cmTicketsLoad(1);
});
</script>

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