<?php
// medical_list.php — Doctor dashboard with filters/search/sort + flash

// إضافة معالجة الأخطاء في البداية
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
ini_set('max_execution_time', 300); // زيادة وقت التنفيذ إلى 5 دقائق
ini_set('memory_limit', '512M'); // زيادة الذاكرة

// بدء قياس وقت التنفيذ
$start_time = microtime(true);

// تسجيل بدء التنفيذ
error_log("=== Starting medical_list.php ===");

try {
    require 'db.php';
    require 'helpers.php';
    require_doctor();

    $doctor = current_doctor();
    error_log("Doctor loaded: " . $doctor['name']);

} catch (Exception $e) {
    error_log("Error in medical_list.php: " . $e->getMessage());
    die("حدث خطأ في النظام. الرجاء المحاولة لاحقاً. التفاصيل: " . $e->getMessage());
}

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

error_log("Flash messages loaded - OK: " . ($flashOk ? 'Yes' : 'No') . ", ERR: " . ($flashErr ? 'Yes' : 'No'));

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

$college_id = $_GET['college_id'] ?? '';
$q = trim($_GET['q'] ?? '');
$sort = $_GET['sort'] ?? 'id_desc';
$allowedSort = ['id_desc','id_asc','medical_date_desc','medical_date_asc'];
if (!in_array($sort, $allowedSort, true)) $sort = 'id_desc';

$limit = 20;

error_log("Inputs - Status: $status, College ID: $college_id, Query: $q, Sort: $sort");

try {
    /* ------- جلب قائمة الكليات ------- */
    $colleges = [];
    error_log("Starting to load colleges...");
    
    $colleges_stmt = $mysqli1->prepare("SELECT id, name FROM colleges ORDER BY name");
    if ($colleges_stmt) {
        $colleges_stmt->execute();
        $colleges_result = $colleges_stmt->get_result();
        $college_count = 0;
        while ($college = $colleges_result->fetch_assoc()) {
            $colleges[$college['id']] = $college['name'];
            $college_count++;
        }
        $colleges_stmt->close();
        error_log("Colleges loaded: $college_count");
    } else {
        error_log("Failed to prepare colleges query");
        $colleges = [1 => 'كلية الطب', 2 => 'كلية الهندسة', 3 => 'كلية العلوم']; // بيانات افتراضية
    }

} catch (Exception $e) {
    error_log("Error loading colleges: " . $e->getMessage());
    $colleges = [1 => 'كلية الطب', 2 => 'كلية الهندسة', 3 => 'كلية العلوم'];
}

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

switch ($status) {
  case 'waiting': 
      $where[] = "s.medical_status = 'completed'";
      $where[] = "s.profile_completed = 1";
      $where[] = "s.medically_fit IS NULL";
      break;
  case 'approved':     
      $where[] = "s.medically_fit = 1";     
      $where[] = "s.medical_status = 'completed'";
      $where[] = "s.profile_completed = 1";
      break;
  case 'rejected':     
      $where[] = "s.medically_fit = 0";     
      $where[] = "s.medical_status = 'completed'";
      $where[] = "s.profile_completed = 1";
      break;
  case 'all':
  default: 
      break;
}

if (!empty($college_id) && is_numeric($college_id)) {
    $where[] = "s.college_id = ?";
    $types  .= "i";
    $params[] = $college_id;
}

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;
    }
}

$whereSql = !empty($where) ? "WHERE " . implode(" AND ", $where) : "";
error_log("WHERE SQL: $whereSql");

/* ------- 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;
}

error_log("ORDER BY: $orderBy");

/* ------- 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,
    s.college_id,
    c.name as college_name,
    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
  LEFT JOIN colleges c ON s.college_id = c.id
  $whereSql
  $orderBy
  LIMIT $limit
";

error_log("SQL Query prepared");
$students = [];
$row_count = 0;

try {
    $stmt = $mysqli1->prepare($sql);
    if (!$stmt) { 
        error_log("Failed to prepare SQL statement: " . $mysqli1->error);
        throw new Exception("DB error in preparing statement.");
    }
    
    if ($types !== '') { 
        error_log("Binding parameters: types=$types, params=" . implode(', ', $params));
        $stmt->bind_param($types, ...$params); 
    }
    
    $stmt->execute();
    error_log("SQL executed successfully");
    
    $res = $stmt->get_result();
    $row_count = $res->num_rows;
    error_log("Number of rows fetched: $row_count");
    
    // تخزين النتائج في مصفوفة للاستخدام لاحقاً
    while($row = $res->fetch_assoc()) {
        $students[] = $row;
    }
    
    $stmt->close();
    
} catch (Exception $e) {
    error_log("Error executing query: " . $e->getMessage());
    $students = [];
    $row_count = 0;
}

/* ------- Counters for tabs ------- */
function count_by($mysqli1, $condSql = '1', $types = '', $params = []) {
    try {
        $sql = "SELECT COUNT(*) FROM students s WHERE ($condSql)";
        $st = $mysqli1->prepare($sql);
        if (!$st) {
            error_log("Count query failed to prepare: " . $mysqli1->error);
            return 0;
        }
        
        if ($types) { 
            $st->bind_param($types, ...$params); 
        }
        
        $st->execute();
        $st->bind_result($c);
        $st->fetch();
        $st->close();
        return (int)$c;
    } catch (Exception $e) {
        error_log("Error in count_by: " . $e->getMessage());
        return 0;
    }
}

error_log("Starting to calculate counts...");

try {
    $totalAll   = count_by($mysqli1, '1');
    $totalWait  = count_by($mysqli1, "s.medical_status = 'completed' AND s.profile_completed = 1 AND s.medically_fit IS NULL");
    $totalApproved = count_by($mysqli1, "s.medically_fit = 1 AND s.medical_status = 'completed' AND s.profile_completed = 1");
    $totalRejected = count_by($mysqli1, "s.medically_fit = 0 AND s.medical_status = 'completed' AND s.profile_completed = 1");

    if (!empty($college_id) && is_numeric($college_id)) {
        $totalAll = count_by($mysqli1, "s.college_id = ?", "i", [$college_id]);
        $totalWait = count_by($mysqli1, "s.medical_status = 'completed' AND s.profile_completed = 1 AND s.medically_fit IS NULL AND s.college_id = ?", "i", [$college_id]);
        $totalApproved = count_by($mysqli1, "s.medically_fit = 1 AND s.medical_status = 'completed' AND s.profile_completed = 1 AND s.college_id = ?", "i", [$college_id]);
        $totalRejected = count_by($mysqli1, "s.medically_fit = 0 AND s.medical_status = 'completed' AND s.profile_completed = 1 AND s.college_id = ?", "i", [$college_id]);
    }
    
    error_log("Counts calculated - All: $totalAll, Waiting: $totalWait, Approved: $totalApproved, Rejected: $totalRejected");
    
} catch (Exception $e) {
    error_log("Error calculating counts: " . $e->getMessage());
    $totalAll = $totalWait = $totalApproved = $totalRejected = 0;
}

// حساب وقت التنفيذ
$end_time = microtime(true);
$execution_time = $end_time - $start_time;
error_log("Execution time: " . round($execution_time, 2) . " seconds");

// التحقق إذا كان وقت التنفيذ طويلاً
if ($execution_time > 10) {
    error_log("WARNING: Long execution time detected!");
}

// بدء إخراج HTML
ob_start(); // Start output buffering
?>
<!doctype html>
<html lang="ar" dir="rtl">
<head>
<meta charset="utf-8">
<title>كشف الفحص الطبي - لوحة الطبيب</title>
<?php 
// استخدام نسخة مبسطة من base_head_css إذا كانت تسبب مشاكل
echo '<meta name="viewport" content="width=device-width, initial-scale=1">';
echo '<link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;700&display=swap" rel="stylesheet">';
echo '<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">';
?>
<style>
/* CSS مختصر للبداية - يمكن إضافة المزيد لاحقاً */
:root {
  --primary: #4361ee;
  --success: #06d6a0;
  --warning: #ffd166;
  --danger: #ef476f;
  --dark: #2b2d42;
  --light: #f8f9fa;
  --border: #e9ecef;
}

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

body {
  background: #f5f7fa;
  min-height: 100vh;
  font-family: 'Cairo', sans-serif;
  padding: 20px;
}

.container {
  max-width: 1400px;
  margin: 0 auto;
  width: 100%;
}

.main-card {
  background: white;
  border-radius: 16px;
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.dashboard-header {
  background: linear-gradient(135deg, #2b2d42, #4a4e69);
  color: white;
  padding: 20px;
  text-align: center;
}

.welcome-text {
  font-size: 1.8rem;
  font-weight: 700;
  margin-bottom: 10px;
}

.subtitle {
  font-size: 1rem;
  opacity: 0.9;
  margin-bottom: 20px;
}

.action-buttons-top {
  display: flex;
  gap: 10px;
  justify-content: center;
  flex-wrap: wrap;
}

.btn {
  padding: 10px 20px;
  border: none;
  border-radius: 10px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  display: inline-flex;
  align-items: center;
  gap: 8px;
  text-decoration: none;
  font-size: 0.9rem;
  min-width: 120px;
  justify-content: center;
}

.btn-refresh {
  background: #f59e0b;
  color: white;
}

.btn-home {
  background: #10b981;
  color: white;
}

.btn-logout {
  background: #ef4444;
  color: white;
}

.btn:hover {
  transform: translateY(-2px);
  opacity: 0.9;
}

.flash-message {
  padding: 15px 20px;
  margin: 20px;
  border-radius: 12px;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 10px;
}

.flash-success {
  background: #d1fae5;
  color: #065f46;
  border: 1px solid #a7f3d0;
}

.flash-error {
  background: #fee2e2;
  color: #991b1b;
  border: 1px solid #fecaca;
}

.filters-section {
  padding: 20px;
  background: var(--light);
  border-bottom: 1px solid var(--border);
}

.filters-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 15px;
  margin-bottom: 15px;
}

.form-control {
  width: 100%;
  padding: 10px 15px;
  border: 2px solid #e2e8f0;
  border-radius: 8px;
  font-size: 0.9rem;
  font-family: 'Cairo', sans-serif;
}

.filter-actions {
  display: flex;
  gap: 10px;
  justify-content: flex-end;
  margin-top: 15px;
}

.btn-primary {
  background: var(--primary);
  color: white;
}

.btn-light {
  background: #64748b;
  color: white;
}

.tabs-section {
  padding: 15px 20px;
  background: white;
  border-bottom: 1px solid var(--border);
}

.tabs-container {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
  justify-content: center;
}

.tab {
  padding: 10px 20px;
  border-radius: 10px;
  text-decoration: none;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 8px;
  background: white;
  color: #64748b;
  border: 1px solid var(--border);
}

.tab.active {
  background: #f1f5f9;
  color: var(--primary);
}

.count-badge {
  background: #e2e8f0;
  padding: 4px 8px;
  border-radius: 20px;
  font-size: 0.8rem;
  font-weight: 700;
  min-width: 30px;
  text-align: center;
}

.table-section {
  padding: 0;
  overflow-x: auto;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
  min-width: 800px;
}

.data-table th {
  background: #f8fafc;
  padding: 12px 10px;
  text-align: right;
  font-weight: 700;
  color: var(--dark);
  border-bottom: 2px solid var(--border);
}

.data-table td {
  padding: 12px 10px;
  border-bottom: 1px solid var(--border);
}

.table-footer {
  padding: 15px 20px;
  background: #f8fafc;
  border-top: 1px solid var(--border);
  text-align: center;
  color: #64748b;
}

.status-badge {
  padding: 5px 10px;
  border-radius: 20px;
  font-size: 0.8rem;
  font-weight: 700;
  display: inline-flex;
  align-items: center;
  gap: 4px;
}

.badge-waiting { background: #fef3c7; color: #92400e; }
.badge-approved { background: #d1fae5; color: #065f46; }
.badge-rejected { background: #fee2e2; color: #991b1b; }

.action-btn {
  padding: 6px 12px;
  background: var(--primary);
  color: white;
  text-decoration: none;
  border-radius: 6px;
  font-size: 0.8rem;
  display: inline-flex;
  align-items: center;
  gap: 5px;
}

@media (max-width: 768px) {
  body { padding: 10px; }
  .welcome-text { font-size: 1.5rem; }
  .action-buttons-top { flex-direction: column; align-items: center; }
  .btn { width: 100%; max-width: 300px; }
  .filters-grid { grid-template-columns: 1fr; }
}
</style>
</head>
<body>
<div class="container">
  <div class="main-card">
    <!-- الهيدر -->
    <div class="dashboard-header">
      <div class="header-content">
        <div class="welcome-text">
          <i class="fas fa-user-md"></i>
          مرحباً د. <?php echo htmlspecialchars($doctor['name'] ?? 'الطبيب'); ?>
        </div>
        <div class="subtitle">لوحة التحكم - إدارة الخدمات الصحية</div>
        
        <!-- أزرار الإجراءات في الأعلى -->
        <div class="action-buttons-top">
          <button class="btn btn-refresh" id="refreshBtn">
            <i class="fas fa-sync-alt"></i>
            تحديث الصفحة
          </button>
          
          <a href="../index.php" class="btn btn-home" id="homeBtn">
            <i class="fas fa-home"></i>
            الصفحة الرئيسية
          </a>
          
          <a href="signout.php?role=doctor" class="btn btn-logout" id="logoutBtn">
            <i class="fas fa-sign-out-alt"></i>
            تسجيل الخروج
          </a>
        </div>
      </div>
    </div>

    <!-- الرسائل -->
    <?php if ($flashOk): ?>
      <div class="flash-message flash-success">
        <i class="fas fa-check-circle"></i>
        <?php echo htmlspecialchars($flashOk); ?>
      </div>
    <?php endif; ?>
    
    <?php if ($flashErr): ?>
      <div class="flash-message flash-error">
        <i class="fas fa-exclamation-triangle"></i>
        <?php echo htmlspecialchars($flashErr); ?>
      </div>
    <?php endif; ?>

    <!-- الفلاتر -->
    <div class="filters-section">
      <form method="get" id="filtersForm">
        <input type="hidden" name="status" value="<?php echo htmlspecialchars($status); ?>">
        
        <div class="filters-grid">
          <div class="filter-group">
            <label style="font-weight: 600; margin-bottom: 5px; display: block;">
              <i class="fas fa-university"></i> الكليّة
            </label>
            <select name="college_id" class="form-control">
              <option value="">جميع الكليات</option>
              <?php foreach ($colleges as $id => $name): ?>
                <option value="<?php echo $id; ?>" <?php echo $college_id == $id ? 'selected' : ''; ?>>
                  <?php echo htmlspecialchars($name); ?>
                </option>
              <?php endforeach; ?>
            </select>
          </div>

          <div class="filter-group">
            <label style="font-weight: 600; margin-bottom: 5px; display: block;">
              <i class="fas fa-search"></i> البحث
            </label>
            <input type="text" name="q" value="<?php echo htmlspecialchars($q); ?>" 
                   placeholder="ابحث برقم أو اسم الطالب..." class="form-control">
          </div>

          <div class="filter-group">
            <label style="font-weight: 600; margin-bottom: 5px; display: block;">
              <i class="fas fa-sort"></i> الترتيب
            </label>
            <select name="sort" class="form-control">
              <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>
          </div>
        </div>

        <div class="filter-actions">
          <button type="submit" class="btn btn-primary">
            <i class="fas fa-filter"></i>
            تطبيق الفلاتر
          </button>
          <a href="medical_list.php?status=all" class="btn btn-light">
            <i class="fas fa-times"></i>
            إعادة تعيين
          </a>
        </div>
      </form>
    </div>

    <!-- التبويبات -->
    <div class="tabs-section">
      <div class="tabs-container">
        <a class="tab all <?php echo $status==='all'?'active':''; ?>" 
           href="?status=all&sort=<?php echo urlencode($sort); ?>&q=<?php echo urlencode($q); ?>&college_id=<?php echo urlencode($college_id); ?>">
          <i class="fas fa-users"></i>
          الكل
          <span class="count-badge"><?php echo $totalAll; ?></span>
        </a>
        
        <a class="tab waiting <?php echo $status==='waiting'?'active':''; ?>" 
           href="?status=waiting&sort=<?php echo urlencode($sort); ?>&q=<?php echo urlencode($q); ?>&college_id=<?php echo urlencode($college_id); ?>">
          <i class="fas fa-clock"></i>
          في الانتظار
          <span class="count-badge"><?php echo $totalWait; ?></span>
        </a>
        
        <a class="tab approved <?php echo $status==='approved'?'active':''; ?>" 
           href="?status=approved&sort=<?php echo urlencode($sort); ?>&q=<?php echo urlencode($q); ?>&college_id=<?php echo urlencode($college_id); ?>">
          <i class="fas fa-check-circle"></i>
          مقبول
          <span class="count-badge"><?php echo $totalApproved; ?></span>
        </a>
        
        <a class="tab rejected <?php echo $status==='rejected'?'active':''; ?>" 
           href="?status=rejected&sort=<?php echo urlencode($sort); ?>&q=<?php echo urlencode($q); ?>&college_id=<?php echo urlencode($college_id); ?>">
          <i class="fas fa-times-circle"></i>
          مرفوض
          <span class="count-badge"><?php echo $totalRejected; ?></span>
        </a>
      </div>
    </div>

    <!-- الجدول -->
    <div class="table-section">
      <?php if (empty($students)): ?>
        <div style="text-align: center; padding: 40px; color: #64748b;">
          <i class="fas fa-info-circle" style="font-size: 3rem; margin-bottom: 20px; opacity: 0.5;"></i>
          <h3 style="margin-bottom: 10px;">لا توجد بيانات للعرض</h3>
          <p>حاول تغيير معايير البحث أو الفلاتر.</p>
        </div>
      <?php else: ?>
        <table class="data-table">
          <thead>
            <tr>
              <th>الرقم الجامعي</th>
              <th>اسم الطالب</th>
              <th>الكليّة</th>
              <th>الهاتف</th>
              <th>الحالة</th>
              <th>آخر فحص</th>
              <th>الإجراء</th>
            </tr>
          </thead>
          <tbody>
          <?php foreach ($students as $row): ?>
            <?php
              $name  = $row['student_name'] ?: $row['student_name_eng'];
              $medically_fit = $row['medically_fit'];
              
              if ($medically_fit === null) { 
                $medTxt = 'في الانتظار'; 
                $medClass = 'badge-waiting';
                $medIcon = 'fas fa-clock';
              } elseif ((int)$medically_fit === 1) { 
                $medTxt = 'مقبول طبيًا';         
                $medClass = 'badge-approved';
                $medIcon = 'fas fa-check-circle';
              } else { 
                $medTxt = 'مرفوض طبيًا';     
                $medClass = 'badge-rejected';
                $medIcon = 'fas fa-times-circle';
              }
            ?>
            <tr>
              <td><?php echo htmlspecialchars($row['student_id']); ?></td>
              <td><?php echo htmlspecialchars($name); ?></td>
              <td><?php echo htmlspecialchars($row['college_name'] ?? '—'); ?></td>
              <td><?php echo htmlspecialchars($row['phone_number'] ?? '—'); ?></td>
              <td>
                <span class="status-badge <?php echo $medClass; ?>">
                  <i class="<?php echo $medIcon; ?>"></i>
                  <?php echo $medTxt; ?>
                </span>
              </td>
              <td><?php echo $row['medical_checked_at'] ? date('Y-m-d H:i', strtotime($row['medical_checked_at'])) : '—'; ?></td>
              <td>
                <a class="action-btn" href="medical_review.php?id=<?php echo urlencode($row['student_id']); ?>">
                  <i class="fas fa-eye"></i>
                  عرض
                </a>
              </td>
            </tr>
          <?php endforeach; ?>
          </tbody>
        </table>
      <?php endif; ?>
    </div>

    <!-- الفوتر -->
    <div class="table-footer">
      <i class="fas fa-info-circle"></i>
      <?php if (!empty($students)): ?>
        تم عرض <?php echo count($students); ?> طالب. <?php echo ($row_count >= $limit ? ' (الحد الأقصى ' . $limit . ')' : ''); ?>
      <?php else: ?>
        لا توجد نتائج مطابقة للبحث
      <?php endif; ?>
      <br>
      <small>وقت التنفيذ: <?php echo round($execution_time, 2); ?> ثانية</small>
    </div>
  </div>
</div>

<script>
// JavaScript مبسط
document.addEventListener('DOMContentLoaded', function() {
  console.log('Page loaded successfully');
  
  // زر التحديث
  const refreshBtn = document.getElementById('refreshBtn');
  if (refreshBtn) {
    refreshBtn.addEventListener('click', function(e) {
      e.preventDefault();
      console.log('Refreshing page...');
      
      // تأثير بسيط
      const icon = this.querySelector('i');
      const originalClass = icon.className;
      icon.className = 'fas fa-spinner fa-spin';
      
      setTimeout(() => {
        window.location.reload();
      }, 300);
    });
  }
  
  // زر الخروج مع تأكيد
  const logoutBtn = document.getElementById('logoutBtn');
  if (logoutBtn) {
    logoutBtn.addEventListener('click', function(e) {
      if (!confirm('هل أنت متأكد من تسجيل الخروج؟')) {
        e.preventDefault();
      }
    });
  }
  
  // تحسين تجربة البحث
  const searchInput = document.querySelector('input[name="q"]');
  if (searchInput) {
    searchInput.addEventListener('keypress', function(e) {
      if (e.key === 'Enter') {
        e.preventDefault();
        document.getElementById('filtersForm').submit();
      }
    });
  }
  
  // تأثيرات بسيطة للأزرار
  const buttons = document.querySelectorAll('.btn');
  buttons.forEach(btn => {
    btn.addEventListener('mousedown', function() {
      this.style.opacity = '0.8';
    });
    btn.addEventListener('mouseup', function() {
      this.style.opacity = '';
    });
  });
});
</script>
</body>
</html>
<?php
ob_end_flush(); // إرسال المحتوى المخرن
error_log("=== Page generated successfully ===");
?>