<?php
require_once '../includes/config.php';
require_once '../includes/functions.php';
require_once '../includes/auth.php';
requireAdminLogin();

if ($_SERVER['REQUEST_METHOD'] === 'POST' && verify_csrf()) {
    $action = $_POST['action'] ?? '';
    $tid    = (int)$_POST['ticket_id'];
    if ($action === 'reply' && $tid) {
        $msg = trim($_POST['reply_message'] ?? '');
        if ($msg) {
            $pdo->prepare("INSERT INTO ticket_replies (ticket_id,sender_id,sender_type,message) VALUES (?,?,'admin',?)")->execute([$tid,$_SESSION['admin_id'],$msg]);
            $pdo->prepare("UPDATE support_tickets SET status='in_progress',updated_at=NOW() WHERE id=?")->execute([$tid]);
            $t2 = $pdo->prepare("SELECT user_id FROM support_tickets WHERE id=? LIMIT 1"); $t2->execute([$tid]); $t3=$t2->fetch();
            if ($t3) addNotification($pdo,$t3['user_id'],'Support Reply','The support team has replied to your ticket.','info',$tid,'ticket');
            flash('success','Reply sent.');
        }
    }
    if ($action === 'close') { $pdo->prepare("UPDATE support_tickets SET status='closed',closed_at=NOW() WHERE id=?")->execute([$tid]); flash('success','Ticket closed.'); }
    if ($action === 'open')  { $pdo->prepare("UPDATE support_tickets SET status='open' WHERE id=?")->execute([$tid]); flash('success','Ticket re-opened.'); }
    header('Location: /admin/support.php' . ($tid && $_GET['view']??false ? '?view='.$tid : '')); exit;
}

$viewTicket = null; $viewReplies = [];
if (isset($_GET['view'])) {
    $vs = $pdo->prepare("SELECT t.*, CONCAT(u.first_name,' ',u.last_name) AS user_name, u.email AS user_email FROM support_tickets t JOIN users u ON t.user_id=u.id WHERE t.id=? LIMIT 1");
    $vs->execute([(int)$_GET['view']]); $viewTicket=$vs->fetch();
    if ($viewTicket) { $r=$pdo->prepare("SELECT * FROM ticket_replies WHERE ticket_id=? ORDER BY created_at ASC"); $r->execute([$viewTicket['id']]); $viewReplies=$r->fetchAll(); }
}

$sf = $_GET['status'] ?? 'open';
$tickets = $pdo->prepare("SELECT t.*, CONCAT(u.first_name,' ',u.last_name) AS user_name FROM support_tickets t JOIN users u ON t.user_id=u.id WHERE t.status=? ORDER BY t.updated_at DESC");
$tickets->execute([$sf]); $ticketList=$tickets->fetchAll();
$pageTitle = 'Support Tickets';
?>
<?php include '../includes/header.php'; ?>
<div class="page-title"><i class="fa fa-headset me-2 text-danger"></i>Support Tickets</div>
<ul class="nav nav-tabs mb-4">
  <?php foreach (['open'=>'Open','in_progress'=>'In Progress','pending_user'=>'Pending User','resolved'=>'Resolved','closed'=>'Closed'] as $s=>$l): ?>
  <li class="nav-item"><a class="nav-link <?= $sf===$s?'active':'' ?>" href="?status=<?= $s ?>"><?= $l ?></a></li>
  <?php endforeach; ?>
</ul>

<div class="row g-4">
  <div class="col-lg-<?= $viewTicket ? '4' : '12' ?>">
    <div class="card">
      <div class="table-responsive">
        <table class="table table-hover mb-0 small">
          <thead><tr><th>Ticket</th><th>User</th><th>Subject</th><th>Priority</th><th>Updated</th></tr></thead>
          <tbody>
          <?php if (empty($ticketList)): ?><tr><td colspan="5" class="text-center py-3 text-muted">No <?= $sf ?> tickets.</td></tr>
          <?php else: foreach ($ticketList as $t): ?>
          <tr class="<?= (isset($_GET['view']) && $_GET['view']==$t['id']) ? 'table-active' : '' ?>">
            <td><a href="?status=<?= $sf ?>&view=<?= $t['id'] ?>" class="text-decoration-none"><code><?= sanitize($t['ticket_number']) ?></code></a></td>
            <td><?= sanitize($t['user_name']) ?></td>
            <td><?= sanitize(substr($t['subject'],0,30)) ?></td>
            <td><?= statusBadge($t['priority']) ?></td>
            <td><?= timeAgo($t['updated_at']) ?></td>
          </tr>
          <?php endforeach; endif; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>
  <?php if ($viewTicket): ?>
  <div class="col-lg-8">
    <div class="card">
      <div class="card-header d-flex justify-content-between align-items-center">
        <div><code><?= sanitize($viewTicket['ticket_number']) ?></code> — <?= sanitize($viewTicket['subject']) ?> <?= statusBadge($viewTicket['status']) ?></div>
        <form method="POST">
          <?= csrf_field() ?><input type="hidden" name="ticket_id" value="<?= $viewTicket['id'] ?>">
          <?php if ($viewTicket['status']!=='closed'): ?>
          <button name="action" value="close" class="btn btn-sm btn-outline-danger">Close Ticket</button>
          <?php else: ?><button name="action" value="open" class="btn btn-sm btn-outline-success">Re-open</button><?php endif; ?>
        </form>
      </div>
      <div class="card-body" style="max-height:450px;overflow-y:auto;">
        <div class="small text-muted mb-3">From: <strong><?= sanitize($viewTicket['user_name']) ?></strong> (<?= sanitize($viewTicket['user_email']) ?>) &bull; <?= formatDate($viewTicket['created_at']) ?></div>
        <!-- Original -->
        <div class="bg-light rounded p-3 mb-3">
          <div class="fw-bold small text-muted mb-1">Customer</div>
          <?= nl2br(sanitize($viewTicket['message'])) ?>
        </div>
        <?php foreach ($viewReplies as $rep): $isAdmin=$rep['sender_type']==='admin'; ?>
        <div class="d-flex gap-3 mb-3 <?= $isAdmin?'flex-row-reverse':'' ?>">
          <div class="<?= $isAdmin?'bg-primary text-white':'bg-light' ?> rounded p-3 flex-grow-1 small" style="max-width:85%">
            <div class="fw-bold <?= $isAdmin?'text-white-50':'text-muted' ?>"><?= $isAdmin?'Support Agent':'Customer' ?> &bull; <?= timeAgo($rep['created_at']) ?></div>
            <div class="mt-1"><?= nl2br(sanitize($rep['message'])) ?></div>
          </div>
        </div>
        <?php endforeach; ?>
      </div>
      <?php if ($viewTicket['status']!=='closed'): ?>
      <div class="card-footer">
        <form method="POST" class="d-flex gap-2">
          <?= csrf_field() ?><input type="hidden" name="action" value="reply"><input type="hidden" name="ticket_id" value="<?= $viewTicket['id'] ?>">
          <textarea name="reply_message" class="form-control form-control-sm" rows="2" placeholder="Type your reply..." required></textarea>
          <button class="btn btn-primary px-3">Send</button>
        </form>
      </div>
      <?php endif; ?>
    </div>
  </div>
  <?php endif; ?>
</div>
<?php include '../includes/footer.php'; ?>
