<?php
// medical_review.php — Doctor view of medical form data
error_reporting(E_ALL);
ini_set('display_errors', 1);

// بداية الجلسة إذا لم تبدأ
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require 'db.php';
require 'helpers.php';
require_doctor();
$doctor = current_doctor();

/* ------- Input ------- */
$student_id = $_GET['id'] ?? '';
if (!$student_id) { 
    header("Location: medical_list.php"); 
    exit; 
}

/* ------- Get student data with medical records ------- */
$sql = "
  SELECT 
    s.student_id, s.student_name, s.student_name_eng, s.gender, s.date_of_birth, s.nationality,
    s.phone_number, s.phone_number2, s.email, s.medically_fit, s.medical_notes, s.medical_checked_at, 
    s.interview_status, s.profile_completed, s.college_id, s.program_id,
    c.name as college_name, p.name as program_name,
    m.*
  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
  LEFT JOIN programs p ON s.program_id = p.id
  WHERE s.student_id = ?
";

// استخدام $mysqli1 بدلاً من $mysqli إذا كان هذا هو المتغير المستخدم في db.php
$stmt = $mysqli1->prepare($sql);
if (!$stmt) {
    die("خطأ في إعداد الاستعلام: " . $mysqli1->error);
}

// استخدام "s" لنوع string بدلاً من "i" ل integer
$stmt->bind_param("s", $student_id);

if (!$stmt->execute()) {
    die("خطأ في تنفيذ الاستعلام: " . $stmt->error);
}

$student = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$student) { 
    flash_set('err', 'لم يتم العثور على الطالب'); 
    header("Location: medical_list.php"); 
    exit; 
}

/* block if not completed */
if ((int)$student['profile_completed'] !== 1) {
    flash_set('err', 'لا يمكن فحص طالب لم يُكمل/يحدّث ملفه.');
    header("Location: medical_list.php");
    exit;
}

$err = '';

/* ------- Handle POST ------- */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verify_csrf($_POST['csrf'] ?? '')) {
        $err = "رمز الحماية غير صالح.";
    } else {
        $medical_notes = trim($_POST['medical_notes'] ?? '');
        $doctor_decision = $_POST['doctor_decision'] ?? ''; // approved, rejected
        
        $valid_decisions = ['approved', 'rejected'];
        if (!in_array($doctor_decision, $valid_decisions)) {
            $err = "يرجى اختيار قرار طبي صحيح.";
        } else {
            // Update student record with doctor's decision
            $medically_fit = $doctor_decision === 'approved' ? 1 : 0;
            $medical_checked_at = date('Y-m-d H:i:s');
            
            $update_stmt = $mysqli1->prepare("
                UPDATE students 
                SET medically_fit = ?,
                    medical_notes = ?,
                    medical_checked_at = ?
                WHERE student_id = ?
            ");
            
            if (!$update_stmt) {
                $err = "خطأ في إعداد استعلام التحديث: " . $mysqli1->error;
            } else {
                // استخدام "s" لنوع string لل student_id
                $update_stmt->bind_param("isss", $medically_fit, $medical_notes, $medical_checked_at, $student_id);
                
                if ($update_stmt->execute()) {
                    flash_set('ok', 'تم حفظ القرار الطبي بنجاح.');
                    header("Location: medical_list.php");
                    exit;
                } else {
                    $err = "حدث خطأ أثناء الحفظ: " . $update_stmt->error;
                }
                $update_stmt->close();
            }
        }
    }
}

// Medical questions in both languages
$medical_questions = [
    'has_disability' => [
        'ar' => 'إعاقة حركية',
        'en' => 'Physical Disability'
    ],
    'has_chronic_diseases' => [
        'ar' => 'أمراض مزمنة', 
        'en' => 'Chronic Diseases'
    ],
    'has_psychological_diseases' => [
        'ar' => 'أمراض نفسية',
        'en' => 'Psychological Diseases'
    ],
    'has_vision_problems' => [
        'ar' => 'مشاكل في الرؤية',
        'en' => 'Vision Problems'
    ],
    'has_hearing_problems' => [
        'ar' => 'مشاكل في السمع',
        'en' => 'Hearing Problems'
    ],
    'covid_vaccinated' => [
        'ar' => 'تطعيم كوفيد-19',
        'en' => 'COVID-19 Vaccination'
    ],
    'has_diabetes' => [
        'ar' => 'سكري',
        'en' => 'Diabetes'
    ],
    'has_blood_pressure' => [
        'ar' => 'ضغط الدم',
        'en' => 'Blood Pressure'
    ],
    'has_family_diseases' => [
        'ar' => 'أمراض وراثية في العائلة',
        'en' => 'Family Genetic Diseases'
    ]
];
?>
<!doctype html>
<html lang="ar" dir="rtl">
<head>
<meta charset="utf-8">
<title>الملف الطبي: <?php echo e($student['student_id']); ?></title>
<?php base_head_css(); ?>
<style>
  :root {
    --uofg-primary: #1e3a8a;
    --uofg-success: #198754;
    --uofg-danger: #dc3545;
    --uofg-warning: #ffc107;
    --uofg-light: #f8f9fa;
    --uofg-border: #dee2e6;
  }
  
  body {
    background-color: #f5f5f5;
    min-height: 100vh;
    padding: 20px 0;
    font-family: 'Cairo', sans-serif;
  }
  
  .medical-container {
    background: white;
    border-radius: 10px;
    box-shadow: 0 0 20px rgba(0,0,0,0.1);
    overflow: hidden;
    margin: 0 auto;
    max-width: 1000px;
    border: 1px solid var(--uofg-border);
  }
  
  .header {
    background: linear-gradient(135deg, var(--uofg-primary) 0%, #2c5aa0 100%);
    color: white;
    padding: 30px;
    text-align: center;
    border-bottom: 4px solid var(--uofg-success);
  }
  
  .student-info {
    background: var(--uofg-light);
    border: 1px solid var(--uofg-border);
    border-radius: 8px;
    padding: 20px;
    margin: 20px;
  }
  
  .medical-section {
    background: white;
    border: 1px solid var(--uofg-border);
    border-radius: 8px;
    padding: 25px;
    margin: 15px 20px;
  }
  
  .question-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 0;
    border-bottom: 1px solid #f1f5f9;
  }
  
  .question-item:last-child {
    border-bottom: none;
  }
  
  .question-text {
    flex: 1;
  }
  
  .question-arabic {
    font-size: 1.1rem;
    font-weight: 600;
    color: #2c3e50;
    margin-bottom: 4px;
  }
  
  .question-english {
    font-size: 0.9rem;
    font-weight: 500;
    color: #6c757d;
    font-style: italic;
  }
  
  .answer-badge {
    padding: 6px 12px;
    border-radius: 20px;
    font-size: 0.9rem;
    font-weight: 600;
    min-width: 80px;
    text-align: center;
  }
  
  .answer-yes {
    background: var(--uofg-danger);
    color: white;
  }
  
  .answer-no {
    background: var(--uofg-success);
    color: white;
  }
  
  .details-box {
    background: #f8f9fa;
    border: 1px solid #e9ecef;
    border-radius: 6px;
    padding: 15px;
    margin-top: 10px;
  }
  
  .form-actions {
    background: var(--uofg-light);
    padding: 25px;
    border-top: 1px solid var(--uofg-border);
  }
  
  .btn {
    display: inline-block;
    padding: 10px 20px;
    border-radius: 6px;
    text-decoration: none;
    font-weight: 600;
    border: none;
    cursor: pointer;
    transition: all 0.3s ease;
  }
  
  .btn-primary {
    background: var(--uofg-primary);
    color: white;
  }
  
  .btn-success {
    background: var(--uofg-success);
    color: white;
  }
  
  .btn-danger {
    background: var(--uofg-danger);
    color: white;
  }
  
  .btn-light {
    background: #6c757d;
    color: white;
  }
  
  .btn:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(0,0,0,0.2);
  }
  
  .notice {
    padding: 12px 16px;
    border-radius: 6px;
    margin: 20px;
  }
  
  .notice-error {
    background: #f8d7da;
    border: 1px solid #f5c6cb;
    color: #721c24;
  }
  
  .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; }
  
  .current-status {
    padding: 10px 15px;
    border-radius: 6px;
    margin-bottom: 20px;
    text-align: center;
    font-weight: 600;
  }
  
  .status-waiting { background: #fffbeb; border: 1px solid #fcd34d; color: #92400e; }
  .status-approved { background: #f0fdf4; border: 1px solid #86efac; color: #166534; }
  .status-rejected { background: #fef2f2; border: 1px solid #fca5a5; color: #991b1b; }
  
  .row {
    display: flex;
    flex-wrap: wrap;
    margin: 0 -10px;
  }
  
  .col-md-6 {
    flex: 0 0 50%;
    padding: 0 10px;
    margin-bottom: 10px;
  }
  
  @media (max-width: 768px) {
    .col-md-6 {
      flex: 0 0 100%;
    }
  }
</style>
<link href="https://fonts.googleapis.com/css2?family=Cairo:wght@300;400;500;600;700&display=swap" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
  <div class="medical-container">
    <!-- Header -->
    <div class="header">
      <h1><i class="fas fa-file-medical"></i> الملف الطبي للطالب</h1>
      <p>جامعة الجزيرة - قسم الشؤون الطبية</p>
    </div>

    <!-- Student Information -->
    <div class="student-info">
      <div class="row">
        <div class="col-md-6">
          <strong>الاسم:</strong> <?php echo e($student['student_name']); ?>
        </div>
        <div class="col-md-6">
          <strong>الرقم الجامعي:</strong> <?php echo e($student['student_id']); ?>
        </div>
        <div class="col-md-6">
          <strong>الكليّة:</strong> <?php echo e($student['college_name'] ?? 'غير محدد'); ?>
        </div>
        <div class="col-md-6">
          <strong>البرنامج:</strong> <?php echo e($student['program_name'] ?? 'غير محدد'); ?>
        </div>
        <div class="col-md-6">
          <strong>الجنس:</strong> <?php echo e($student['gender'] == 1 ? 'ذكر' : ($student['gender'] == 2 ? 'أنثى' : 'غير محدد')); ?>
        </div>
        <div class="col-md-6">
          <strong>تاريخ الميلاد:</strong> <?php echo e($student['date_of_birth'] ?? 'غير محدد'); ?>
        </div>
        <div class="col-md-6">
          <strong>الجنسية:</strong> <?php echo e($student['nationality'] ?? 'غير محدد'); ?>
        </div>
        <div class="col-md-6">
          <strong>الهاتف:</strong> <?php echo e($student['phone_number'] ?? 'غير محدد'); ?>
        </div>
        <div class="col-md-6">
          <strong>البريد الإلكتروني:</strong> <?php echo e($student['email'] ?? 'غير محدد'); ?>
        </div>
      </div>
    </div>

    <?php if ($err): ?>
      <div class="notice notice-error">
        <i class="fas fa-exclamation-triangle"></i> <?php echo e($err); ?>
      </div>
    <?php endif; ?>

    <!-- Current Medical Status -->
    <div class="medical-section">
      <h3><i class="fas fa-info-circle"></i> الحالة الطبية الحالية</h3>
      <?php
        $medically_fit = $student['medically_fit'];
        if ($medically_fit === null) {
          $statusText = 'في الانتظار';
          $statusClass = 'status-waiting';
        } elseif ((int)$medically_fit === 1) {
          $statusText = 'مقبول طبيًا';
          $statusClass = 'status-approved';
        } else {
          $statusText = 'مرفوض طبيًا';
          $statusClass = 'status-rejected';
        }
      ?>
      <div class="current-status <?php echo $statusClass; ?>">
        الحالة الحالية: <?php echo $statusText; ?>
        <?php if ($student['medical_checked_at']): ?>
          <br><small>آخر تحديث: <?php echo e($student['medical_checked_at']); ?></small>
        <?php endif; ?>
      </div>
    </div>

    <!-- Medical Information -->
    <div class="medical-section">
      <h3><i class="fas fa-stethoscope"></i> المعلومات الطبية</h3>
      
      <?php if ($student['medical_date']): ?>
        <p><strong>تاريخ تعبئة النموذج:</strong> <?php echo e($student['medical_date']); ?></p>
        
        <div class="medical-questions">
          <?php foreach ($medical_questions as $field => $text): ?>
            <div class="question-item">
              <div class="question-text">
                <div class="question-arabic"><?php echo e($text['ar']); ?></div>
                <div class="question-english"><?php echo e($text['en']); ?></div>
              </div>
              <div class="answer-badge <?php echo ($student[$field] ?? 'no') === 'yes' ? 'answer-yes' : 'answer-no'; ?>">
                <?php echo ($student[$field] ?? 'no') === 'yes' ? 'نعم' : 'لا'; ?>
              </div>
            </div>
            
            <!-- Show details for specific questions -->
            <?php if ($field === 'has_chronic_diseases' && ($student[$field] ?? 'no') === 'yes' && !empty($student['chronic_diseases_details'])): ?>
              <div class="details-box">
                <strong>تفاصيل الأمراض المزمنة:</strong>
                <p><?php echo e($student['chronic_diseases_details']); ?></p>
              </div>
            <?php endif; ?>
            
            <?php if ($field === 'has_family_diseases' && ($student[$field] ?? 'no') === 'yes' && !empty($student['family_diseases_details'])): ?>
              <div class="details-box">
                <strong>تفاصيل الأمراض الوراثية في العائلة:</strong>
                <p><?php echo e($student['family_diseases_details']); ?></p>
              </div>
            <?php endif; ?>
          <?php endforeach; ?>
        </div>

        <!-- Additional Notes -->
        <?php if (!empty($student['additional_notes'])): ?>
          <div class="details-box" style="margin-top: 20px;">
            <strong>ملاحظات إضافية من الطالب:</strong>
            <p><?php echo e($student['additional_notes']); ?></p>
          </div>
        <?php endif; ?>

      <?php else: ?>
        <div class="text-center" style="padding: 40px; color: #6c757d;">
          <i class="fas fa-file-medical" style="font-size: 3rem; margin-bottom: 15px;"></i>
          <p>لم يقم الطالب بتعبئة النموذج الطبي بعد.</p>
        </div>
      <?php endif; ?>
    </div>

    <!-- Doctor Decision Form -->
    <?php if ($student['medical_date']): ?>
    <div class="medical-section">
      <h3><i class="fas fa-user-md"></i> قرار الطبيب</h3>
      <form method="post">
        <input type="hidden" name="csrf" value="<?php echo e(csrf_token()); ?>">
        
        <div style="margin-bottom: 20px;">
          <label style="display: block; margin-bottom: 10px; font-weight: 600;">القرار الطبي:</label>
          <div style="display: flex; gap: 15px; flex-wrap: wrap;">
            <label style="display: flex; align-items: center; gap: 8px; cursor: pointer;">
              <input type="radio" name="doctor_decision" value="approved" required
                     <?php echo ($student['medically_fit'] === 1 ? 'checked' : ''); ?>>
              <span>مقبول طبيًا</span>
            </label>
            <label style="display: flex; align-items: center; gap: 8px; cursor: pointer;">
              <input type="radio" name="doctor_decision" value="rejected" required
                     <?php echo ($student['medically_fit'] === 0 ? 'checked' : ''); ?>>
              <span>مرفوض طبيًا</span>
            </label>
          </div>
        </div>
        
        <div style="margin-bottom: 20px;">
          <label style="display: block; margin-bottom: 8px; font-weight: 600;">ملاحظات الطبيب:</label>
          <textarea name="medical_notes" rows="4" style="width: 100%; padding: 10px; border: 1px solid var(--uofg-border); border-radius: 6px;"><?php echo e($student['medical_notes'] ?? ''); ?></textarea>
        </div>
        
        <div class="form-actions">
          <div style="display: flex; gap: 10px; justify-content: center;">
            <button type="submit" class="btn btn-success">
              <i class="fas fa-save"></i> حفظ القرار
            </button>
            <a href="medical_list.php" class="btn btn-light">
              <i class="fas fa-arrow-right"></i> العودة للقائمة
            </a>
          </div>
        </div>
      </form>
    </div>
    <?php endif; ?>
  </div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/js/all.min.js"></script>
</body>
</html>