<?php
require_once '../config.php';
requirePatient();

$patient_id = $_SESSION['patient_id'];

// Handle cancel
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['cancel_id'])) {
    $apt_id = (int)$_POST['cancel_id'];
    $conn->prepare("UPDATE appointments SET status='cancelled' WHERE id=? AND patient_id=? AND status IN('pending','confirmed')")
        ->execute() ?: null;
    $upd = $conn->prepare("UPDATE appointments SET status='cancelled' WHERE id=? AND patient_id=? AND status IN('pending','confirmed')");
    $upd->bind_param('ii', $apt_id, $patient_id);
    $upd->execute();
    setFlash('success', 'Appointment cancelled successfully.');
    header('Location: appointments.php');
    exit;
}

// Handle reschedule
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['reschedule_id'])) {
    $apt_id   = (int)$_POST['reschedule_id'];
    $new_date = clean($_POST['new_date'] ?? '');
    $new_time = clean($_POST['new_time'] ?? '');

    if ($new_date && $new_time && strtotime($new_date) >= strtotime('today')) {
        $upd = $conn->prepare("UPDATE appointments SET appointment_date=?, appointment_time=?, status='pending' WHERE id=? AND patient_id=?");
        $upd->bind_param('ssii', $new_date, $new_time, $apt_id, $patient_id);
        $upd->execute();
        setFlash('success', 'Appointment rescheduled successfully.');
    } else {
        setFlash('error', 'Please select a valid future date and time.');
    }
    header('Location: appointments.php');
    exit;
}

// Filters
$filter = $_GET['filter'] ?? 'all';
$where  = "WHERE a.patient_id = $patient_id";
if ($filter === 'upcoming') $where .= " AND a.appointment_date >= CURDATE() AND a.status IN('pending','confirmed')";
elseif ($filter === 'completed') $where .= " AND a.status = 'completed'";
elseif ($filter === 'cancelled') $where .= " AND a.status = 'cancelled'";

$appointments = $conn->query("
    SELECT a.*, d.full_name as doctor_name, d.profile_photo, s.name as specialization
    FROM appointments a
    JOIN doctors d ON a.doctor_id = d.id
    LEFT JOIN specializations s ON d.specialization_id = s.id
    $where
    ORDER BY a.appointment_date DESC, a.appointment_time DESC
")->fetch_all(MYSQLI_ASSOC);

$counts = [
    'all'       => $conn->query("SELECT COUNT(*) FROM appointments WHERE patient_id=$patient_id")->fetch_row()[0],
    'upcoming'  => $conn->query("SELECT COUNT(*) FROM appointments WHERE patient_id=$patient_id AND appointment_date>=CURDATE() AND status IN('pending','confirmed')")->fetch_row()[0],
    'completed' => $conn->query("SELECT COUNT(*) FROM appointments WHERE patient_id=$patient_id AND status='completed'")->fetch_row()[0],
    'cancelled' => $conn->query("SELECT COUNT(*) FROM appointments WHERE patient_id=$patient_id AND status='cancelled'")->fetch_row()[0],
];
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>My Appointments - HealthLink</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
  <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
  <style>
    body { background: #f0f4ff; font-family: Inter, 'Segoe UI', sans-serif; }
    .card { border-radius: 16px; border: 1px solid #e2e8f0; box-shadow: 0 2px 10px rgba(11,74,203,0.07); }
    .apt-card:hover { transform: translateY(-3px); box-shadow: 0 8px 24px rgba(11,74,203,0.13); border-color: #0B4ACB; }
    .apt-card { transition: transform 0.2s, box-shadow 0.2s; }
    .top-bar { background:#fff; border-bottom:1px solid #e2e8f0; padding:14px 28px; display:flex; align-items:center; justify-content:space-between; box-shadow:0 1px 8px rgba(11,74,203,.07); }
    .top-bar h5 { margin:0; font-size:16px; font-weight:700; color:#0f172a; }
    .page-body { padding:26px 28px; }
    .filter-btn { border-radius:10px; font-size:13px; font-weight:600; padding:8px 18px; border:1.5px solid #e2e8f0; background:#fff; color:#64748b; text-decoration:none; transition:all .2s; display:inline-flex; align-items:center; gap:6px; }
    .filter-btn:hover { border-color:#0B4ACB; color:#0B4ACB; }
    .filter-btn.active { background:linear-gradient(135deg,#0B4ACB,#3B63E6); color:#fff; border-color:#0B4ACB; box-shadow:0 4px 12px rgba(11,74,203,.25); }
    .filter-btn.active .f-badge { background:rgba(255,255,255,.25); color:#fff; }
    .f-badge { background:#f1f5f9; color:#64748b; font-size:11px; font-weight:700; padding:1px 7px; border-radius:20px; }
    .status-pending   { background:#fff8e1; color:#d97706; border:1px solid #fde68a; }
    .status-confirmed { background:#eff4ff; color:#0B4ACB; border:1px solid #c7d7fc; }
    .status-completed { background:#eff6ff; color:#3b82f6; border:1px solid #bfdbfe; }
    .status-cancelled { background:#fef2f2; color:#ef4444; border:1px solid #fecaca; }
    .apt-badge { padding:4px 12px; border-radius:20px; font-size:11px; font-weight:700; }
    .modal-content { border-radius:16px; }
    .doc-avatar { width:46px; height:46px; border-radius:14px; background:#eff4ff; border:1px solid #c7d7fc; display:flex; align-items:center; justify-content:center; font-size:1.3rem; flex-shrink:0; }
    .btn-blue { background:linear-gradient(135deg,#0B4ACB,#3B63E6); color:#fff !important; border:none; padding:8px 18px; border-radius:10px; font-size:13px; font-weight:600; cursor:pointer; transition:all .2s; text-decoration:none; display:inline-flex; align-items:center; gap:6px; }
    .btn-blue:hover { opacity:.9; transform:translateY(-1px); }
  </style>
</head>
<body>
<?php include 'sidebar.php'; ?>
<div class="main-content">
<?php $page_title = 'My Appointments'; include 'topbar.php'; ?>

  <div class="page-body">
    <?php displayFlash(); ?>

    <!-- Filter Tabs -->
    <div class="d-flex gap-2 flex-wrap mb-4">
      <?php $tabs=['all'=>['All','fa-list'],'upcoming'=>['Upcoming','fa-clock'],'completed'=>['Completed','fa-check-circle'],'cancelled'=>['Cancelled','fa-times-circle']];
      foreach($tabs as $key=>[$label,$icon]): ?>
        <a href="?filter=<?= $key ?>" class="filter-btn <?= $filter===$key?'active':'' ?>">
          <i class="fas <?= $icon ?>"></i> <?= $label ?> <span class="f-badge"><?= $counts[$key] ?></span>
        </a>
      <?php endforeach; ?>
    </div>

    <?php if (empty($appointments)): ?>
      <div class="card p-5 text-center text-muted">
        <i class="fas fa-calendar-times fa-4x mb-3" style="opacity:0.2;"></i>
        <h5>No appointments found</h5>
        <p>You have no <?= $filter !== 'all' ? $filter : '' ?> appointments.</p>
        <a href="doctors.php" class="btn-blue mt-2"><i class="fas fa-search"></i> Find a Doctor</a>
      </div>
    <?php else: ?>
      <div class="row g-3">
        <?php foreach ($appointments as $apt):
          $is_upcoming = in_array($apt['status'], ['pending','confirmed']) && strtotime($apt['appointment_date']) >= strtotime('today');
          $is_today = $apt['appointment_date'] === date('Y-m-d');
        ?>
          <div class="col-md-6 col-xl-4">
            <div class="card apt-card p-3 h-100">

              <!-- Header -->
              <div class="d-flex justify-content-between align-items-start mb-3">
                <div class="d-flex gap-2 align-items-center">
                  <?php if ($apt['profile_photo']): ?>
                    <img src="<?= SITE_URL ?>/<?= $apt['profile_photo'] ?>" style="width:44px;height:44px;border-radius:50%;object-fit:cover;">
                  <?php else: ?>
                    <div style="width:44px;height:44px;border-radius:50%;background:#e6f5f3;display:flex;align-items:center;justify-content:center;flex-shrink:0;">
                      <i class="fas fa-user-md" style="color:#0B7B6E;font-size:1.2rem;"></i>
                    </div>
                  <?php endif; ?>
                  <div>
                    <div style="font-weight:700;font-size:0.88rem;">Dr. <?= htmlspecialchars($apt['doctor_name']) ?></div>
                    <div style="font-size:0.72rem;color:#0B4ACB;font-weight:600;"><?= htmlspecialchars($apt['specialization'] ?? '') ?></div>
                  </div>
                </div>
                <span class="apt-badge status-<?= $apt['status'] ?>"><?= ucfirst($apt['status']) ?></span>
              </div>

              <!-- Info -->
              <div style="font-size:0.82rem;color:#4a5568;" class="mb-2">
                <i class="fas fa-calendar me-1 text-primary"></i><?= date('d M Y', strtotime($apt['appointment_date'])) ?>
                &nbsp;&middot;&nbsp;
                <i class="fas fa-clock me-1 text-primary"></i><?= date('h:i A', strtotime($apt['appointment_time'])) ?>
              </div>
              <div style="font-size:0.8rem;color:#718096;" class="mb-2">
                <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>
                <span class="ms-2 text-muted" style="font-size:0.72rem;"><?= htmlspecialchars($apt['appointment_no']) ?></span>
              </div>
              <?php if ($apt['symptoms']): ?>
                <div style="font-size:0.78rem;color:#718096;background:#f7fafa;padding:6px 10px;border-radius:8px;margin-bottom:8px;">
                  <?= htmlspecialchars(substr($apt['symptoms'], 0, 80)) ?><?= strlen($apt['symptoms'])>80?'...':'' ?>
                </div>
              <?php endif; ?>
              <div class="mt-auto pt-2" style="font-weight:700;color:#0B4ACB;">Rs. <?= number_format($apt['consultation_fee']) ?></div>

              <!-- Actions -->
              <?php if ($is_upcoming): ?>
                <div class="d-flex gap-2 mt-3">
                  <?php if ($apt['status']==='confirmed' && $is_today): ?>
                    <a href="consultation.php?id=<?= $apt['id'] ?>" class="btn-blue flex-grow-1">
                      <i class="fas fa-video"></i>Join
                    </a>
                  <?php endif; ?>
                  <button type="button" class="btn btn-outline-primary btn-sm flex-grow-1"
                    data-bs-toggle="modal" data-bs-target="#rescheduleModal"
                    data-id="<?= $apt['id'] ?>"
                    data-date="<?= $apt['appointment_date'] ?>"
                    data-time="<?= $apt['appointment_time'] ?>">
                    <i class="fas fa-calendar-alt me-1"></i>Reschedule
                  </button>
                  <form method="POST" onsubmit="return confirm('Cancel this appointment?')">
                    <input type="hidden" name="cancel_id" value="<?= $apt['id'] ?>">
                    <button class="btn btn-outline-danger btn-sm"><i class="fas fa-times"></i></button>
                  </form>
                </div>
              <?php elseif ($apt['status']==='completed'): ?>
                <div class="mt-3">
                  <a href="medical-history.php" class="btn btn-sm w-100" style="background:#eff4ff;color:#0B4ACB;border:1px solid #c7d7fc;font-weight:600;border-radius:10px;">
                    <i class="fas fa-file-medical me-1"></i>View Records
                  </a>
                </div>
              <?php endif; ?>

            </div>
          </div>
        <?php endforeach; ?>
      </div>
    <?php endif; ?>
  </div>
</div>

<!-- Reschedule Modal -->
<div class="modal fade" id="rescheduleModal" tabindex="-1">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header border-0">
        <h5 class="modal-title fw-700"><i class="fas fa-calendar-alt me-2 text-primary"></i>Reschedule Appointment</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <form method="POST">
        <div class="modal-body">
          <input type="hidden" name="reschedule_id" id="reschedule_id">
          <div class="mb-3">
            <label class="form-label fw-600">New Date</label>
            <input type="date" name="new_date" id="new_date" class="form-control" min="<?= date('Y-m-d') ?>" required>
          </div>
          <div class="mb-3">
            <label class="form-label fw-600">New Time</label>
            <select name="new_time" class="form-select" required>
              <?php
              $slots = ['09:00','09:30','10:00','10:30','11:00','11:30','12:00','14:00','14:30','15:00','15:30','16:00','16:30','17:00'];
              foreach ($slots as $s): ?>
                <option value="<?= $s ?>:00"><?= date('h:i A', strtotime($s)) ?></option>
              <?php endforeach; ?>
            </select>
          </div>
        </div>
        <div class="modal-footer border-0">
          <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
          <button type="submit" class="btn btn-primary"><i class="fas fa-check me-1"></i>Confirm Reschedule</button>
        </div>
      </form>
    </div>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
  document.getElementById('rescheduleModal').addEventListener('show.bs.modal', e => {
    const btn = e.relatedTarget;
    document.getElementById('reschedule_id').value = btn.dataset.id;
    document.getElementById('new_date').value = btn.dataset.date;
  });
</script>
</body>
</html>
