<?php
use App\Core\Auth;
use App\Core\Database;

$respPct = null; $resPct = null;
if ($ticket['response_due_at'] && !$ticket['first_response_at']) {
    $total = max(1, strtotime($ticket['response_due_at']) - strtotime($ticket['created_at']));
    $elapsed = max(0, time() - strtotime($ticket['created_at']));
    $respPct = min(100, round(($elapsed / $total) * 100));
}
if ($ticket['resolution_due_at'] && !in_array($ticket['status'], ['RESOLVED', 'CLOSED'])) {
    $total = max(1, strtotime($ticket['resolution_due_at']) - strtotime($ticket['created_at']));
    $elapsed = max(0, time() - strtotime($ticket['created_at']) - (int)$ticket['sla_paused_seconds']);
    $resPct = min(100, round(($elapsed / $total) * 100));
}
?>
<div class="ticket-header">
  <h2 class="mono" style="margin:0"><?= e($ticket['ticket_no']) ?></h2>
  <?= priority_badge(['code' => $priority['code'], 'color' => $priority['color']]) ?>
  <span class="<?= status_badge_class($ticket['status']) ?>"><?= status_label($ticket['status']) ?></span>
  <?php if ($ticket['is_response_breached'] || $ticket['is_resolution_breached']) : ?><span class="badge badge-breach">SLA BREACHED</span><?php endif; ?>
  <?php if ($ticket['is_out_of_entitlement']) : ?><span class="badge badge-oe">OUT OF ENTITLEMENT</span><?php endif; ?>
  <?php if ($ticket['escalation_level'] > 0) : ?><span class="badge badge-escalated">Escalation L<?= $ticket['escalation_level'] ?></span><?php endif; ?>
</div>
<p class="text-faint" style="margin-bottom:18px"><?= e($customer['name']) ?> · <?= e($contact['name']) ?> · <?= e($product['name'] ?? '') ?></p>

<div class="ticket-grid">
  <div>
    <div class="tabs" data-tabs>
      <a href="#" class="tab active" data-tab="conversation">Conversation</a>
      <a href="#" class="tab" data-tab="details">Details</a>
      <a href="#" class="tab" data-tab="attachments">Attachments (<?= count($attachments) ?>)</a>
      <a href="#" class="tab" data-tab="time">Time Log (<?= count($timeLogs) ?>)</a>
      <a href="#" class="tab" data-tab="audit">Audit Trail</a>
    </div>

    <div data-tab-panel="conversation">
      <div class="thread">
        <?php foreach ($messages as $m) :
          $authorName = $m['user_name'] ?? $m['contact_name'] ?? 'System';
          $isInternal = $m['type'] === 'internal_note';
        ?>
          <div class="msg msg-<?= e($m['type']) ?>">
            <div class="msg-head">
              <span><span class="msg-author"><?= e($authorName) ?></span>
                <?php if ($isInternal) : ?><span class="msg-tag internal">Internal note</span>
                <?php elseif ($m['type'] === 'public_reply') : ?><span class="msg-tag public">Public reply</span>
                <?php elseif ($m['type'] === 'inbound_email') : ?><span class="msg-tag public">Inbound email</span>
                <?php endif; ?>
              </span>
              <span class="msg-time"><?= fmt_dt($m['created_at']) ?></span>
            </div>
            <div class="msg-body"><?= nl2br(e($m['body'])) ?></div>
            <?php if (!empty($attachmentsByMsg[$m['id']])) : ?>
              <div class="msg-attachments">
                <?php foreach ($attachmentsByMsg[$m['id']] as $a) : ?>
                  <a class="attachment-chip" href="<?= url('/tickets/' . $ticket['id'] . '/attachment/' . $a['id']) ?>">📎 <?= e($a['original_name']) ?></a>
                <?php endforeach; ?>
              </div>
            <?php endif; ?>
          </div>
        <?php endforeach; ?>
      </div>

      <?php if (!in_array($ticket['status'], ['CLOSED', 'REJECTED'])) : ?>
      <div class="reply-box">
        <form method="post" action="<?= url('/tickets/' . $ticket['id'] . '/reply') ?>" enctype="multipart/form-data" data-confirm-public-reply data-has-internal-notes="<?= $hasInternalNotes ? '1' : '0' ?>">
          <?= csrf_field() ?>
          <div class="flex items-center justify-between mb-0" style="margin-bottom:8px">
            <label class="mb-0">Reply to customer</label>
            <select data-canned-select data-target="#reply-body" style="width:auto;font-size:12px">
              <option value="">Insert canned response…</option>
              <?php foreach ($canned as $c) : ?><option data-body="<?= e($c['body']) ?>"><?= e($c['title']) ?></option><?php endforeach; ?>
            </select>
          </div>
          <textarea id="reply-body" name="body" rows="4" placeholder="Visible to the customer…" required></textarea>
          <div class="reply-actions">
            <div class="reply-actions-left">
              <button type="submit" class="btn btn-primary btn-sm">Send public reply</button>
              <label class="btn btn-sm btn-ghost" style="cursor:pointer">
                📎 Attach<input type="file" name="attachments[]" multiple data-file-preview="#att-preview-reply" style="display:none">
              </label>
            </div>
          </div>
          <div id="att-preview-reply" class="help-text mt-2"></div>
        </form>
        <hr style="border:none;border-top:1px solid var(--line);margin:14px 0">
        <form method="post" action="<?= url('/tickets/' . $ticket['id'] . '/note') ?>" enctype="multipart/form-data">
          <?= csrf_field() ?>
          <label>Internal note <span class="text-faint">(never visible to the customer)</span></label>
          <textarea name="body" rows="3" placeholder="Notes for the team…" required></textarea>
          <div class="reply-actions">
            <button type="submit" class="btn btn-sm" style="background:var(--amber-bg);border-color:#fde68a;color:#92400e">Add internal note</button>
            <label class="btn btn-sm btn-ghost" style="cursor:pointer">
              📎 Attach<input type="file" name="attachments[]" multiple data-file-preview="#att-preview-note" style="display:none">
            </label>
          </div>
          <div id="att-preview-note" class="help-text mt-2"></div>
        </form>
      </div>
      <?php endif; ?>
    </div>

    <div data-tab-panel="details" style="display:none">
      <div class="card">
        <div class="card-body">
          <div class="kv"><span class="k">Subject</span><span class="v"><?= e($ticket['subject']) ?></span></div>
          <div class="kv"><span class="k">Description</span><span class="v" style="text-align:left;max-width:400px"><?= nl2br(e($ticket['description'])) ?></span></div>
          <div class="kv"><span class="k">Category</span><span class="v"><?= e($category['name']) ?></span></div>
          <div class="kv"><span class="k">Severity</span><span class="v"><?= e($ticket['severity']) ?></span></div>
          <div class="kv"><span class="k">Channel</span><span class="v"><?= e($ticket['channel']) ?></span></div>
          <div class="kv"><span class="k">Version</span><span class="v"><?= e($ticket['version'] ?: '—') ?></span></div>
          <div class="kv"><span class="k">Reassignments</span><span class="v"><?= (int)$ticket['reassignment_count'] ?></span></div>
        </div>
      </div>

      <?php if (Auth::isAny(['L1','L2','L3','LEAD','HEAD','ADMIN'])) : ?>
      <div class="card mt-3">
        <div class="card-header"><h3>Change classification</h3></div>
        <div class="card-body">
          <form method="post" action="<?= url('/tickets/' . $ticket['id'] . '/classify') ?>">
            <?= csrf_field() ?>
            <div class="form-row">
              <div class="form-group">
                <label>Priority</label>
                <select name="priority_id">
                  <?php foreach ($priorities as $p) : ?><option value="<?= $p['id'] ?>" <?= $p['id']==$ticket['priority_id']?'selected':'' ?>><?= e($p['code']) ?> — <?= e($p['name']) ?></option><?php endforeach; ?>
                </select>
              </div>
              <div class="form-group">
                <label>Category</label>
                <select name="category_id">
                  <?php foreach ($categories as $c) : ?><option value="<?= $c['id'] ?>" <?= $c['id']==$ticket['category_id']?'selected':'' ?>><?= e($c['name']) ?></option><?php endforeach; ?>
                </select>
              </div>
            </div>
            <div class="form-group">
              <label>Severity</label>
              <select name="severity">
                <?php foreach (['Business stopped','Major impact','Minor impact','Cosmetic'] as $sv) : ?>
                  <option <?= $sv===$ticket['severity']?'selected':'' ?>><?= $sv ?></option>
                <?php endforeach; ?>
              </select>
            </div>
            <div class="form-group">
              <label>Reason for change <span class="req">*</span></label>
              <input type="text" name="reason" required placeholder="Why is this changing?">
            </div>
            <button type="submit" class="btn btn-sm">Save classification</button>
          </form>
        </div>
      </div>

      <div class="card mt-3">
        <div class="card-header"><h3>Link a development defect / change request</h3></div>
        <div class="card-body">
          <?php if ($ticket['linked_record_ref']) : ?>
            <div class="kv"><span class="k"><?= e($ticket['linked_record_type']) ?></span><span class="v"><?= e($ticket['linked_record_ref']) ?> — <?= e($ticket['linked_record_status']) ?></span></div>
          <?php endif; ?>
          <form method="post" action="<?= url('/tickets/' . $ticket['id'] . '/link') ?>" class="mt-2">
            <?= csrf_field() ?>
            <div class="form-row">
              <select name="linked_record_type" style="max-width:140px">
                <option>Defect</option><option>Change Request</option>
              </select>
              <input type="text" name="linked_record_ref" placeholder="e.g. BUG-2026-0913" required>
            </div>
            <button type="submit" class="btn btn-sm mt-2">Save link</button>
          </form>
        </div>
      </div>
      <?php endif; ?>
    </div>

    <div data-tab-panel="attachments" style="display:none">
      <div class="card">
        <div class="table-wrap">
          <table class="table">
            <thead><tr><th>File</th><th>Size</th><th>Uploaded by</th><th>When</th><th></th></tr></thead>
            <tbody>
            <?php foreach ($attachments as $a) : ?>
              <tr>
                <td>📎 <?= e($a['original_name']) ?></td>
                <td class="text-sm"><?= number_format($a['size_bytes'] / 1024, 1) ?> KB</td>
                <td class="text-sm"><?= e($a['uploaded_by_user_name'] ?? $a['uploaded_by_contact_name'] ?? 'Email intake') ?></td>
                <td class="text-sm"><?= fmt_dt($a['created_at']) ?></td>
                <td><a class="btn btn-sm" href="<?= url('/tickets/' . $ticket['id'] . '/attachment/' . $a['id']) ?>">Download</a></td>
              </tr>
            <?php endforeach; ?>
            <?php if (empty($attachments)) : ?><tr><td colspan="5" class="text-faint">No attachments on this ticket yet.</td></tr><?php endif; ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>

    <div data-tab-panel="time" style="display:none">
      <div class="card">
        <div class="card-header"><h3>Effort log</h3></div>
        <div class="table-wrap">
          <table class="table">
            <thead><tr><th>Date</th><th>Agent</th><th>Activity</th><th>Duration</th><th>Billable</th><th>Description</th></tr></thead>
            <tbody>
            <?php foreach ($timeLogs as $tl) : ?>
              <tr>
                <td><?= fmt_d($tl['log_date']) ?></td>
                <td><?= e($tl['user_name']) ?></td>
                <td><?= e($tl['activity_type']) ?></td>
                <td><?= fmt_minutes((int)$tl['duration_minutes']) ?></td>
                <td><?= $tl['is_billable'] ? '<span class="badge badge-oe">Billable</span>' : '<span class="text-faint">No</span>' ?></td>
                <td class="text-sm"><?= e($tl['description']) ?></td>
              </tr>
            <?php endforeach; ?>
            <?php if (empty($timeLogs)) : ?><tr><td colspan="6" class="text-faint">No effort logged yet.</td></tr><?php endif; ?>
            </tbody>
          </table>
        </div>
        <div class="card-body">
          <form method="post" action="<?= url('/tickets/' . $ticket['id'] . '/time') ?>">
            <?= csrf_field() ?>
            <div class="form-row">
              <div class="form-group"><label>Date</label><input type="date" name="log_date" value="<?= date('Y-m-d') ?>" required></div>
              <div class="form-group"><label>Duration (minutes)</label><input type="number" name="duration_minutes" min="1" required></div>
            </div>
            <div class="form-row">
              <div class="form-group">
                <label>Activity type</label>
                <select name="activity_type"><option>Investigation</option><option>Fix</option><option>Customer call</option><option>Configuration</option><option>Testing</option></select>
              </div>
              <?php if (Auth::can('billing.mark_billable')) : ?>
              <div class="form-group checkbox-row" style="margin-top:26px">
                <input type="checkbox" name="is_billable" value="1" id="is_billable"><label for="is_billable" class="mb-0">Billable (outside entitlement)</label>
              </div>
              <?php endif; ?>
            </div>
            <div class="form-group"><label>Description</label><input type="text" name="description" placeholder="What was done"></div>
            <button type="submit" class="btn btn-sm">Log effort</button>
          </form>
        </div>
      </div>
    </div>

    <div data-tab-panel="audit" style="display:none">
      <div class="card">
        <div class="card-body timeline">
          <?php foreach ($auditLog as $a) : ?>
            <div class="timeline-item">
              <div class="timeline-dot"></div>
              <div>
                <strong><?= e($a['user_name'] ?? 'System') ?></strong> — <?= e(str_replace('_', ' ', $a['action'])) ?>
                <?php if ($a['field_name']) : ?>(<?= e($a['field_name']) ?>: <?= e($a['old_value']) ?> → <?= e($a['new_value']) ?>)<?php endif; ?>
                <div class="text-faint"><?= fmt_dt($a['created_at']) ?></div>
              </div>
            </div>
          <?php endforeach; ?>
          <?php if (empty($auditLog)) : ?><div class="text-faint">No audit entries.</div><?php endif; ?>
        </div>
      </div>
    </div>
  </div>

  <div class="side-panel">
    <div class="card">
      <div class="card-header"><h3>SLA</h3></div>
      <div class="card-body">
        <div class="sla-row">
          <span>First response</span>
          <span><?= $ticket['first_response_at'] ? '<span class="badge badge-resolved">Met</span>' : ($ticket['is_response_breached'] ? '<span class="badge badge-breach">Breached</span>' : fmt_remaining($ticket['response_due_at'], false)) ?></span>
        </div>
        <?php if ($respPct !== null) : ?><div class="progress"><div class="progress-bar" style="width:<?= $respPct ?>%;background:<?= $respPct>=80?'var(--red)':'var(--brand)' ?>"></div></div><?php endif; ?>

        <div class="sla-row" style="margin-top:10px">
          <span>Resolution</span>
          <span><?= in_array($ticket['status'],['RESOLVED','CLOSED']) ? '<span class="badge badge-resolved">Met</span>' : ($ticket['is_resolution_breached'] ? '<span class="badge badge-breach">Breached</span>' : fmt_remaining($ticket['resolution_due_at'], false)) ?></span>
        </div>
        <?php if ($resPct !== null) : ?><div class="progress"><div class="progress-bar" style="width:<?= $resPct ?>%;background:<?= $resPct>=80?'var(--red)':'var(--brand)' ?>"></div></div><?php endif; ?>

        <div class="kv mt-3"><span class="k">Policy</span><span class="v"><?= e($slaPolicy['name'] ?? '—') ?></span></div>
        <div class="kv"><span class="k">Response target</span><span class="v"><?= $ticket['first_response_minutes'] ? fmt_minutes($ticket['first_response_minutes']) : '—' ?></span></div>
        <div class="kv"><span class="k">Resolution target</span><span class="v"><?= $ticket['resolution_minutes'] ? fmt_minutes($ticket['resolution_minutes']) : '—' ?></span></div>
        <div class="kv"><span class="k">Paused time</span><span class="v"><?= fmt_minutes((int)round($ticket['sla_paused_seconds'] / 60)) ?></span></div>
        <div class="kv"><span class="k">Created</span><span class="v"><?= fmt_dt($ticket['created_at']) ?></span></div>
      </div>
    </div>

    <div class="card">
      <div class="card-header"><h3>Ticket details</h3></div>
      <div class="card-body">
        <div class="kv"><span class="k">Customer</span><span class="v"><a href="<?= url('/admin/customers/' . $customer['id']) ?>"><?= e($customer['name']) ?></a></span></div>
        <div class="kv"><span class="k">Contact</span><span class="v"><?= e($contact['name']) ?></span></div>
        <div class="kv"><span class="k">Contract</span><span class="v"><?= e($contract['contract_no'] ?? 'None') ?> <?= $contract ? '· ' . e($contract['tier']) : '' ?></span></div>
        <div class="kv"><span class="k">Product / Module</span><span class="v"><?= e($product['name'] ?? '') ?></span></div>
        <div class="kv"><span class="k">Queue</span><span class="v"><?= e(Database::scalar('SELECT name FROM queues WHERE id = :id', ['id' => $ticket['queue_id']]) ?? '—') ?></span></div>
        <div class="kv"><span class="k">Assignee</span><span class="v"><?= e($assignee['name'] ?? 'Unassigned') ?></span></div>
        <?php if ($ticket['linked_record_ref']) : ?><div class="kv"><span class="k">Linked record</span><span class="v"><?= e($ticket['linked_record_ref']) ?></span></div><?php endif; ?>
      </div>
    </div>

    <div class="card">
      <div class="card-header"><h3>Actions</h3></div>
      <div class="card-body" style="display:flex;flex-direction:column;gap:8px">
        <?php if (!$ticket['assignee_id']) : ?>
          <form method="post" action="<?= url('/tickets/' . $ticket['id'] . '/claim') ?>"><?= csrf_field() ?><button class="btn btn-primary btn-block btn-sm">Claim this ticket</button></form>
        <?php endif; ?>

        <?php if (Auth::can('ticket.assign')) : ?>
          <form method="post" action="<?= url('/tickets/' . $ticket['id'] . '/assign') ?>">
            <?= csrf_field() ?>
            <select name="assignee_id" required>
              <option value="">Reassign to…</option>
              <?php foreach ($agents as $a) : ?><option value="<?= $a['id'] ?>" <?= $a['id']==$ticket['assignee_id']?'selected':'' ?>><?= e($a['name']) ?></option><?php endforeach; ?>
            </select>
            <button class="btn btn-block btn-sm mt-2">Reassign</button>
          </form>
        <?php endif; ?>

        <?php if (in_array('PENDING_CUSTOMER', $allowedTransitions)) : ?>
          <form method="post" action="<?= url('/tickets/' . $ticket['id'] . '/status') ?>"><?= csrf_field() ?><input type="hidden" name="status" value="PENDING_CUSTOMER"><input type="hidden" name="reason" value="Awaiting customer response"><button class="btn btn-block btn-sm">Set Pending Customer</button></form>
        <?php endif; ?>
        <?php if (in_array('PENDING_THIRD_PARTY', $allowedTransitions)) : ?>
          <form method="post" action="<?= url('/tickets/' . $ticket['id'] . '/status') ?>"><?= csrf_field() ?><input type="hidden" name="status" value="PENDING_THIRD_PARTY"><input type="hidden" name="reason" value="Awaiting third party"><button class="btn btn-block btn-sm">Set Pending Third Party</button></form>
        <?php endif; ?>
        <?php if (in_array('IN_PROGRESS', $allowedTransitions)) : ?>
          <form method="post" action="<?= url('/tickets/' . $ticket['id'] . '/status') ?>"><?= csrf_field() ?><input type="hidden" name="status" value="IN_PROGRESS"><button class="btn btn-block btn-sm">Move to In Progress</button></form>
        <?php endif; ?>

        <?php if (in_array('RESOLVED', $allowedTransitions) && Auth::can('ticket.resolve_close')) : ?>
          <details>
            <summary class="btn btn-block btn-sm" style="cursor:pointer">Mark resolved</summary>
            <form method="post" action="<?= url('/tickets/' . $ticket['id'] . '/status') ?>" class="mt-2">
              <?= csrf_field() ?><input type="hidden" name="status" value="RESOLVED">
              <div class="form-group"><label>Resolution code <span class="req">*</span></label>
                <select name="resolution_code" required><option>Configuration fix</option><option>Software defect fixed</option><option>User error — guidance given</option><option>Data correction</option><option>Duplicate</option><option>No fault found</option></select>
              </div>
              <div class="form-group"><label>Root cause <span class="req">*</span></label>
                <select name="root_cause" required><option>User setup error</option><option>Data quality</option><option>Software defect</option><option>Third-party dependency</option><option>Environment / infrastructure</option><option>Process gap</option></select>
              </div>
              <button class="btn btn-primary btn-block btn-sm">Confirm resolve</button>
            </form>
          </details>
        <?php endif; ?>

        <?php if (in_array('CLOSED', $allowedTransitions) && Auth::can('ticket.resolve_close')) : ?>
          <form method="post" action="<?= url('/tickets/' . $ticket['id'] . '/status') ?>"><?= csrf_field() ?><input type="hidden" name="status" value="CLOSED"><button class="btn btn-block btn-sm" style="background:var(--green-bg);border-color:#bbf7d0;color:#166534">Close ticket</button></form>
        <?php endif; ?>
        <?php if (in_array('REOPENED', $allowedTransitions)) : ?>
          <form method="post" action="<?= url('/tickets/' . $ticket['id'] . '/status') ?>"><?= csrf_field() ?><input type="hidden" name="status" value="REOPENED"><input type="hidden" name="reason" value="Reopened by agent"><button class="btn btn-block btn-sm">Reopen</button></form>
        <?php endif; ?>

        <?php if (!in_array($ticket['status'], ['CLOSED', 'REJECTED', 'RESOLVED']) && Auth::can('ticket.escalate')) : ?>
        <details>
          <summary class="btn btn-block btn-sm" style="cursor:pointer;color:var(--red)">Escalate…</summary>
          <form method="post" action="<?= url('/tickets/' . $ticket['id'] . '/escalate') ?>" class="mt-2">
            <?= csrf_field() ?>
            <textarea name="reason" rows="2" placeholder="Reason for escalation" required></textarea>
            <button class="btn btn-danger btn-block btn-sm mt-2">Escalate to next level</button>
          </form>
        </details>
        <?php endif; ?>

        <?php if (in_array('REJECTED', $allowedTransitions)) : ?>
        <details>
          <summary class="btn btn-block btn-sm" style="cursor:pointer">Reject…</summary>
          <form method="post" action="<?= url('/tickets/' . $ticket['id'] . '/status') ?>" class="mt-2">
            <?= csrf_field() ?><input type="hidden" name="status" value="REJECTED">
            <textarea name="reason" rows="2" placeholder="Reason for rejection" required></textarea>
            <button class="btn btn-block btn-sm mt-2">Confirm reject</button>
          </form>
        </details>
        <?php endif; ?>

        <form method="post" action="<?= url('/tickets/' . $ticket['id'] . '/watch') ?>"><?= csrf_field() ?><button class="btn btn-block btn-sm btn-ghost">👁 Watch this ticket</button></form>

        <form method="post" action="<?= url('/tickets/' . $ticket['id'] . '/attachment') ?>" enctype="multipart/form-data" class="mt-2">
          <?= csrf_field() ?>
          <label>Add attachment</label>
          <input type="file" name="attachment" required>
          <button class="btn btn-block btn-sm mt-2">Upload</button>
        </form>
      </div>
    </div>
  </div>
</div>
