<?php
header("Expires: Tue, 01 Jan 2000 00:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require 'db.php';
require 'helpers.php';
require_student();

$student_id = $_SESSION['student_id'];

// First, let's check if the student exists with a simple query
$check_stmt = $mysqli1->prepare("SELECT student_id, student_name FROM students WHERE student_id = ?");
$check_stmt->bind_param("s", $student_id);
$check_stmt->execute();
$check_result = $check_stmt->get_result();

if ($check_result->num_rows === 0) {
    die("Error: No student found with ID: " . htmlspecialchars($student_id));
}

// Now try the full query
$data = [];
$full_stmt = $mysqli1->prepare("
SELECT 
  s.student_id,
  s.student_name,
  s.student_name_eng,
  s.email,
  s.country_id,
  s.state_id,
  s.locality_id,
  s.blood_type,
  s.phone_number,
  s.phone_number2,
  s.nationality,
  s.national_id,
  s.guardian_name,
  s.guardian_phone_number,
  s.guardian_address,
  s.date_of_birth,
  s.agreed_regulations,
  s.self_declare_fit,
  s.gender,
  s.program_fees,
  s.home_address,
  s.student_case,
  s.medical_status,
  s.profile_completed,
  s.last_medical_exam,
  c.name AS college_name,
  p.name AS program_name,
  sec.name AS section_name
FROM students s
LEFT JOIN colleges c ON s.college_id = c.id
LEFT JOIN programs p ON s.program_id = p.id
LEFT JOIN sections sec ON s.section_id = sec.id
WHERE s.student_id = ?
");

if ($full_stmt) {
    $full_stmt->bind_param("s", $student_id);
    $full_stmt->execute();
    $full_result = $full_stmt->get_result();
    $data = $full_result->fetch_assoc() ?? [];
} else {
    die("Error in full query: " . $mysqli1->error);
}

// Check medical status
$medical_status = $data['medical_status'] ?? 'pending';
$last_exam = $data['last_medical_exam'] ?? null;
$medical_record = $mysqli1->query("SELECT * FROM student_medical_records WHERE student_id = '$student_id' ORDER BY created_at DESC LIMIT 1")->fetch_assoc();

// Determine if student can submit
$can_submit = ($medical_status === 'completed');
$can_edit_profile = $can_submit;
// Calculate fees
$registration_fees = 250000;
$medical_fees = 100000;
$program_fees = $data['program_fees'] ?? 0;
$total_fees = $registration_fees + $medical_fees + $program_fees;

include 'header.php';
?>

<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>الملف الشخصي للطالب</title>
    
    <!-- External CSS -->
    <link rel="stylesheet" href="css/student_profile.css">
    <link rel="preconnect" href="https://fonts.googleapis.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=AR+One+Sans&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
</head>
<body>
    <div class="row">
        <div class="col-12">
            <div class="card p-3 p-md-4 mb-4 shadow-sm">

                <div class="w-100">
                    <div class="card card-arabic p-3 p-md-4 shadow-sm">
                        <h6 class="mb-3 rtl-heading">ملخص الطلب</h6>
                        <ul class="list-group list-group-flush">
                            <li class="list-group-item"><strong>رقم الطالب:</strong> 
                                <?= e(strlen($data['student_id']) === 10 ? substr($data['student_id'], 0, 2) . '-' . substr($data['student_id'], 2) : $data['student_id']) ?>
                            </li>
                            <li class="list-group-item"><strong>الاسم:</strong> <?= e($data['student_name']) ?></li>
                            <li class="list-group-item"><strong>الكلية:</strong> <?= e($data['college_name']) ?></li>
                            <li class="list-group-item"><strong>البرنامج:</strong> <?= e($data['program_name']) ?></li>
                            <li class="list-group-item"><strong>القسم:</strong> <?= e($data['section_name']) ?></li>
                        </ul>
                    </div>
                </div>

                <!-- Medical Requirement Alert -->
                <?php if (!$can_submit): ?>
                <div class="alert alert-danger medical-required-alert card-arabic mt-4" role="alert">
                    <div class="d-flex align-items-center">
                        <i class="fas fa-exclamation-triangle fa-2x me-3"></i>
                        <div>
                            <h5 class="alert-heading mb-2">تنبيه مهم!</h5>
                            <p class="mb-2">يجب استكمال الملف الطبي قبل إرسال الطلب.</p>
                            <p class="mb-0">الرجاء الضغط على زر "تعبئة النموذج الطبي" لاستكمال البيانات الطبية.</p>
                        </div>
                    </div>
                </div>
                <?php endif; ?>

                <br/>
                
<!-- Enhanced Medical Status Card -->
<div class="col-12">
    <div class="card card-arabic p-3 mb-4">
        <div class="d-flex justify-content-between align-items-center mb-3">
            <h6 class="rtl-heading mb-0" style="text-decoration:none;color:#000;">حالة الملف</h6>
            <span class="badge <?= $can_submit ? 'bg-success' : 'bg-warning' ?> p-2 medical-status-badge">
                <?= $can_submit ? 'مكتمل وجاهز للإرسال' : 'قيد الاستكمال' ?>
            </span>
        </div>
        
        <!-- Status Progress -->
        <div class="status-progress mb-3">
            <div class="progress" style="height: 10px;">
                <div class="progress-bar <?= $can_submit ? 'bg-success' : 'bg-danger' ?>" 
                     role="progressbar" 
                     style="width: <?= $can_submit ? '100' : '50' ?>%">
                </div>
            </div>
            <div class="d-flex justify-content-between mt-2">
                <small class="<?= $medical_status === 'completed' ? 'text-success fw-bold' : 'text-muted' ?>">
                    <i class="fas <?= $medical_status === 'completed' ? 'fa-check-circle' : 'fa-clock' ?> me-1"></i>
                    الملف الطبي
                </small>
                <small class="<?= $can_submit ? 'text-success fw-bold' : 'text-muted' ?>">
                    <i class="fas <?= $can_submit ? 'fa-check-circle' : 'fa-edit' ?> me-1"></i>
                    البيانات الشخصية
                </small>
            </div>
        </div>
        
        <?php if ($last_exam): ?>
            <div class="mb-3" style="direction: rtl; text-align: right;">
                <p class="text-muted mb-1" style="font-size: 0.9rem;">
                    <i class="fas fa-calendar-alt me-1"></i>
                    آخر فحص: <?= e($last_exam) ?>
                </p>
            </div>
        <?php endif; ?>
        
        <div class="d-flex flex-wrap gap-2 justify-content-between align-items-center">
            <div class="d-flex flex-wrap gap-2 medical-action-buttons">
                <?php if ($medical_status === 'completed' && $medical_record): ?>
                    <a href="student_medical_form.php" class="btn btn-outline-primary btn-sm">
                        <i class="fas fa-eye me-1"></i> عرض السجل الطبي
                    </a>
                    <a href="student_medical_form.php" class="btn btn-outline-secondary btn-sm">
                        <i class="fas fa-edit me-1"></i> تحديث البيانات
                    </a>
                <?php else: ?>
                    <a href="student_medical_form.php" class="btn btn-success btn-lg pulse">
                        <i class="fas fa-file-medical me-1"></i> تعبئة النموذج الطبي
                    </a>
                <?php endif; ?>
            </div>
            
            <div class="medical-status-text <?= $can_submit ? 'text-success' : 'text-warning' ?>">
                <i class="fas <?= $can_submit ? 'fa-check-circle' : 'fa-exclamation-triangle' ?> me-1"></i>
                <?= $can_submit ? 'الملف جاهز للإرسال' : 'يجب استكمال الملف الطبي أولاً' ?>
            </div>
        </div>
    </div>
</div>

<!-- Disabled Overlay -->
<?php if (!$can_edit_profile): ?>
<div class="disabled-overlay">
    <div class="disabled-message">
        <div class="alert alert-danger">
            <div class="d-flex align-items-center">
                <i class="fas fa-lock fa-2x me-3"></i>
                <div>
                    <h4 class="alert-heading mb-2">النموذج مغلق</h4>
                    <p class="mb-2">لا يمكنك تعديل البيانات الشخصية حتى تكمل النموذج الطبي أولاً.</p>
                    <p class="mb-0">الرجاء استكمال النموذج الطبي لفتح جميع الخيارات.</p>
                </div>
            </div>
        </div>
        <a href="student_medical_form.php" class="btn btn-success btn-lg">
            <i class="fas fa-file-medical me-2"></i>
            انتقل إلى النموذج الطبي
        </a>
    </div>
</div>
<?php endif; ?>

<!-- Your Form - Add conditional class -->
<form method="post" action="student_update.php" class="row g-3 <?= !$can_edit_profile ? 'form-disabled' : '' ?>" enctype="multipart/form-data" id="studentForm" data-medical-status="<?= $medical_status ?>">
 
                </br>
                <h5 class="mb-3 rtl-heading">أكمل بيانات الملف</h5>

                <!-- IMPORTANT: add enctype for file uploads -->
                <form method="post" action="student_update.php" class="row g-3" enctype="multipart/form-data" id="studentForm" data-medical-status="<?= $medical_status ?>">
                    
                    <!-- CSRF Token -->
                    <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">

                    <!-- Basic Info -->
                    <div class="col-md-6 form-floating rtl-fix">
                        <input class="form-control" name="student_name" id="student_name" value="<?= e($data['student_name']) ?>" placeholder="الاسم الكامل" readonly>
                        <label for="student_name">الاسم الكامل (بالعربية)</label>
                    </div>

                    <div class="col-md-6 form-floating rtl-fix">
                        <input class="form-control" name="student_name_eng" id="student_name_eng" value="<?= e($data['student_name_eng']) ?>" placeholder="الاسم الكامل بالإنجليزية" required>
                        <label for="student_name_eng">الاسم الكامل (بالإنجليزية)</label>
                    </div>

                    <div class="col-md-6 form-floating rtl-fix">
                        <input
                            type="email"
                            class="form-control"
                            name="email"
                            id="email"
                            value="<?= e($data['email']) ?>"
                            placeholder="البريد الإلكتروني"
                            required
                            autocomplete="email"
                            inputmode="email"
                            dir="ltr"
                            pattern="^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,63}$"
                            title="يرجى إدخال بريد إلكتروني صحيح مثل name@example.com"
                        />
                        <label for="email">البريد الإلكتروني</label>
                        <div class="invalid-feedback">أدخل بريدًا إلكترونيًا صحيحًا مثل name@example.com</div>
                    </div>

                    <!-- Phone Number 1 -->
                    <div class="col-md-6 form-floating rtl-fix">
                        <input
                            class="form-control phone-input"
                            name="phone_number"
                            id="phone_number"
                            value="<?= e($data['phone_number']) ?>"
                            placeholder="رقم الهاتف"
                            required
                            inputmode="tel"
                            pattern="^249\d{9}$"
                            title="يرجى إدخال رقم هاتف يبدأ بـ 249 ويتكون من 12 رقمًا مثل 249123456789"
                            maxlength="12"
                        />
                        <label for="phone_number">رقم الهاتف</label>
                        <div class="valid-feedback">رقم هاتف صحيح</div>
                        <div class="invalid-feedback">يجب أن يبدأ الرقم بـ 249 ويتكون من 12 رقمًا</div>
                    </div>

                    <!-- Phone Number 2 -->
                    <div class="col-md-6 form-floating rtl-fix">
                        <input 
                            class="form-control phone-input" 
                            name="phone_number2" 
                            id="phone_number2" 
                            value="<?= e($data['phone_number2']) ?>" 
                            placeholder="رقم هاتف بديل" 
                            required 
                            inputmode="tel"
                            pattern="^249\d{9}$"
                            title="يرجى إدخال رقم هاتف يبدأ بـ 249 ويتكون من 12 رقمًا مثل 249123456789"
                            maxlength="12"
                        >
                        <label for="phone_number2">رقم هاتف بديل</label>
                        <div class="valid-feedback">رقم هاتف صحيح</div>
                        <div class="invalid-feedback">يجب أن يبدأ الرقم بـ 249 ويتكون من 12 رقمًا</div>
                    </div>

                    <!-- Identity -->
                    <div class="col-md-6 form-floating rtl-fix">
                        <input class="form-control" name="nationality" id="nationality" value="<?= e($data['nationality']) ?>" placeholder="الجنسية" required>
                        <label for="nationality">الجنسية</label>
                    </div>

                    <div class="col-md-6 form-floating rtl-fix">
                        <input
                            class="form-control"
                            type="text"
                            name="national_id"
                            id="national_id"
                            value="<?= e($data['national_id']) ?>"
                            placeholder="الرقم الوطني"
                            required
                            inputmode="numeric"
                            dir="ltr"
                            pattern="^[0-9_-]+$"
                            title="يُسمح بالأرقام والرمزين (-) و (_). يجب أن يحتوي على 11 رقمًا على الأقل"
                        >
                        <label for="national_id">الرقم الوطني</label>
                        <div class="invalid-feedback">
                            يُسمح بالأرقام والرمزين (-) و (_)، ويجب أن يحتوي الحقل على 11 رقمًا على الأقل.
                        </div>
                    </div>

                    <!-- Guardian Info -->
                    <div class="col-md-6 form-floating rtl-fix">
                        <input class="form-control" name="guardian_name" id="guardian_name" value="<?= e($data['guardian_name']) ?>" placeholder="اسم ولي الأمر" required>
                        <label for="guardian_name">اسم ولي الأمر</label>
                    </div>

                    <!-- Guardian Phone -->
                    <div class="col-md-6 form-floating rtl-fix">
                        <input
                            class="form-control phone-input"
                            name="guardian_phone_number"
                            id="guardian_phone_number"
                            value="<?= e($data['guardian_phone_number']) ?>"
                            placeholder="رقم هاتف ولي الأمر"
                            required
                            inputmode="tel"
                            pattern="^249\d{9}$"
                            title="يرجى إدخال رقم هاتف يبدأ بـ 249 ويتكون من 12 رقمًا مثل 249123456789"
                            maxlength="12"
                        />
                        <label for="guardian_phone_number">رقم هاتف ولي الأمر</label>
                        <div class="valid-feedback">رقم هاتف صحيح</div>
                        <div class="invalid-feedback">يجب أن يبدأ الرقم بـ 249 ويتكون من 12 رقمًا</div>
                    </div>

                    <div class="col-md-6 form-floating rtl-fix">
                        <input class="form-control" name="guardian_address" id="guardian_address" value="<?= e($data['guardian_address']) ?>" placeholder="عنوان ولي الأمر" required>
                        <label for="guardian_address">عنوان ولي الأمر</label>
                    </div>

                    <!-- Personal Info -->
                    <div class="col-md-6 form-floating rtl-fix">
                        <select class="form-select" name="student_case" id="student_case">
                            <option value="">لا يوجد</option>
                            <option value="above_average" <?= (isset($data['student_case']) && $data['student_case']==='above_average')?'selected':''; ?>>وضع فوق الوسط</option>
                            <option value="average" <?= (isset($data['student_case']) && $data['student_case']==='average')?'selected':''; ?>>وضع وسط</option>
                            <option value="below_average" <?= (isset($data['student_case']) && $data['student_case']==='below_average')?'selected':''; ?>>وضع دون الوسط</option>
                            <option value="poor" <?= (isset($data['student_case']) && $data['student_case']==='poor')?'selected':''; ?>>فقير</option>
                            <option value="father_deceased" <?= (isset($data['student_case']) && $data['student_case']==='father_deceased')?'selected':''; ?>>أبناء شهداء</option>
                            <option value="has_sibling" <?= (isset($data['student_case']) && $data['student_case']==='has_sibling')?'selected':''; ?>>لديه أخ أو أخت في الجامعة</option>
                            <option value="university_employee_child" <?= (isset($data['student_case']) && $data['student_case']==='university_employee_child')?'selected':''; ?>>أبناء عاملين بالجامعة</option>
                            <option value="other_university_employee_child" <?= (isset($data['student_case']) && $data['student_case']==='other_university_employee_child')?'selected':''; ?>>أبناء عاملين بالجامعات الاخرى</option>
                            <option value="orphan" <?= (isset($data['student_case']) && $data['student_case']==='orphan')?'selected':''; ?>>الطلاب الايتام</option>
                            <option value="pensioner_child" <?= (isset($data['student_case']) && $data['student_case']==='pensioner_child')?'selected':''; ?>>أبناء المعاشيين</option>
                            <option value="higher_education_employee_child" <?= (isset($data['student_case']) && $data['student_case']==='higher_education_employee_child')?'selected':''; ?>>أبناء العاملين بالتعليم العالي</option>
                            <option value="martyr_family" <?= (isset($data['student_case']) && $data['student_case']==='martyr_family')?'selected':''; ?>>أبناء وزوجات الشهداء</option>
                            <option value="fully_disabled" <?= (isset($data['student_case']) && $data['student_case']==='fully_disabled')?'selected':''; ?>>المعاقون اعاقة كاملة</option>
                            <option value="quran_memorizer" <?= (isset($data['student_case']) && $data['student_case']==='quran_memorizer')?'selected':''; ?>>الحفظة لكلام الله</option>
                            <option value="poor_student" <?= (isset($data['student_case']) && $data['student_case']==='poor_student')?'selected':''; ?>>الطلاب الفقراء</option>
                            <option value="disabled_parent_child" <?= (isset($data['student_case']) && $data['student_case']==='disabled_parent_child')?'selected':''; ?>>أبناء المعاقين</option>
                        </select>
                        <label for="student_case">الوضع المعيشي</label>
                    </div>

                    <div class="col-md-6 form-floating rtl-fix">
                        <input 
                            type="date" 
                            class="form-control" 
                            name="date_of_birth" 
                            id="date_of_birth" 
                            value="<?= e($data['date_of_birth'] ?: date('Y-m-d')) ?>" 
                            placeholder="تاريخ الميلاد" 
                            required
                        >
                        <label for="date_of_birth">تاريخ الميلاد</label>
                    </div>

                    <div class="col-md-6 form-floating rtl-fix">
                        <select class="form-select" name="gender" id="gender">
                            <option value="0" <?= ((int)$data['gender']===0?'selected':'') ?>>غير محدد</option>
                            <option value="1" <?= ((int)$data['gender']===1?'selected':'') ?>>ذكر</option>
                            <option value="2" <?= ((int)$data['gender']===2?'selected':'') ?>>أنثى</option>
                        </select>
                        <label for="gender">الجنس</label>
                    </div>

                    <div class="col-md-6 form-floating rtl-fix">
                        <input class="form-control" name="home_address" id="home_address" value="<?= e($data['home_address']) ?>" placeholder="عنوان السكن" required>
                        <label for="home_address">عنوان السكن</label>
                    </div>

                    <div class="col-md-6 form-floating rtl-fix">
                        <select class="form-select" name="blood_type" id="blood_type">
                            <option value="">اختر</option>
                            <?php foreach (['A+', 'A-', 'B+', 'B-', 'AB+', 'AB-', 'O+', 'O-'] as $type): ?>
                                <option value="<?= $type ?>" <?= $data['blood_type']===$type ? 'selected' : '' ?>><?= $type ?></option>
                            <?php endforeach; ?>
                        </select>
                        <label for="blood_type">فصيلة الدم</label>
                    </div>

                    <!-- Location -->
                    <div class="col-md-6 form-floating rtl-fix">
                        <select class="form-select" name="country_id" id="country_id" required data-selected-state="<?= $data['state_id'] ?? '' ?>" data-selected-locality="<?= $data['locality_id'] ?? '' ?>">
                            <option value="">اختر الدولة</option>
                            <?php
                                $countries = $mysqli1->query("SELECT id, name FROM countries ORDER BY name");
                                while ($c = $countries->fetch_assoc()):
                            ?>
                                <option value="<?= $c['id'] ?>" <?= ($data['country_id'] ?? '') == $c['id'] ? 'selected' : '' ?>><?= e($c['name']) ?></option>
                            <?php endwhile; ?>
                        </select>
                        <label for="country_id">الدولة</label>
                    </div>

                    <div class="col-md-6 form-floating rtl-fix">
                        <select class="form-select" name="state_id" id="state_id" required>
                            <option value="">اختر الولاية</option>
                            <?php
                                if (!empty($data['country_id'])) {
                                    $states = $mysqli1->query("SELECT id, name FROM states WHERE country_id = " . (int)$data['country_id'] . " ORDER BY name");
                                    while ($s = $states->fetch_assoc()):
                            ?>
                                <option value="<?= $s['id'] ?>" <?= ($data['state_id'] ?? '') == $s['id'] ? 'selected' : '' ?>><?= e($s['name']) ?></option>
                            <?php 
                                    endwhile;
                                }
                            ?>
                        </select>
                        <label for="state_id">الولاية</label>
                    </div>

                    <div class="col-md-6 form-floating rtl-fix">
                        <select class="form-select" name="locality_id" id="locality_id" required>
                            <option value="">اختر المنطقة</option>
                            <?php
                                if (!empty($data['state_id'])) {
                                    $localities = $mysqli1->query("SELECT id, name FROM localities WHERE state_id = " . (int)$data['state_id'] . " ORDER BY name");
                                    while ($l = $localities->fetch_assoc()):
                            ?>
                                <option value="<?= $l['id'] ?>" <?= ($data['locality_id'] ?? '') == $l['id'] ? 'selected' : '' ?>><?= e($l['name']) ?></option>
                            <?php 
                                    endwhile;
                                }
                            ?>
                        </select>
                        <label for="locality_id">المنطقة</label>
                    </div>

                 

                    <!-- Banks & Fees Card -->
                    <div class="col-12">
                        <div class="card card-arabic p-3">
                            <h6 class="rtl-heading mb-3" style="text-decoration:none;color:#000;">البنوك المتاحة للدفع والمصروفات الدراسية</h6>
                            
                            <!-- Fees Section -->
                            <div class="mb-4">
                                <h6 class="text-primary mb-3" style="direction: rtl; text-align: right;">
                                    <i class="fas fa-money-bill-wave me-2"></i>
                                    المصروفات الدراسية - للفصل الدراسي
                                </h6>
                                
                                <div class="fees-list" style="direction: rtl; text-align: right;">
                                    <div class="d-flex justify-content-between align-items-center py-2 border-bottom">
                                        
                                         <span class="fee-item">رسوم التسجيل - تدفع مع بداية كل فصل دراسي</span>
                                         
                                        <span class="fee-amount text-success fw-bold">250.000 SDG</span>
                                    </div>
                                    
                                    <div class="d-flex justify-content-between align-items-center py-2 border-bottom">
                                      <span class="fee-item">رسوم الخدمات الصحية والتأمين الطبي-تدفع مرة واحدة فقط</span>
                                        <span class="fee-amount text-success fw-bold">100.000 SDG</span>
                                    </div>
                                    
                                    <div class="d-flex justify-content-between align-items-center py-2 border-bottom">
                                       <span class="fee-item"><?= e($data['program_name']) ?> - المصروفات الدراسية للفصل الدراسي</span>
                                        
                                        <span class="fee-amount text-success fw-bold"><?= number_format($data['program_fees'] ?? 0, 0) ?> SDG</span>
                                    </div>
                                    
                                    <!-- Total -->
                                    <div class="d-flex justify-content-between align-items-center py-3 mt-2" style="background-color: #f8f9fa; border-radius: 8px; padding: 0 15px;">
                                        <span class="total-label fw-bold fs-5">المجموع الكلي</span>
                                        <span class="total-amount text-danger fw-bold fs-5">
                                            <?= number_format($total_fees, 0) ?> SDG
                                        </span>
                                    </div>
                                </div>
                            </div>

                            <!-- Banks Section -->
                            <div class="mt-4 p-4 text-center shadow-sm payment-methods-card">
                                <div class="row align-items-center">
                                    <div class="col-lg-2 mb-3 mb-lg-0">
                                        <i class="fas fa-credit-card fa-4x text-warning"></i>
                                    </div>
                                    <div class="col-lg-8">
                                        <h4 class="fw-bold mb-3">طرق سداد المصروفات الدراسية</h4>
                                        <div class="row">
                                            <div class="col-md-6 mb-2">
                                                <div class="p-2 bg-white bg-opacity-25 rounded">
                                                    <i class="fas fa-building me-2"></i>
                                                    <strong>السداد المباشر</strong>
                                                    <div class="mt-1">
                                                        <small> من خلال فروع بنك امدرمان الوطني و بنك النيل </small>
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="col-md-6 mb-2">
                                                <div class="p-2 bg-white bg-opacity-25 rounded">
                                                    <i class="fas fa-mobile-alt me-2"></i>
                                                    <strong>السداد الإلكتروني</strong>
                                                    <div class="mt-1">
                                                        <small> من خلال تطبيقات  بنك امدرمان الوطني و بنك النيل </small>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

               

                    <!-- Attachments -->
                    <div class="col-12">
                        <div class="card card-arabic p-3">
                            <h6 class="rtl-heading mb-3" style="text-decoration:none;color:#000;">المرفقات</h6>

                            <!-- Four hidden file inputs -->
                            <input class="visually-hidden" type="file" id="file_personal_photo" name="file_personal_photo" accept=".jpg,.jpeg,.png,.webp">
                            <input class="visually-hidden" type="file" id="file_national_id" name="file_national_id" accept=".pdf,.jpg,.jpeg,.png,.webp">
                            <input class="visually-hidden" type="file" id="file_medical_report" name="file_medical_report" accept=".pdf,.jpg,.jpeg,.png,.webp">
                            <input class="visually-hidden" type="file" id="file_discount_justification" name="file_discount_justification" accept=".pdf,.jpg,.jpeg,.png,.webp">

                            <!-- Buttons -->
                            <div class="d-flex flex-wrap gap-2">
                                <button type="button" class="btn btn-outline-success btn-sm" id="btn_personal_photo">
                                    صورة شخصية
                                </button>
                                <button type="button" class="btn btn-outline-primary btn-sm" id="btn_national_id">
                                    اثبات الشخصية (يفضل الرقم الوطني)
                                </button>
                                <button type="button" class="btn btn-outline-warning btn-sm d-none" id="btn_discount_justification">
                                    إثبات سبب التخفيض
                                </button>

                                <button type="button" class="btn btn-outline-danger btn-sm ms-auto d-none" id="btn_clear_personal">إزالة الصورة</button>
                                <button type="button" class="btn btn-outline-danger btn-sm d-none" id="btn_clear_national">إزالة الإثبات</button>
                                <button type="button" class="btn btn-outline-danger btn-sm d-none" id="btn_clear_medical">إزالة التقرير</button>
                                <button type="button" class="btn btn-outline-danger btn-sm d-none" id="btn_clear_discount">إزالة الإثبات</button>
                            </div>

                            <!-- Status / hints -->
                            <div class="mt-3">
                                <div class="hint">الصيغ المسموحة: صورة شخصية (JPG/PNG/WEBP) | اثبات شخصية (PDF/JPG/PNG/WEBP) | تقرير طبي (PDF/JPG/PNG/WEBP) | إثبات التخفيض (PDF/JPG/PNG/WEBP) — الحد الأقصى 5MB لكل ملف</div>
                                <div id="sel_personal" class="mt-2 small text-muted"></div>
                                <div id="sel_national" class="mt-1 small text-muted"></div>
                                <div id="sel_medical" class="mt-1 small text-muted"></div>
                                <div id="sel_discount" class="mt-1 small text-muted"></div>
                            </div>

                            <!-- Upload Progress -->
                            <div class="upload-progress mt-3">
                                <div class="progress-container">
                                    <div class="progress-bar" role="progressbar" style="width: 0%"></div>
                                </div>
                                
                                <div class="progress-stats">
                                    <div class="progress-text">
                                        <i class="fas fa-cloud-upload-alt upload-icon"></i>
                                        جاري رفع الملفات...
                                    </div>
                                    <div class="progress-percentage">0%</div>
                                </div>
                                
                                <div class="upload-details">
                                    <div class="upload-time">
                                        <i class="fas fa-clock"></i>
                                        <span id="upload-time">تقدير الوقت: حساب...</span>
                                    </div>
                                    <div class="upload-speed">
                                        <i class="fas fa-tachometer-alt"></i>
                                        <span id="upload-speed">سرعة: حساب...</span>
                                    </div>
                                </div>
                                
                                <div class="upload-status">
                                    <i class="fas fa-sync-alt fa-spin me-2"></i>
                                    <span id="status-text">جاري معالجة طلبك...</span>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Agreements -->
                    <div class="col-12">
                        <div class="form-check rtl-right">
                            <input class="form-check-input" type="checkbox" name="agreed_regulations" id="agreed_regulations" value="1"
                                <?= $data['agreed_regulations'] ? 'checked' : '' ?> required>
                            <label class="form-check-label" for="agreed_regulations">
                                أقر بأنني قرأت ووافقت على <a href="regulations.pdf" target="_blank">لوائح الجامعة</a>.
                            </label>
                        </div>
                    </div>

                    <div class="col-12">
                        <div class="form-check rtl-right">
                            <input class="form-check-input" type="checkbox" name="self_declare_fit" id="self_declare_fit" value="NULL"
                                <?= $data['self_declare_fit'] ? 'checked' : '' ?> required>
                            <label class="form-check-label" for="self_declare_fit">
                                أؤكد أنني لائق طبياً وفقًا لـ <a href="fitness_requirements.pdf" target="_blank">متطلبات البرنامج الصحية</a>.
                            </label>
                        </div>
                    </div>

                    <!-- Submit -->
                    <div class="col-12 text-end">
                        <?php if ($can_submit): ?>
                            <button 
                                class="btn btn-success" 
                                type="submit"
                                id="submitBtn"
                                style="width:100%; font-size:1.25rem; padding:.75rem 1rem; border-radius:.75rem;"
                            >
                                <i class="fas fa-paper-plane me-2"></i>
                                إرسال الطلب / Submit Application
                            </button>
                            <div class="mt-2 text-center text-success">
                                <i class="fas fa-check-circle me-2"></i>
                                جميع المتطلبات مكتملة - يمكنك إرسال الطلب الآن
                            </div>
                        <?php else: ?>
                            <button 
                                class="btn btn-secondary" 
                                type="button"
                                style="width:100%; font-size:1.25rem; padding:.75rem 1rem; border-radius:.75rem;"
                                disabled
                            >
                                <i class="fas fa-ban me-2"></i>
                                ❌ لا يمكن إرسال الطلب - استكمل الملف الطبي أولاً
                            </button>
                            <div class="mt-2 text-center text-danger">
                                <i class="fas fa-exclamation-circle me-2"></i>
                                يجب استكمال الملف الطبي قبل إرسال الطلب
                                <div class="mt-1 small">
                                    <span class="badge <?= $medical_status === 'completed' ? 'bg-success' : 'bg-danger' ?>">
                                        الملف الطبي: <?= $medical_status === 'completed' ? 'مكتمل' : 'غير مكتمل' ?>
                                    </span>
                                </div>
                            </div>
                        <?php endif; ?>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- JavaScript -->
    <!-- Your existing PHP and HTML code remains the same until the JavaScript section -->

    <!-- JavaScript -->
    <script>
    document.addEventListener('DOMContentLoaded', function() {
        console.log('DOM loaded - initializing scripts...');
        
        // Disable form if medical not completed
        const form = document.getElementById('studentForm');
        const canEditProfile = <?= $can_edit_profile ? 'true' : 'false' ?>;
        
        if (!canEditProfile) {
            // Disable all form inputs
            const allInputs = form.querySelectorAll('input, select, textarea, button');
            allInputs.forEach(input => {
                if (input.type !== 'hidden' && input.id !== 'submitBtn') {
                    input.disabled = true;
                }
            });
            
            // Prevent form submission
            form.addEventListener('submit', function(e) {
                e.preventDefault();
                alert('يجب استكمال النموذج الطبي أولاً قبل إرسال الطلب');
                return false;
            });
            
            // Add click prevention
            form.addEventListener('click', function(e) {
                if (!e.target.closest('.medical-action-buttons')) {
                    e.preventDefault();
                    e.stopPropagation();
                    
                    // Show message
                    const alertDiv = document.createElement('div');
                    alertDiv.className = 'alert alert-warning alert-dismissible fade show mt-3';
                    alertDiv.innerHTML = `
                        <i class="fas fa-info-circle me-2"></i>
                        يجب استكمال النموذج الطبي أولاً لتعديل البيانات
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    `;
                    
                    const existingAlert = form.querySelector('.interaction-alert');
                    if (existingAlert) {
                        existingAlert.remove();
                    }
                    
                    alertDiv.classList.add('interaction-alert');
                    form.insertBefore(alertDiv, form.firstChild);
                    
                    setTimeout(() => {
                        if (alertDiv.parentNode) {
                            alertDiv.remove();
                        }
                    }, 3000);
                }
            });
        }

        // Location Dropdowns
        const countrySelect = document.getElementById('country_id');
        const stateSelect = document.getElementById('state_id');
        const localitySelect = document.getElementById('locality_id');

        if (countrySelect && stateSelect && localitySelect) {
            const selectedStateId = countrySelect.dataset.selectedState || '';
            const selectedLocalityId = countrySelect.dataset.selectedLocality || '';
            
            // Load initial states if country is already selected
            if (countrySelect.value) {
                loadStates(countrySelect.value, selectedStateId);
            }

            countrySelect.addEventListener('change', function() {
                const countryId = this.value;
                stateSelect.innerHTML = '<option value="">اختر الولاية</option>';
                localitySelect.innerHTML = '<option value="">اختر المنطقة</option>';
                
                if (countryId) {
                    loadStates(countryId);
                }
            });

            stateSelect.addEventListener('change', function() {
                const stateId = this.value;
                localitySelect.innerHTML = '<option value="">اختر المنطقة</option>';
                
                if (stateId) {
                    loadLocalities(stateId);
                }
            });

            function loadStates(countryId, selectedStateId = '') {
                stateSelect.disabled = true;
                stateSelect.innerHTML = '<option value="">جاري التحميل...</option>';
                
                fetch(`ajax_get_states.php?country_id=${countryId}`)
                    .then(response => response.json())
                    .then(states => {
                        stateSelect.innerHTML = '<option value="">اختر الولاية</option>';
                        
                        if (states.length === 0) {
                            stateSelect.innerHTML = '<option value="">لا توجد ولايات</option>';
                            return;
                        }
                        
                        let foundSelected = false;
                        states.forEach(state => {
                            const option = document.createElement('option');
                            option.value = state.id;
                            option.textContent = state.name;
                            if (selectedStateId && state.id == selectedStateId) {
                                option.selected = true;
                                foundSelected = true;
                                loadLocalities(selectedStateId, selectedLocalityId);
                            }
                            stateSelect.appendChild(option);
                        });
                        
                        if (!foundSelected && states.length > 0) {
                            stateSelect.value = states[0].id;
                            loadLocalities(states[0].id);
                        }
                        
                        stateSelect.disabled = false;
                    })
                    .catch(error => {
                        console.error('Error loading states:', error);
                        stateSelect.innerHTML = '<option value="">خطأ في التحميل</option>';
                        stateSelect.disabled = false;
                    });
            }

            function loadLocalities(stateId, selectedLocalityId = '') {
                localitySelect.disabled = true;
                localitySelect.innerHTML = '<option value="">جاري التحميل...</option>';
                
                fetch(`ajax_get_localities.php?state_id=${stateId}`)
                    .then(response => response.json())
                    .then(localities => {
                        localitySelect.innerHTML = '<option value="">اختر المنطقة</option>';
                        
                        if (localities.length === 0) {
                            localitySelect.innerHTML = '<option value="">لا توجد مناطق</option>';
                            return;
                        }
                        
                        let foundSelected = false;
                        localities.forEach(locality => {
                            const option = document.createElement('option');
                            option.value = locality.id;
                            option.textContent = locality.name;
                            if (selectedLocalityId && locality.id == selectedLocalityId) {
                                option.selected = true;
                                foundSelected = true;
                            }
                            localitySelect.appendChild(option);
                        });
                        
                        if (!foundSelected && localities.length > 0) {
                            localitySelect.value = localities[0].id;
                        }
                        
                        localitySelect.disabled = false;
                    })
                    .catch(error => {
                        console.error('Error loading localities:', error);
                        localitySelect.innerHTML = '<option value="">خطأ في التحميل</option>';
                        localitySelect.disabled = false;
                    });
            }
        }

        // Phone Validation Functions
        function validatePhoneNumber(phone) {
            const phoneRegex = /^249\d{9}$/;
            return phoneRegex.test(phone);
        }

        function formatPhoneInput(input) {
            let value = input.value.replace(/\D/g, '');
            
            // Auto-add 249 if not present
            if (value.length > 0 && !value.startsWith('249')) {
                if (value.length <= 9) {
                    value = '249' + value;
                }
            }
            
            // Limit to 12 digits
            if (value.length > 12) {
                value = value.substring(0, 12);
            }
            
            input.value = value;
            return value;
        }

        function validatePhoneInput(input) {
            const value = formatPhoneInput(input);
            const isValid = validatePhoneNumber(value);
            
            // Clear previous validation states
            input.classList.remove('is-valid', 'is-invalid');
            
            if (value.length === 0) {
                // No validation for empty field
            } else if (isValid) {
                input.classList.add('is-valid');
            } else {
                input.classList.add('is-invalid');
            }
            
            return isValid;
        }

        // Initialize phone validation for all phone inputs
        const phoneInputs = document.querySelectorAll('.phone-input');
        phoneInputs.forEach(input => {
            // Validate on input (typing)
            input.addEventListener('input', function() {
                validatePhoneInput(this);
            });
            
            // Validate on blur (when leaving field)
            input.addEventListener('blur', function() {
                validatePhoneInput(this);
            });
            
            // Validate initial values
            if (input.value) {
                validatePhoneInput(input);
            }
        });

        // File Uploads
        const fileButtons = {
            'btn_personal_photo': 'file_personal_photo',
            'btn_national_id': 'file_national_id', 
            'btn_medical_report': 'file_medical_report',
            'btn_discount_justification': 'file_discount_justification'
        };

        const fileDisplays = {
            'file_personal_photo': 'sel_personal',
            'file_national_id': 'sel_national',
            'file_medical_report': 'sel_medical', 
            'file_discount_justification': 'sel_discount'
        };

        const clearButtons = {
            'btn_clear_personal': 'file_personal_photo',
            'btn_clear_national': 'file_national_id',
            'btn_clear_medical': 'file_medical_report',
            'btn_clear_discount': 'file_discount_justification'
        };

        // Initialize button click handlers
        Object.keys(fileButtons).forEach(buttonId => {
            const button = document.getElementById(buttonId);
            const fileInputId = fileButtons[buttonId];
            
            if (button) {
                button.addEventListener('click', function() {
                    document.getElementById(fileInputId).click();
                });
            }
        });

        // Initialize file input change handlers
        Object.keys(fileDisplays).forEach(fileInputId => {
            const fileInput = document.getElementById(fileInputId);
            const displayElementId = fileDisplays[fileInputId];
            
            if (fileInput) {
                fileInput.addEventListener('change', function(e) {
                    const file = e.target.files[0];
                    const displayElement = document.getElementById(displayElementId);
                    
                    if (file) {
                        displayElement.textContent = `تم اختيار: ${file.name} (${(file.size / 1024 / 1024).toFixed(2)} MB)`;
                        displayElement.className = 'mt-1 small text-success';
                        
                        // Show clear button
                        const clearButtonId = Object.keys(clearButtons).find(key => clearButtons[key] === fileInputId);
                        if (clearButtonId) {
                            const clearButton = document.getElementById(clearButtonId);
                            if (clearButton) {
                                clearButton.classList.remove('d-none');
                            }
                        }
                    } else {
                        displayElement.textContent = '';
                    }
                });
            }
        });

        // Initialize clear button handlers
        Object.keys(clearButtons).forEach(clearButtonId => {
            const clearButton = document.getElementById(clearButtonId);
            const fileInputId = clearButtons[clearButtonId];
            const displayElementId = fileDisplays[fileInputId];
            
            if (clearButton) {
                clearButton.addEventListener('click', function() {
                    const fileInput = document.getElementById(fileInputId);
                    const displayElement = document.getElementById(displayElementId);
                    
                    if (fileInput) {
                        fileInput.value = '';
                    }
                    if (displayElement) {
                        displayElement.textContent = '';
                        displayElement.className = 'mt-1 small text-muted';
                    }
                    
                    // Hide clear button
                    clearButton.classList.add('d-none');
                });
            }
        });

        // Form Validation on Submit
        if (form) {
            form.addEventListener('submit', function(e) {
                const medicalStatus = form.dataset.medicalStatus || '';
                
                // Check if all required fields are filled
                const requiredFields = form.querySelectorAll('[required]');
                let allFieldsFilled = true;
                
                requiredFields.forEach(field => {
                    if (!field.value.trim()) {
                        allFieldsFilled = false;
                        field.classList.add('is-invalid');
                    } else {
                        field.classList.remove('is-invalid');
                    }
                });
                
                // Check phone validation
                const phoneInputs = form.querySelectorAll('.phone-input');
                let allPhonesValid = true;
                
                phoneInputs.forEach(input => {
                    const value = input.value.replace(/\D/g, '');
                    if (!validatePhoneNumber(value)) {
                        allPhonesValid = false;
                        input.classList.add('is-invalid');
                    }
                });
                
                if (medicalStatus !== 'completed' || !allFieldsFilled || !allPhonesValid) {
                    e.preventDefault();
                    
                    let errorMessage = '';
                    
                    if (medicalStatus !== 'completed') {
                        errorMessage = `
                            <h6><i class="fas fa-exclamation-triangle me-2"></i>لا يمكن إرسال الطلب</h6>
                            <p class="mb-0">يجب استكمال الملف الطبي قبل إرسال الطلب. الرجاء الضغط على زر "تعبئة النموذج الطبي".</p>
                        `;
                    } else if (!allFieldsFilled) {
                        errorMessage = `
                            <h6><i class="fas fa-exclamation-triangle me-2"></i>لا يمكن إرسال الطلب</h6>
                            <p class="mb-0">يرجى ملء جميع الحقول الإلزامية المميزة بالنجمة (*).</p>
                        `;
                    } else if (!allPhonesValid) {
                        errorMessage = `
                            <h6><i class="fas fa-exclamation-triangle me-2"></i>لا يمكن إرسال الطلب</h6>
                            <p class="mb-0">يرجى تصحيح أرقام الهواتف لتكون بصيغة 249123456789.</p>
                        `;
                    }
                    
                    const alertDiv = document.createElement('div');
                    alertDiv.className = 'alert alert-danger mt-3';
                    alertDiv.innerHTML = errorMessage;
                    
                    const existingAlert = document.querySelector('.submission-alert');
                    if (existingAlert) {
                        existingAlert.remove();
                    }
                    
                    alertDiv.classList.add('submission-alert');
                    form.parentNode.insertBefore(alertDiv, form);
                    
                    alertDiv.scrollIntoView({ behavior: 'smooth' });
                }
            });
        }
    });
    </script>
</body>
</html>