<?php
session_start();
require_once '../config.php';
requireAdmin();
$page_title = 'Support';

$conn->query("CREATE TABLE IF NOT EXISTS support_tickets (
    id INT PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(100) NOT NULL,
    email VARCHAR(100) NOT NULL,
    phone VARCHAR(20),
    subject VARCHAR(255) NOT NULL,
    message TEXT NOT NULL,
    category VARCHAR(50),
    status ENUM('open','in_progress','closed','resolved') DEFAULT 'open',
    priority ENUM('low','medium','high','urgent') DEFAULT 'medium',
    resolution_notes TEXT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    resolved_at TIMESTAMP NULL
)");

if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['action'])) {
    $tid = (int)$_POST['ticket_id'];
    if ($_POST['action']==='close') {
        $conn->query("UPDATE support_tickets SET status='closed', resolved_at=NOW() WHERE id=$tid");
        setFlash('success','Ticket closed successfully.');
    } elseif ($_POST['action']==='open') {
        $conn->query("UPDATE support_tickets SET status='open', resolved_at=NULL WHERE id=$tid");
        setFlash('success','Ticket reopened.');
    }
    header('Location: support.php'); exit;
}

$search        = clean($_GET['search'] ?? '');
$status_filter = clean($_GET['status'] ?? '');

$where = ["1=1"]; $params = []; $types = '';
if ($search)        { $where[] = "(subject LIKE ? OR email LIKE ? OR name LIKE ?)"; $s="%$search%"; $params[]=$s;$params[]=$s;$params[]=$s; $types.='sss'; }
if ($status_filter) { $where[] = "status=?"; $params[]=$status_filter; $types.='s'; }
$wq = implode(' AND ', $where);

$stmt = $conn->prepare("SELECT * FROM support_tickets WHERE $wq ORDER BY created_at DESC");
if ($params) $stmt->bind_param($types, ...$params);
$stmt->execute();
$tickets = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

$total_tickets  = $conn->query("SELECT COUNT(*) FROM support_tickets")->fetch_row()[0];
$open_tickets   = $conn->query("SELECT COUNT(*) FROM support_tickets WHERE status='open'")->fetch_row()[0];
$closed_tickets = $conn->query("SELECT COUNT(*) FROM support_tickets WHERE status='closed'")->fetch_row()[0];

include 'header.php';
?>
<style>
  .stat-card { border-radius:14px; padding:18px; display:flex; align-items:center; gap:14px; box-shadow:0 4px 20px rgba(11,74,203,.12); transition:transform .2s; position:relative; overflow:hidden; }
  .stat-card:hover { transform:translateY(-3px); }
  .stat-card::after { content:''; position:absolute; right:-20px; top:-20px; width:80px; height:80px; border-radius:50%; background:rgba(255,255,255,.1); }
  .stat-icon { width:46px; height:46px; border-radius:14px; background:rgba(255,255,255,.22); display:grid; place-items:center; flex-shrink:0; font-size:20px; color:#fff; }
  .stat-num { font-size:24px; font-weight:800; color:#fff; line-height:1; }
  .stat-lbl { font-size:11px; color:rgba(255,255,255,.8); margin-top:3px; font-weight:500; }
  @media(max-width:768px) {
    .stat-card { padding:14px 12px; gap:10px; } .stat-num { font-size:20px; }
    .filter-form { flex-direction:column; }
    .filter-form .form-control, .filter-form .form-select, .filter-form button { width:100% !important; }
    table thead { display:none; }
    table tr { display:block; margin-bottom:10px; border:1px solid #e2e8f0; border-radius:12px; padding:10px; background:#fff; }
    table td { display:flex; justify-content:space-between; align-items:center; padding:5px 8px; border:none; font-size:13px; }
    table td::before { content:attr(data-label); font-weight:700; color:#94a3b8; font-size:11px; text-transform:uppercase; flex-shrink:0; margin-right:8px; }
  }
</style>

<?php displayFlash(); ?>

<div class="d-flex justify-content-between align-items-center mb-4 flex-wrap gap-2">
  <div>
    <h5 class="mb-0 fw-800" style="color:#0f172a;"><i class="fas fa-headset me-2 text-primary"></i>Support Center</h5>
    <small class="text-muted">Manage support tickets</small>
  </div>
</div>

<!-- Stats -->
<div class="row g-3 mb-4">
  <?php $cards = [
    ['Total Tickets', $total_tickets,  'fa-ticket-alt',       'linear-gradient(135deg,#0B4ACB,#3B63E6)'],
    ['Open',          $open_tickets,   'fa-exclamation-circle','linear-gradient(135deg,#d97706,#f59e0b)'],
    ['Closed',        $closed_tickets, 'fa-check-circle',     'linear-gradient(135deg,#059669,#10b981)'],
  ]; ?>
  <?php foreach ($cards as [$lbl,$val,$icon,$grad]): ?>
  <div class="col-4">
    <div class="stat-card" style="background:<?= $grad ?>;">
      <div class="stat-icon"><i class="fas <?= $icon ?>"></i></div>
      <div><div class="stat-num"><?= $val ?></div><div class="stat-lbl"><?= $lbl ?></div></div>
    </div>
  </div>
  <?php endforeach; ?>
</div>

<!-- Filter -->
<div class="admin-card mb-4 p-3">
  <form method="GET" class="d-flex gap-2 flex-wrap filter-form">
    <input type="text" name="search" class="form-control form-control-sm" placeholder="Search name, email, subject..." value="<?= htmlspecialchars($search) ?>" style="min-width:200px;">
    <select name="status" class="form-select form-select-sm" style="min-width:130px;">
      <option value="">All Status</option>
      <option value="open"   <?= $status_filter==='open'?'selected':'' ?>>Open</option>
      <option value="closed" <?= $status_filter==='closed'?'selected':'' ?>>Closed</option>
    </select>
    <button type="submit" class="btn btn-primary btn-sm"><i class="fas fa-search me-1"></i>Filter</button>
    <a href="support.php" class="btn btn-outline-secondary btn-sm">Clear</a>
  </form>
</div>

<!-- Tickets Table -->
<div class="admin-card">
  <div class="p-3 border-bottom">
    <h6 class="mb-0 fw-700"><i class="fas fa-list me-2 text-primary"></i>Support Tickets <span class="badge bg-secondary ms-1"><?= count($tickets) ?></span></h6>
  </div>
  <?php if (empty($tickets)): ?>
    <div class="p-5 text-center text-muted">
      <i class="fas fa-inbox fa-3x mb-3" style="opacity:.2;"></i>
      <h6>No support tickets found</h6>
    </div>
  <?php else: ?>
  <div class="table-responsive">
    <table class="table table-hover mb-0">
      <thead class="table-light">
        <tr><th>#</th><th>Name</th><th>Email</th><th>Subject</th><th>Priority</th><th>Status</th><th>Date</th><th>Action</th></tr>
      </thead>
      <tbody>
        <?php foreach ($tickets as $t):
          $pc = ['low'=>'secondary','medium'=>'info','high'=>'warning','urgent'=>'danger'][$t['priority']] ?? 'secondary';
          $sc = $t['status']==='open' ? 'warning' : 'success';
        ?>
        <tr>
          <td data-label="#" style="font-size:12px;color:#94a3b8;">#<?= $t['id'] ?></td>
          <td data-label="Name" style="font-weight:600;font-size:13px;"><?= htmlspecialchars($t['name']) ?></td>
          <td data-label="Email" style="font-size:12px;color:#64748b;"><?= htmlspecialchars($t['email']) ?></td>
          <td data-label="Subject" style="font-size:13px;"><?= htmlspecialchars(substr($t['subject'],0,40)).(strlen($t['subject'])>40?'...':'') ?></td>
          <td data-label="Priority"><span class="badge bg-<?= $pc ?>"><?= ucfirst($t['priority']) ?></span></td>
          <td data-label="Status"><span class="badge bg-<?= $sc ?>"><?= ucfirst($t['status']) ?></span></td>
          <td data-label="Date" style="font-size:12px;"><?= date('d M Y', strtotime($t['created_at'])) ?></td>
          <td data-label="Action">
            <form method="POST" style="display:inline;">
              <input type="hidden" name="ticket_id" value="<?= $t['id'] ?>">
              <?php if ($t['status']==='open'): ?>
                <input type="hidden" name="action" value="close">
                <button class="btn btn-sm btn-success" onclick="return confirm('Close this ticket?')"><i class="fas fa-check me-1"></i>Close</button>
              <?php else: ?>
                <input type="hidden" name="action" value="open">
                <button class="btn btn-sm btn-outline-warning"><i class="fas fa-redo me-1"></i>Reopen</button>
              <?php endif; ?>
            </form>
          </td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>
  <?php endif; ?>
</div>

<?php include 'footer.php'; ?>
