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

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

$where = []; $params = []; $types = '';
if ($search)        { $where[] = "(p.full_name LIKE ? OR d.full_name LIKE ? OR a.appointment_no LIKE ?)"; $s="%$search%"; $params[]=$s;$params[]=$s;$params[]=$s; $types.='sss'; }
if ($status_filter) { $where[] = "a.status=?"; $params[]=$status_filter; $types.='s'; }
if ($date_filter)   { $where[] = "DATE(a.appointment_date)=?"; $params[]=$date_filter; $types.='s'; }
$wq = $where ? 'WHERE '.implode(' AND ',$where) : '';

$stmt = $conn->prepare("SELECT a.*, p.full_name as patient_name, p.health_id, p.phone as patient_phone, d.full_name as doctor_name, s.name as specialization_name FROM appointments a JOIN patients p ON a.patient_id=p.id JOIN doctors d ON a.doctor_id=d.id LEFT JOIN specializations s ON d.specialization_id=s.id $wq ORDER BY a.appointment_date DESC, a.appointment_time DESC");
if ($params) $stmt->bind_param($types, ...$params);
$stmt->execute();
$appointments = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

$stats = [
    'total'     => $conn->query("SELECT COUNT(*) FROM appointments")->fetch_row()[0],
    'pending'   => $conn->query("SELECT COUNT(*) FROM appointments WHERE status='pending'")->fetch_row()[0],
    'confirmed' => $conn->query("SELECT COUNT(*) FROM appointments WHERE status='confirmed'")->fetch_row()[0],
    'completed' => $conn->query("SELECT COUNT(*) FROM appointments WHERE status='completed'")->fetch_row()[0],
    'today'     => $conn->query("SELECT COUNT(*) FROM appointments WHERE DATE(appointment_date)=CURDATE()")->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; }
  .filter-form .form-control, .filter-form .form-select { font-size:13px; }
  @media(max-width:768px) {
    .stat-num { font-size:20px; }
    .stat-card { padding:14px 12px; gap:10px; }
    .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-calendar-alt me-2 text-primary"></i>Appointments</h5>
    <small class="text-muted"><?= count($appointments) ?> records found</small>
  </div>
</div>

<!-- Stats -->
<div class="row g-3 mb-4">
  <?php $cards = [
    ['Total',     $stats['total'],     'fa-calendar-alt',  'linear-gradient(135deg,#0B4ACB,#3B63E6)'],
    ['Pending',   $stats['pending'],   'fa-clock',         'linear-gradient(135deg,#d97706,#f59e0b)'],
    ['Confirmed', $stats['confirmed'], 'fa-check-circle',  'linear-gradient(135deg,#059669,#10b981)'],
    ['Completed', $stats['completed'], 'fa-check-double',  'linear-gradient(135deg,#0891b2,#06b6d4)'],
    ['Today',     $stats['today'],     'fa-calendar-day',  'linear-gradient(135deg,#7c3aed,#a855f7)'],
  ]; ?>
  <?php foreach ($cards as [$lbl,$val,$icon,$grad]): ?>
  <div class="col-6 col-xl">
    <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 patient, doctor, apt#..." value="<?= htmlspecialchars($search) ?>" style="min-width:180px;">
    <input type="date" name="date" class="form-control form-control-sm" value="<?= htmlspecialchars($date_filter) ?>" style="min-width:140px;">
    <select name="status" class="form-select form-select-sm" style="min-width:130px;">
      <option value="">All Status</option>
      <?php foreach(['pending','confirmed','completed','cancelled'] as $s): ?>
        <option value="<?=$s?>" <?=$status_filter===$s?'selected':''?>><?=ucfirst($s)?></option>
      <?php endforeach; ?>
    </select>
    <button type="submit" class="btn btn-primary btn-sm"><i class="fas fa-search me-1"></i>Filter</button>
    <a href="appointments.php" class="btn btn-outline-secondary btn-sm">Clear</a>
  </form>
</div>

<!-- Table -->
<div class="admin-card">
  <div class="p-3 border-bottom d-flex justify-content-between align-items-center">
    <h6 class="mb-0 fw-700"><i class="fas fa-list me-2 text-primary"></i>All Appointments <span class="badge bg-secondary ms-1"><?= count($appointments) ?></span></h6>
  </div>
  <?php if (empty($appointments)): ?>
    <div class="p-5 text-center text-muted">
      <i class="fas fa-calendar-times fa-3x mb-3" style="opacity:.2;"></i>
      <h6>No appointments found</h6>
    </div>
  <?php else: ?>
  <div class="table-responsive">
    <table class="table table-hover mb-0">
      <thead class="table-light">
        <tr>
          <th>Apt #</th><th>Patient</th><th>Doctor</th><th>Date & Time</th><th>Type</th><th>Status</th><th>Fee</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($appointments as $apt):
          $sc = ['pending'=>'warning','confirmed'=>'success','completed'=>'info','cancelled'=>'danger'][$apt['status']] ?? 'secondary';
        ?>
        <tr>
          <td data-label="Apt #"><code style="font-size:11px;"><?= htmlspecialchars($apt['appointment_no']) ?></code></td>
          <td data-label="Patient">
            <div style="font-weight:600;font-size:13px;"><?= htmlspecialchars($apt['patient_name']) ?></div>
            <div style="font-size:11px;color:#94a3b8;"><?= htmlspecialchars($apt['health_id']) ?></div>
          </td>
          <td data-label="Doctor">
            <div style="font-weight:600;font-size:13px;">Dr. <?= htmlspecialchars($apt['doctor_name']) ?></div>
            <div style="font-size:11px;color:#94a3b8;"><?= htmlspecialchars($apt['specialization_name'] ?? '') ?></div>
          </td>
          <td data-label="Date & Time">
            <div style="font-weight:600;font-size:13px;"><?= date('d M Y', strtotime($apt['appointment_date'])) ?></div>
            <div style="font-size:11px;color:#94a3b8;"><?= date('h:i A', strtotime($apt['appointment_time'])) ?></div>
          </td>
          <td data-label="Type"><span class="badge bg-light text-dark"><i class="fas fa-<?= $apt['consultation_type']==='online'?'video':'hospital' ?> me-1"></i><?= ucfirst($apt['consultation_type'] ?? '') ?></span></td>
          <td data-label="Status"><span class="badge bg-<?= $sc ?>"><?= ucfirst($apt['status']) ?></span></td>
          <td data-label="Fee" style="font-weight:700;color:#059669;">Rs. <?= number_format($apt['consultation_fee']) ?></td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>
  <?php endif; ?>
</div>

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