<?php
// medical_list.php — Doctor dashboard with filters/search/sort + flash
require 'db.php';
require 'helpers.php';
require_doctor();

$doctor = current_doctor();

/* ------- Flash ------- */
$flashOk  = flash_get('ok');
$flashErr = flash_get('err');

/* ------- Inputs ------- */
$status = $_GET['status'] ?? 'all'; // all|waiting|approved|rejected
$allowedStatus = ['all','waiting','approved','rejected'];
if (!in_array($status, $allowedStatus, true)) $status = 'all';

$q = trim($_GET['q'] ?? '');                  // search (id exact or name like)
$sort = $_GET['sort'] ?? 'id_desc';           // id_desc|id_asc|medical_date_desc|medical_date_asc
$allowedSort = ['id_desc','id_asc','medical_date_desc','medical_date_asc'];
if (!in_array($sort, $allowedSort, true)) $sort = 'id_desc';

$limit = 50;

/* ------- WHERE ------- */
$where = [];
$params = [];
$types  = '';

switch ($status) {
  case 'waiting': 
      $where[] = "s.medical_status = 'completed'";
      $where[] = "s.profile_completed = 1";
      break;
  case 'approved':     
      $where[] = "s.medically_fit = 1";     
      break;
  case 'rejected':     
      $where[] = "s.medically_fit = 0";     
      break;
  case 'all':
  default: 
      // No conditions for 'all' - show all students
      break;
}

if ($q !== '') {
    if (ctype_digit($q)) {
        $where[] = "s.student_id = ?";
        $types  .= "s";
        $params[] = $q;
    } else {
        $where[] = "(s.student_id LIKE ? OR s.student_name LIKE ? OR s.student_name_eng LIKE ?)";
        $types  .= "sss";
        $like = "%{$q}%";
        $params[] = $like; $params[] = $like; $params[] = $like;
    }
}

// Add WHERE clause only if there are conditions
$whereSql = !empty($where) ? "WHERE " . implode(" AND ", $where) : "";

/* ------- ORDER ------- */
switch ($sort) {
  case 'id_asc':              $orderBy = "ORDER BY s.student_id ASC"; break;
  case 'medical_date_desc':   $orderBy = "ORDER BY m.medical_date DESC, s.student_id DESC"; break;
  case 'medical_date_asc':    $orderBy = "ORDER BY m.medical_date ASC, s.student_id ASC"; break;
  case 'id_desc':
  default:                    $orderBy = "ORDER BY s.student_id DESC"; break;
}

/* ------- Query ------- */
$sql = "
  SELECT 
    s.student_id, 
    s.student_name, 
    s.student_name_eng, 
    s.nationality,
    s.phone_number, 
    s.interview_status, 
    s.medically_fit,
    s.medical_checked_at,
    s.last_medical_exam,
    s.medical_status,
    s.profile_completed,
    m.medical_date,
    m.has_disability,
    m.has_chronic_diseases,
    m.has_psychological_diseases,
    m.has_vision_problems,
    m.has_hearing_problems,
    m.covid_vaccinated,
    m.has_diabetes,
    m.has_blood_pressure,
    m.has_family_diseases
  FROM students s
  LEFT JOIN student_medical_records m ON s.student_id = m.student_id
  $whereSql
  $orderBy
  LIMIT $limit
";
$stmt = $mysqli1->prepare($sql);
if (!$stmt) { die("DB error."); }
if ($types !== '') { $stmt->bind_param($types, ...$params); }
$stmt->execute();
$res = $stmt->get_result();

/* ------- Counters for tabs ------- */
function count_by($mysqli1, $condSql = '1', $types = '', $params = []) {
    $sql = "SELECT COUNT(*) FROM students s WHERE ($condSql)";
    $st = $mysqli1->prepare($sql);
    if ($types) { $st->bind_param($types, ...$params); }
    $st->execute();
    $st->bind_result($c);
    $st->fetch();
    $st->close();
    return (int)$c;
}

// Counters with different conditions
$totalAll   = count_by($mysqli1, '1'); // All students regardless of profile completion
$totalWait  = count_by($mysqli1, "s.medical_status = 'completed' AND s.profile_completed = 1");
$totalApproved = count_by($mysqli1, "s.medically_fit = 1");
$totalRejected = count_by($mysqli1, "s.medically_fit = 0");
?><!doctype html>
<html lang="ar" dir="rtl">
<head>
<meta charset="utf-8">
<title>كشف الفحص الطبي</title>
<?php base_head_css(); ?>
<style>
  .tabs a{margin-inline-end:6px}
  .countchip{background:#fff;border:1px solid #ddd;border-radius:20px;padding:2px 8px;margin-inline-start:6px;font-size:.85rem}
  .toolbar{display:flex;gap:8px;align-items:center;flex-wrap:wrap}
  .medical-indicators { display: flex; gap: 4px; flex-wrap: wrap; margin-top: 4px; }
  .medical-indicator {
    font-size: 0.7rem;
    padding: 1px 4px;
    border-radius: 3px;
    background: #e5e7eb;
    color: #374151;
  }
  .medical-indicator.yes { background: #dcfce7; color: #166534; }
  .medical-indicator.no { background: #fef2f2; color: #991b1b; }
  .badge {
    display: inline-block;
    padding: 4px 8px;
    border-radius: 4px;
    font-size: 0.8rem;
    font-weight: 600;
  }
  .badge-waiting { background: #fef3c7; color: #92400e; }
  .badge-approved { background: #d1fae5; color: #065f46; }
  .badge-rejected { background: #fee2e2; color: #991b1b; }
</style>
</head>
<body>
<div class="container">
  <div class="card">
    <div style="display:flex;justify-content:space-between;align-items:center">
      <h2>مرحباً د. <?php echo e($doctor['name']); ?></h2>
      <div>
        <a class="btn light" href="medical_list.php">تحديث</a>
        <a class="btn danger" href="signout.php?role=doctor">خروج</a>
      </div>
    </div>

    <?php if ($flashOk): ?><div class="notice"><?php echo e($flashOk); ?></div><?php endif; ?>
    <?php if ($flashErr): ?><div class="notice" style="background:#ffebee;border-color:#ffcdd2"><?php echo e($flashErr); ?></div><?php endif; ?>

    <div class="card">
      <div class="toolbar" style="justify-content:space-between">
        <div class="tabs" role="tablist">
          <a class="btn <?php echo $status==='all'?'primary':'light'; ?>" href="?status=all&sort=<?php echo e($sort); ?>&q=<?php echo urlencode($q); ?>">
            الكل <span class="countchip" style="background:<?php echo $status==='all'?'#e3f2fd':'#f5f5f5'; ?>;color:#333;border:1px solid #ddd;"><?php echo $totalAll; ?></span>
          </a>
          <a class="btn <?php echo $status==='waiting'?'primary':'light'; ?>" href="?status=waiting&sort=<?php echo e($sort); ?>&q=<?php echo urlencode($q); ?>">
            الانتظار <span class="countchip" style="background:<?php echo $status==='waiting'?'#fff3cd':'#f5f5f5'; ?>;color:#856404;border:1px solid #ffeaa7;"><?php echo $totalWait; ?></span>
          </a>
          <a class="btn <?php echo $status==='approved'?'primary':'light'; ?>" href="?status=approved&sort=<?php echo e($sort); ?>&q=<?php echo urlencode($q); ?>">
            مقبول طبيًا <span class="countchip" style="background:<?php echo $status==='approved'?'#d1edff':'#f5f5f5'; ?>;color:#0c5460;border:1px solid #bee5eb;"><?php echo $totalApproved; ?></span>
          </a>
          <a class="btn <?php echo $status==='rejected'?'primary':'light'; ?>" href="?status=rejected&sort=<?php echo e($sort); ?>&q=<?php echo urlencode($q); ?>">
            مرفوض طبيًا <span class="countchip" style="background:<?php echo $status==='rejected'?'#f8d7da':'#f5f5f5'; ?>;color:#721c24;border:1px solid #f1b0b7;"><?php echo $totalRejected; ?></span>
          </a>
        </div>

        <form method="get" class="toolbar" style="justify-content:flex-end">
          <input type="hidden" name="status" value="<?php echo e($status); ?>">
          <input name="q" value="<?php echo e($q); ?>" placeholder="بحث برقم/اسم الطالب" style="min-width:220px">
          <select name="sort" aria-label="ترتيب">
            <option value="id_desc"       <?php echo $sort==='id_desc'?'selected':''; ?>>الأحدث (رقم الطالب ↓)</option>
            <option value="id_asc"        <?php echo $sort==='id_asc'?'selected':''; ?>>الأقدم (رقم الطالب ↑)</option>
            <option value="medical_date_desc"  <?php echo $sort==='medical_date_desc'?'selected':''; ?>>آخر فحص (الأحدث)</option>
            <option value="medical_date_asc"   <?php echo $sort==='medical_date_asc'?'selected':''; ?>>آخر فحص (الأقدم)</option>
          </select>
          <button class="btn" type="submit">تطبيق</button>
        </form>
      </div>
    </div>

    <table>
      <thead>
        <tr>
          <th>الرقم</th>
          <th>الاسم</th>
          <th>الهاتف</th>
          <th>الحالة الطبية</th>
          <th>آخر فحص</th>
          <th>المعلومات الطبية</th>
          <th>إجراء</th>
        </tr>
      </thead>
      <tbody>
      <?php while($row = $res->fetch_assoc()): ?>
        <?php
          $name  = $row['student_name'] ?: $row['student_name_eng'];
          
          // Medical status based on medically_fit field
          $medically_fit = $row['medically_fit'];
          if ($medically_fit === null) { 
            $medTxt = 'الانتظار'; 
            $medClass = 'badge-waiting'; 
          } elseif ((int)$medically_fit === 1) { 
            $medTxt = 'مقبول طبيًا';         
            $medClass = 'badge-approved'; 
          } else { 
            $medTxt = 'مرفوض طبيًا';     
            $medClass = 'badge-rejected'; 
          }
        ?>
        <tr>
          <td><?php echo e($row['student_id']); ?></td>
          <td><?php echo e($name); ?></td>
          <td><?php echo e($row['phone_number']); ?></td>
          <td><span class="badge <?php echo $medClass; ?>"><?php echo $medTxt; ?></span></td>
          <td><?php echo e($row['medical_checked_at'] ?: '—'); ?></td>
          <td>
            <?php if ($row['medical_date']): ?>
              <div class="medical-indicators">
                <?php if ($row['has_disability'] === 'yes'): ?>
                  <span class="medical-indicator yes" title="إعاقة حركية">إعاقة</span>
                <?php endif; ?>
                <?php if ($row['has_chronic_diseases'] === 'yes'): ?>
                  <span class="medical-indicator yes" title="أمراض مزمنة">مزمن</span>
                <?php endif; ?>
                <?php if ($row['has_psychological_diseases'] === 'yes'): ?>
                  <span class="medical-indicator yes" title="أمراض نفسية">نفسي</span>
                <?php endif; ?>
                <?php if ($row['has_vision_problems'] === 'yes'): ?>
                  <span class="medical-indicator yes" title="مشاكل بصرية">بصر</span>
                <?php endif; ?>
                <?php if ($row['has_hearing_problems'] === 'yes'): ?>
                  <span class="medical-indicator yes" title="مشاكل سمعية">سمع</span>
                <?php endif; ?>
                <?php if ($row['has_diabetes'] === 'yes'): ?>
                  <span class="medical-indicator yes" title="سكري">سكري</span>
                <?php endif; ?>
                <?php if ($row['has_blood_pressure'] === 'yes'): ?>
                  <span class="medical-indicator yes" title="ضغط">ضغط</span>
                <?php endif; ?>
              </div>
            <?php else: ?>
              <span class="text-muted">—</span>
            <?php endif; ?>
          </td>
          <td><a class="btn primary" href="medical_review.php?id=<?php echo urlencode($row['student_id']); ?>">عرض</a></td>
        </tr>
      <?php endwhile; ?>
      </tbody>
    </table>

    <p style="opacity:.7;margin-top:8px">تم عرض أول <?php echo $limit; ?> صف (إن وُجد). استخدم البحث لتقليل النتائج.</p>
  </div>
</div>
</body>
</html>