<?php
require_once 'includes/config.php';
require_once 'includes/functions.php';
require_once 'includes/auth.php';
requireUserLogin();
$currentUser = currentUser($pdo);
$uid = (int)$_SESSION['user_id'];
$error = ''; $success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && verify_csrf()) {
    $action = $_POST['action'] ?? '';
    if ($action === 'new_ticket') {
        $subject  = trim($_POST['subject'] ?? '');
        $message  = trim($_POST['message'] ?? '');
        $priority = $_POST['priority'] ?? 'normal';
        $category = $_POST['category'] ?? 'general';
        if (!$subject || !$message) { $error = 'Subject and message are required.'; goto done; }
        $ticketNo = 'TKT-' . date('Ymd') . '-' . strtoupper(bin2hex(random_bytes(3)));
        $pdo->prepare("INSERT INTO support_tickets (user_id,ticket_number,subject,message,priority,category,status) VALUES (?,?,?,?,?,?,'open')")->execute([$uid,$ticketNo,$subject,$message,$priority,$category]);
        $tid = (int)$pdo->lastInsertId();
        addNotification($pdo, $uid, 'Ticket Created', "Your support ticket ($ticketNo) has been created.", 'info', $tid, 'ticket');
        $success = "Ticket <strong>$ticketNo</strong> created. We'll respond shortly.";
    }
    if ($action === 'reply') {
        $tid = (int)($_POST['ticket_id'] ?? 0);
        $msg = trim($_POST['reply_message'] ?? '');
        if (!$tid || !$msg) { $error = 'Message cannot be empty.'; goto done; }
        // Verify ownership
        $ownCheck = $pdo->prepare("SELECT id FROM support_tickets WHERE id=? AND user_id=? LIMIT 1");
        $ownCheck->execute([$tid,$uid]);
        if (!$ownCheck->fetch()) { $error = 'Ticket not found.'; goto done; }
        $pdo->prepare("INSERT INTO ticket_replies (ticket_id,sender_id,sender_type,message) VALUES (?,?,'user',?)")->execute([$tid,$uid,$msg]);
        $pdo->prepare("UPDATE support_tickets SET status='in_progress',updated_at=NOW() WHERE id=?")->execute([$tid]);
        $success = 'Reply sent.';
    }
}
done:

$viewTicket = null;
if (isset($_GET['view'])) {
    $vs = $pdo->prepare("SELECT * FROM support_tickets WHERE id=? AND user_id=? LIMIT 1");
    $vs->execute([(int)$_GET['view'], $uid]); $viewTicket = $vs->fetch();
    if ($viewTicket) {
        $replies = $pdo->prepare("SELECT * FROM ticket_replies WHERE ticket_id=? ORDER BY created_at ASC");
        $replies->execute([$viewTicket['id']]); $viewReplies = $replies->fetchAll();
    }
}

$tickets = $pdo->prepare("SELECT * FROM support_tickets WHERE user_id=? ORDER BY updated_at DESC");
$tickets->execute([$uid]); $ticketList = $tickets->fetchAll();
$pageTitle = 'Support';
?>
<!DOCTYPE html><html lang="en"><head>
<meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title><?= $pageTitle ?> | <?= SITE_NAME ?></title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
<link rel="stylesheet" href="/assets/css/style.css">
</head><body>
<?php include 'includes/header.php'; ?>
<div class="page-wrapper"><div class="container">
<div class="d-flex justify-content-between align-items-center mb-3">
  <div class="page-title mb-0"><i class="fa fa-headset me-2 text-danger"></i>Support Center</div>
  <button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#newTicketModal"><i class="fa fa-plus me-1"></i>New Ticket</button>
</div>
<?php if ($error): ?><div class="alert alert-danger"><?= sanitize($error) ?></div><?php endif; ?>
<?php if ($success): ?><div class="alert alert-success"><?= $success ?></div><?php endif; ?>

<?php if ($viewTicket): ?>
<div class="card mb-3">
  <div class="card-header d-flex justify-content-between align-items-center">
    <div>
      <strong><?= sanitize($viewTicket['ticket_number']) ?></strong> &mdash; <?= sanitize($viewTicket['subject']) ?>
      <?= statusBadge($viewTicket['status']) ?>
    </div>
    <a href="/support.php" class="btn btn-sm btn-outline-secondary"><i class="fa fa-arrow-left me-1"></i>Back</a>
  </div>
  <div class="card-body" style="max-height:450px;overflow-y:auto;">
    <!-- Original message -->
    <div class="d-flex gap-3 mb-3">
      <div class="flex-shrink-0"><div style="width:38px;height:38px;border-radius:50%;background:var(--primary);color:#fff;display:flex;align-items:center;justify-content:center;font-weight:700"><?= strtoupper(substr($currentUser['first_name'],0,1)) ?></div></div>
      <div class="bg-light rounded p-3 flex-grow-1">
        <div class="fw-bold small text-muted"><?= sanitize($currentUser['first_name'].' '.$currentUser['last_name']) ?> &bull; <?= formatDate($viewTicket['created_at']) ?></div>
        <div class="mt-1"><?= nl2br(sanitize($viewTicket['message'])) ?></div>
      </div>
    </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="flex-shrink-0">
        <div style="width:38px;height:38px;border-radius:50%;background:<?= $isAdmin?'#1abc9c':'var(--primary)' ?>;color:#fff;display:flex;align-items:center;justify-content:center;">
          <i class="fa fa-<?= $isAdmin?'headset':'user' ?>"></i>
        </div>
      </div>
      <div class="<?= $isAdmin?'bg-success text-white':'bg-light' ?> rounded p-3 flex-grow-1" style="max-width:80%">
        <div class="fw-bold small <?= $isAdmin?'text-white-50':'text-muted' ?>"><?= $isAdmin?SITE_NAME.' Support':'You' ?> &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" rows="2" placeholder="Type your reply..." required></textarea>
      <button class="btn btn-primary px-4">Send</button>
    </form>
  </div>
  <?php endif; ?>
</div>
<?php else: ?>
<!-- Ticket List -->
<div class="card">
  <div class="table-responsive">
    <table class="table table-hover mb-0">
      <thead><tr><th>Ticket</th><th>Subject</th><th>Category</th><th>Priority</th><th>Status</th><th>Updated</th><th></th></tr></thead>
      <tbody>
        <?php if (empty($ticketList)): ?>
        <tr><td colspan="7" class="text-center py-4 text-muted"><i class="fa fa-ticket-alt fa-2x d-block mb-2"></i>No tickets yet. Click "New Ticket" to get help.</td></tr>
        <?php else: foreach ($ticketList as $t): ?>
        <tr>
          <td><code class="small"><?= sanitize($t['ticket_number']) ?></code></td>
          <td><?= sanitize(substr($t['subject'],0,45)) ?></td>
          <td><span class="badge bg-secondary"><?= ucfirst($t['category']) ?></span></td>
          <td><?= statusBadge($t['priority']) ?></td>
          <td><?= statusBadge($t['status']) ?></td>
          <td class="small text-muted"><?= timeAgo($t['updated_at']) ?></td>
          <td><a href="?view=<?= $t['id'] ?>" class="btn btn-sm btn-outline-primary"><i class="fa fa-eye"></i></a></td>
        </tr>
        <?php endforeach; endif; ?>
      </tbody>
    </table>
  </div>
</div>
<?php endif; ?>
</div></div>
<?php include 'includes/footer.php'; ?>

<!-- New Ticket Modal -->
<div class="modal fade" id="newTicketModal" tabindex="-1"><div class="modal-dialog modal-lg"><div class="modal-content">
  <div class="modal-header"><h5 class="modal-title"><i class="fa fa-ticket-alt me-2"></i>New Support Ticket</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
  <form method="POST"><div class="modal-body">
    <?= csrf_field() ?><input type="hidden" name="action" value="new_ticket">
    <div class="row g-3">
      <div class="col-12"><label class="form-label">Subject *</label><input type="text" name="subject" class="form-control" required></div>
      <div class="col-md-6"><label class="form-label">Category</label>
        <select name="category" class="form-select">
          <option value="general">General</option><option value="transaction">Transaction</option>
          <option value="account">Account</option><option value="card">Card</option>
          <option value="loan">Loan</option><option value="investment">Investment</option>
          <option value="security">Security</option><option value="other">Other</option>
        </select>
      </div>
      <div class="col-md-6"><label class="form-label">Priority</label>
        <select name="priority" class="form-select">
          <option value="low">Low</option><option value="normal" selected>Normal</option>
          <option value="high">High</option><option value="urgent">Urgent</option>
        </select>
      </div>
      <div class="col-12"><label class="form-label">Message *</label><textarea name="message" class="form-control" rows="5" placeholder="Describe your issue in detail..." required></textarea></div>
    </div>
  </div>
  <div class="modal-footer"><button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button><button class="btn btn-primary">Submit Ticket</button></div>
  </form>
</div></div></div>
</body></html>
