<?php
require_once '../config.php';
requirePatient();
$patient_id = $_SESSION['patient_id'];

// Filters
$specialty_filter = (int)($_GET['specialty'] ?? 0);
$search_filter    = clean($_GET['search'] ?? '');
$city_filter      = clean($_GET['city'] ?? '');

$specializations = $conn->query("SELECT * FROM specializations WHERE is_active=1 ORDER BY name")->fetch_all(MYSQLI_ASSOC);

$where = "WHERE d.verification_status='approved'";
$params = []; $types = '';

if ($specialty_filter) { $where .= " AND d.specialization_id=?"; $params[] = $specialty_filter; $types .= 'i'; }
if ($search_filter)    { $where .= " AND (d.full_name LIKE ? OR d.qualification LIKE ?)"; $s="%$search_filter%"; $params[]=$s; $params[]=$s; $types.='ss'; }
if ($city_filter)      { $where .= " AND d.city LIKE ?"; $c="%$city_filter%"; $params[]=$c; $types.='s'; }

$stmt = $conn->prepare("
    SELECT d.*, s.name as specialization_name,
           COALESCE(AVG(r.rating),0) as avg_rating,
           COUNT(DISTINCT r.id) as total_reviews,
           COUNT(DISTINCT a.id) as total_patients
    FROM doctors d
    LEFT JOIN specializations s ON d.specialization_id=s.id
    LEFT JOIN reviews r ON r.doctor_id=d.id
    LEFT JOIN appointments a ON a.doctor_id=d.id AND a.status='completed'
    $where
    GROUP BY d.id ORDER BY avg_rating DESC, d.experience_years DESC
");
if ($params) $stmt->bind_param($types, ...$params);
$stmt->execute();
$doctors = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Find Doctors - 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: 14px; border: 1px solid #e2e8f0; box-shadow: 0 2px 8px rgba(11,74,203,0.07); }
    .doctor-card { transition: transform 0.2s, box-shadow 0.2s; }
    .doctor-card:hover { transform: translateY(-4px); box-shadow: 0 8px 24px rgba(11,74,203,0.15); border-color: #0B4ACB; }
    .star { color: #d69e2e; }
    .star.empty { color: #e2e8f0; }
    .fee-badge { background: #eff4ff; color: #0B4ACB; padding: 4px 12px; border-radius: 20px; font-weight: 700; font-size: 0.82rem; border: 1px solid #c7d7fc; }
    .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; }
  </style>
</head>
<body>
<?php include 'sidebar.php'; ?>
<div class="main-content">
<?php $page_title = 'Find Doctors'; include 'topbar.php'; ?>
  <div class="page-body">

    <!-- Tabs: All / Pending -->
    <?php
    $pending_count = $conn->query("SELECT COUNT(*) FROM appointments WHERE patient_id=$patient_id AND status='pending'")->fetch_row()[0];
    $tab = $_GET['tab'] ?? 'all';
    ?>
    <div style="display:flex;gap:8px;margin-bottom:20px;">
      <a href="doctors.php" style="padding:9px 22px;border-radius:10px;font-size:13px;font-weight:600;text-decoration:none;border:1.5px solid <?= $tab==='all'?'#0B4ACB':'#e2e8f0' ?>;background:<?= $tab==='all'?'linear-gradient(135deg,#0B4ACB,#3B63E6)':'#fff' ?>;color:<?= $tab==='all'?'#fff':'#64748b' ?>;">
        <i class="fas fa-user-md me-1"></i> All Doctors
      </a>
      <a href="appointments.php?status=pending" style="padding:9px 22px;border-radius:10px;font-size:13px;font-weight:600;text-decoration:none;border:1.5px solid <?= $tab==='pending'?'#f59e0b':'#e2e8f0' ?>;background:<?= $tab==='pending'?'linear-gradient(135deg,#d97706,#f59e0b)':'#fff' ?>;color:<?= $tab==='pending'?'#fff':'#64748b' ?>;display:flex;align-items:center;gap:8px;">
        <i class="fas fa-clock"></i> Pending Appointments
        <?php if($pending_count > 0): ?>
          <span style="background:#ef4444;color:#fff;font-size:10px;font-weight:700;padding:2px 7px;border-radius:20px;"><?= $pending_count ?></span>
        <?php endif; ?>
      </a>
    </div>

    <!-- Search & Filter -->
    <div class="card mb-4 p-3">
      <form method="GET" class="row g-2 align-items-end">
        <div class="col-md-3">
          <label class="form-label fw-600 mb-1" style="font-size:0.78rem;">Search by Name</label>
          <input type="text" name="search" class="form-control form-control-sm" placeholder="Doctor name..." value="<?= htmlspecialchars($search_filter) ?>">
        </div>
        <div class="col-md-3">
          <label class="form-label fw-600 mb-1" style="font-size:0.78rem;">Specialization</label>
          <select name="specialty" class="form-select form-select-sm">
            <option value="">All Specializations</option>
            <?php foreach ($specializations as $sp): ?>
              <option value="<?= $sp['id'] ?>" <?= $specialty_filter==$sp['id']?'selected':'' ?>><?= htmlspecialchars($sp['name']) ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="col-md-3">
          <label class="form-label fw-600 mb-1" style="font-size:0.78rem;">City</label>
          <input type="text" name="city" class="form-control form-control-sm" placeholder="e.g. Karachi" value="<?= htmlspecialchars($city_filter) ?>">
        </div>
        <div class="col-md-3">
          <button type="submit" class="btn btn-primary btn-sm me-1"><i class="fas fa-search me-1"></i>Search</button>
          <a href="doctors.php" class="btn btn-outline-secondary btn-sm">Clear</a>
        </div>
      </form>
    </div>

    <!-- Specialization Quick Filter -->
    <div class="d-flex gap-2 flex-wrap mb-4">
      <a href="doctors.php" class="btn btn-sm <?= !$specialty_filter ? 'btn-primary' : 'btn-outline-primary' ?>">All</a>
      <?php foreach ($specializations as $sp): ?>
        <a href="?specialty=<?= $sp['id'] ?>" class="btn btn-sm <?= $specialty_filter==$sp['id'] ? 'btn-primary' : 'btn-outline-primary' ?>">
          <?= htmlspecialchars($sp['name']) ?>
        </a>
      <?php endforeach; ?>
    </div>

    <!-- Doctors Grid -->
    <?php if (empty($doctors)): ?>
      <div class="card p-5 text-center text-muted">
        <i class="fas fa-user-md fa-4x mb-3" style="opacity:0.2;"></i>
        <h5>No doctors found</h5>
        <p>Try adjusting your search filters.</p>
      </div>
    <?php else: ?>
      <div class="row g-3">
        <?php foreach ($doctors as $doc): ?>
          <div class="col-md-6 col-xl-4">
            <div class="card doctor-card h-100">
              <div class="card-body p-3">
                <div class="d-flex align-items-start gap-3 mb-3">
                  <?php if ($doc['profile_photo']): ?>
                    <img src="<?= SITE_URL ?>/<?= $doc['profile_photo'] ?>" style="width:60px;height:60px;border-radius:50%;object-fit:cover;border:2px solid #e6f5f3;" alt="">
                  <?php else: ?>
                    <div style="width:60px;height:60px;border-radius:50%;background:#eff4ff;display:flex;align-items:center;justify-content:center;flex-shrink:0;border:2px solid #c7d7fc;">
                      <i class="fas fa-user-md" style="font-size:1.6rem;color:#0B4ACB;"></i>
                    </div>
                  <?php endif; ?>
                  <div class="flex-grow-1">
                    <h6 class="mb-0 fw-700">Dr. <?= htmlspecialchars($doc['full_name']) ?></h6>
                    <div style="font-size:0.78rem;color:#0B4ACB;font-weight:600;"><?= htmlspecialchars($doc['specialization_name']) ?></div>
                    <div style="font-size:0.72rem;color:#718096;"><?= htmlspecialchars($doc['qualification']) ?></div>
                  </div>
                  <span class="fee-badge">Rs.<?= number_format($doc['consultation_fee']) ?></span>
                </div>

                <!-- Rating -->
                <div class="d-flex align-items-center gap-1 mb-2">
                  <?php for ($i=1; $i<=5; $i++): ?>
                    <i class="fas fa-star <?= $i<=$doc['avg_rating'] ? 'star' : 'star empty' ?>" style="font-size:0.72rem;"></i>
                  <?php endfor; ?>
                  <span style="font-size:0.72rem;color:#718096;margin-left:4px;"><?= number_format($doc['avg_rating'],1) ?> (<?= $doc['total_reviews'] ?> reviews)</span>
                </div>

                <div style="font-size:0.78rem;color:#718096;" class="mb-3">
                  <i class="fas fa-clock me-1"></i><?= $doc['experience_years'] ?> yrs exp
                  &nbsp;&middot;&nbsp;
                  <i class="fas fa-map-marker-alt me-1"></i><?= htmlspecialchars($doc['city'] ?? '') ?>
                  &nbsp;&middot;&nbsp;
                  <i class="fas fa-users me-1"></i><?= $doc['total_patients'] ?> patients
                </div>

                <?php if ($doc['bio']): ?>
                  <p style="font-size:0.78rem;color:#4a5568;margin-bottom:12px;"><?= htmlspecialchars(substr($doc['bio'],0,90)) ?>...</p>
                <?php endif; ?>

                <!-- Clinic -->
                <?php if ($doc['clinic_name']): ?>
                  <div style="font-size:0.75rem;background:#f0f4ff;padding:6px 10px;border-radius:8px;margin-bottom:12px;">
                    <i class="fas fa-hospital me-1" style="color:#0B4ACB;"></i><?= htmlspecialchars($doc['clinic_name']) ?>
                  </div>
                <?php endif; ?>
              </div>
              <div class="card-footer bg-white border-0 pt-0 pb-3 px-3">
                <a href="book-appointment.php?doctor_id=<?= $doc['id'] ?>" class="btn w-100 btn-sm" style="background:linear-gradient(135deg,#0B4ACB,#3B63E6);color:#fff;font-weight:600;border:none;padding:9px;border-radius:10px;">
                  <i class="fas fa-calendar-plus me-1"></i>Book Appointment
                </a>
              </div>
            </div>
          </div>
        <?php endforeach; ?>
      </div>
    <?php endif; ?>
  </div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
