<?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'];

// Language handling
$lang = $_GET['lang'] ?? 'ar';
$isArabic = ($lang === 'ar');

// Get student data
$stmt = $mysqli1->prepare("
    SELECT s.*, c.name AS college_name, p.name AS program_name 
    FROM students s 
    JOIN colleges c ON s.college_id = c.id 
    JOIN programs p ON s.program_id = p.id 
    WHERE s.student_id = ?
");
$stmt->bind_param("s", $student_id);
$stmt->execute();
$student_data = $stmt->get_result()->fetch_assoc();

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    error_log("Medical form POST request received");
    error_log("POST data: " . print_r($_POST, true));
    
    // Validate CSRF token
    if (!isset($_POST['csrf']) || $_POST['csrf'] !== csrf_token()) {
        $error_msg = 'Invalid CSRF token';
        error_log($error_msg);
        
        if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest') {
            header('Content-Type: application/json');
            echo json_encode([
                'success' => false,
                'message' => $error_msg
            ]);
            exit;
        } else {
            die($error_msg);
        }
    }
    
    try {
        $medical_data = [
            'student_id' => $student_id,
            'medical_date' => date('Y-m-d'),
            
            // Medical conditions
            'has_disability' => $mysqli1->real_escape_string($_POST['has_disability'] ?? 'no'),
            'has_chronic_diseases' => $mysqli1->real_escape_string($_POST['has_chronic_diseases'] ?? 'no'),
            'chronic_diseases_details' => $mysqli1->real_escape_string($_POST['chronic_diseases_details'] ?? ''),
            'has_psychological_diseases' => $mysqli1->real_escape_string($_POST['has_psychological_diseases'] ?? 'no'),
            'has_vision_problems' => $mysqli1->real_escape_string($_POST['has_vision_problems'] ?? 'no'),
            'has_hearing_problems' => $mysqli1->real_escape_string($_POST['has_hearing_problems'] ?? 'no'),
            'covid_vaccinated' => $mysqli1->real_escape_string($_POST['covid_vaccinated'] ?? 'no'),
            'has_diabetes' => $mysqli1->real_escape_string($_POST['has_diabetes'] ?? 'no'),
            'has_blood_pressure' => $mysqli1->real_escape_string($_POST['has_blood_pressure'] ?? 'no'),
            'has_family_diseases' => $mysqli1->real_escape_string($_POST['has_family_diseases'] ?? 'no'),
            'family_diseases_details' => $mysqli1->real_escape_string($_POST['family_diseases_details'] ?? ''),
            
            // Additional notes
            'additional_notes' => $mysqli1->real_escape_string($_POST['additional_notes'] ?? '')
        ];
        
        error_log("Medical data prepared: " . print_r($medical_data, true));
        
        // Check if record exists
        $existing_record = $mysqli1->query("SELECT id FROM student_medical_records WHERE student_id = '$student_id'")->fetch_assoc();
        
        if ($existing_record) {
            // Update existing record
            $update_fields = [];
            foreach ($medical_data as $key => $value) {
                if ($key !== 'student_id') {
                    $update_fields[] = "`$key` = '$value'";
                }
            }
            $update_query = "UPDATE student_medical_records SET " . implode(', ', $update_fields) . " WHERE student_id = '$student_id'";
            error_log("Update query: " . $update_query);
            $result = $mysqli1->query($update_query);
        } else {
            // Insert new record
            $columns = '`' . implode('`, `', array_keys($medical_data)) . '`';
            $values = "'" . implode("', '", array_values($medical_data)) . "'";
            $insert_query = "INSERT INTO student_medical_records ($columns) VALUES ($values)";
            error_log("Insert query: " . $insert_query);
            $result = $mysqli1->query($insert_query);
        }
        
        if ($result) {
            // Update student medical status
            $update_student = "UPDATE students 
                              SET medical_status = 'completed', 
                                  last_medical_exam = CURDATE(),
                                  medically_fit = null
                              WHERE student_id = '$student_id'";
            $mysqli1->query($update_student);
            
            error_log("Medical data saved successfully for student: $student_id");
            
            // Return JSON response for AJAX (modal submission)
            if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest') {
                header('Content-Type: application/json');
                echo json_encode([
                    'success' => true,
                    'message' => $isArabic ? 'تم حفظ البيانات الطبية بنجاح' : 'Medical data saved successfully'
                ]);
                exit;
            } else {
                // Regular form submission (fallback)
                $_SESSION['success_message'] = $isArabic ? 'تم حفظ البيانات الطبية بنجاح' : 'Medical data saved successfully';
                header('Location: student_profile4.php');
                exit;
            }
        } else {
            $error_msg = $isArabic ? 'خطأ في حفظ البيانات: ' . $mysqli1->error : 'Error saving data: ' . $mysqli1->error;
            error_log($error_msg);
            throw new Exception($error_msg);
        }
    } catch (Exception $e) {
        $error_message = $e->getMessage();
        error_log("Exception: " . $error_message);
        
        // Return JSON response for AJAX (modal submission)
        if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest') {
            header('Content-Type: application/json');
            echo json_encode([
                'success' => false,
                'message' => $error_message
            ]);
            exit;
        }
        // For regular form submission, the $error_message will be displayed normally
    }
}

// Get existing medical record safely
$existing_record = null;
$medical_result = $mysqli1->query("SELECT * FROM student_medical_records WHERE student_id = '$student_id' ORDER BY created_at DESC LIMIT 1");
if ($medical_result) {
    $existing_record = $medical_result->fetch_assoc();
}

// Only include header and show HTML if it's a regular page request (not AJAX)
if (!isset($_SERVER['HTTP_X_REQUESTED_WITH']) || strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) !== 'xmlhttprequest') {
    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><?= $isArabic ? 'النموذج الطبي' : 'Medical Form' ?> - University of Gezira</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style>
        :root {
            --uofg-primary: #1e3a8a;
            --uofg-success: #198754;
            --uofg-danger: #dc3545;
            --uofg-warning: #ffc107;
            --uofg-light: #f8f9fa;
            --uofg-border: #dee2e6;
        }
        
        * {
            font-family: 'Cairo', sans-serif;
        }
        
        body {
            background-color: #f5f5f5;
            min-height: 100vh;
            padding: 20px 0;
        }
        
        .medical-form-container {
            background: white;
            border-radius: 10px;
            box-shadow: 0 0 20px rgba(0,0,0,0.1);
            overflow: hidden;
            margin: 0 auto;
            max-width: 900px;
            border: 1px solid var(--uofg-border);
        }
 
        .form-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);
        }
        
        .form-header h1 {
            margin: 0;
            font-size: 2rem;
            font-weight: 700;
            margin-bottom: 10px;
        }
        
        .form-header p {
            margin: 0;
            opacity: 0.9;
            font-size: 1.1rem;
        }
        
        .language-switcher {
            position: absolute;
            left: 20px;
            top: 20px;
        }
        
        .student-info {
            background: var(--uofg-light);
            border: 1px solid var(--uofg-border);
            border-radius: 8px;
            padding: 20px;
            margin: 20px;
        }
        
        .student-info .row {
            margin-bottom: -10px;
        }
        
        .student-info .col-md-6 {
            margin-bottom: 10px;
        }
        
        .medical-question {
            background: white;
            border: 1px solid var(--uofg-border);
            border-radius: 8px;
            padding: 25px;
            margin: 15px 20px;
            transition: all 0.2s ease;
        }
        
        .medical-question:hover {
            border-color: var(--uofg-primary);
            box-shadow: 0 2px 8px rgba(30, 58, 138, 0.1);
        }
        
        .question-text {
            margin-bottom: 20px;
        }
        
        .question-number {
            background: var(--uofg-primary);
            color: white;
            width: 30px;
            height: 30px;
            border-radius: 50%;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            font-weight: 600;
            margin-left: 10px;
        }
        
        .question-arabic {
            font-size: 1.2rem;
            font-weight: 600;
            color: #2c3e50;
            margin-bottom: 8px;
            line-height: 1.5;
        }
        
        .question-english {
            font-size: 1rem;
            font-weight: 500;
            color: #6c757d;
            line-height: 1.4;
            font-style: italic;
        }
        
        .answer-options {
            display: flex;
            justify-content: center;
            gap: 20px;
            align-items: center;
            flex-wrap: wrap;
        }
        
        .option-label {
            display: flex;
            align-items: center;
            gap: 10px;
            cursor: pointer;
            padding: 12px 25px;
            border-radius: 6px;
            transition: all 0.2s ease;
            border: 2px solid #ced4da;
            background: white;
            min-width: 120px;
            justify-content: center;
            font-weight: 600;
            font-size: 1rem;
        }
        
        .option-label:hover {
            transform: translateY(-1px);
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }
        
        .option-label.yes-option:hover {
            border-color: var(--uofg-success);
            background: rgba(25, 135, 84, 0.05);
        }
        
        .option-label.no-option:hover {
            border-color: var(--uofg-danger);
            background: rgba(220, 53, 69, 0.05);
        }
        
        .option-label.selected.yes-option {
            background: var(--uofg-success);
            color: white;
            border-color: var(--uofg-success);
        }
        
        .option-label.selected.no-option {
            background: var(--uofg-danger);
            color: white;
            border-color: var(--uofg-danger);
        }
        
        .option-input {
            display: none;
        }
        
        .details-input {
            margin-top: 20px;
            display: none;
        }
        
        .details-input.show {
            display: block;
            animation: fadeIn 0.3s ease;
        }
        
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(-5px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        .form-actions {
            background: var(--uofg-light);
            padding: 25px;
            border-top: 1px solid var(--uofg-border);
        }
        
        .alert {
            border-radius: 8px;
            margin: 20px;
            border: 1px solid transparent;
        }
        
        .progress-container {
            padding: 0 20px 20px 20px;
        }
        
        .progress {
            height: 12px;
            background-color: #e9ecef;
            border-radius: 6px;
            overflow: hidden;
        }
        
        .progress-bar {
            background: linear-gradient(90deg, var(--uofg-success), var(--uofg-primary)) !important;
            transition: width 0.3s ease;
            border-radius: 6px;
        }
        
        .required-star {
            color: var(--uofg-danger);
            margin-left: 5px;
        }
        
        .form-control {
            border-radius: 6px;
            border: 1px solid var(--uofg-border);
            padding: 10px 15px;
            font-family: 'Cairo', sans-serif;
        }
        
        .form-control:focus {
            border-color: var(--uofg-primary);
            box-shadow: 0 0 0 0.2rem rgba(30, 58, 138, 0.25);
        }
        
        .reset-section {
            background: var(--uofg-light);
            border: 1px solid var(--uofg-border);
            border-radius: 8px;
            padding: 20px;
            margin: 20px;
            text-align: center;
        }
        
        @media (max-width: 768px) {
            .medical-form-container {
                margin: 10px;
            }
            
            .form-header {
                padding: 20px;
            }
            
            .form-header h1 {
                font-size: 1.5rem;
            }
            
            .medical-question {
                padding: 20px 15px;
                margin: 10px 15px;
            }
            
            .answer-options {
                gap: 10px;
            }
            
            .option-label {
                padding: 10px 20px;
                min-width: 100px;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="medical-form-container">
 

            <!-- Student Information -->
            <div class="student-info">
                <div class="row">
                    <div class="col-md-6">
                        <strong><?= $isArabic ? 'الاسم:' : 'Name:' ?></strong> <?= e($student_data['student_name']) ?>
                    </div>
                    <div class="col-md-6">
                        <strong><?= $isArabic ? 'الرقم الجامعي:' : 'Student ID:' ?></strong> <?= e($student_data['student_id']) ?>
                    </div>
                    <div class="col-md-6">
                        <strong><?= $isArabic ? 'الكليّة:' : 'College:' ?></strong> <?= e($student_data['college_name']) ?>
                    </div>
                    <div class="col-md-6">
                        <strong><?= $isArabic ? 'البرنامج:' : 'Program:' ?></strong> <?= e($student_data['program_name']) ?>
                    </div>
                </div>
            </div>

            <!-- Success/Error Messages -->
            <?php if (isset($error_message)): ?>
                <div class="alert alert-danger">
                    <i class="fas fa-exclamation-triangle"></i> <?= $error_message ?>
                </div>
            <?php endif; ?>

            <!-- Medical Form -->
            <form method="post" id="medicalForm">
                <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">

                <!-- Progress Bar -->
                <div class="progress-container">
                    <div class="d-flex justify-content-between align-items-center mb-2">
                        <span class="text-muted"><?= $isArabic ? 'تقدم تعبئة النموذج:' : 'Form Completion Progress:' ?></span>
                        <span class="text-muted" id="progressText">0% <?= $isArabic ? 'مكتمل' : 'Complete' ?></span>
                    </div>
                    <div class="progress">
                        <div class="progress-bar" id="progressBar" role="progressbar" style="width: 0%"></div>
                    </div>
                </div>

                <?php
                // Define questions in both languages
                $questions = [
                    'has_disability' => [
                        'ar' => 'هل تعاني من إعاقة حركية؟',
                        'en' => 'Do you have a physical disability?'
                    ],
                    'has_chronic_diseases' => [
                        'ar' => 'هل تعاني من أمراض مزمنة؟',
                        'en' => 'Do you have chronic diseases?'
                    ],
                    'has_psychological_diseases' => [
                        'ar' => 'هل تعاني من أمراض نفسية؟',
                        'en' => 'Do you have psychological diseases?'
                    ],
                    'has_vision_problems' => [
                        'ar' => 'هل تعاني من ضعف أو انعدام الرؤية؟',
                        'en' => 'Do you have vision impairment or blindness?'
                    ],
                    'has_hearing_problems' => [
                        'ar' => 'هل تعاني من ضعف أو انعدام السمع؟',
                        'en' => 'Do you have hearing impairment or deafness?'
                    ],
                    'covid_vaccinated' => [
                        'ar' => 'هل تم تطعيمك بجرعات كوفيد-19؟',
                        'en' => 'Have you been vaccinated with COVID-19 doses?'
                    ],
                    'has_diabetes' => [
                        'ar' => 'هل لديك سكري؟',
                        'en' => 'Do you have diabetes?'
                    ],
                    'has_blood_pressure' => [
                        'ar' => 'هل لديك ضغط؟',
                        'en' => 'Do you have blood pressure?'
                    ],
                    'has_family_diseases' => [
                        'ar' => 'هل توجد أمراض وراثية في العائلة؟',
                        'en' => 'Are there genetic diseases in the family?'
                    ]
                ];
                
                $question_number = 1;
                foreach ($questions as $field => $text):
                ?>
                <div class="medical-question required-question">
                    <div class="question-text">
                        <div class="question-arabic">
                            <span class="question-number"><?= $question_number ?></span>
                            <span class="required-star">*</span><?= $text['ar'] ?>
                        </div>
                        <div class="question-english">
                            <?= $text['en'] ?>
                        </div>
                    </div>
                    <div class="answer-options">
                        <label class="option-label no-option" onclick="selectOption(this, '<?= $field ?>', 'no')">
                            <input type="radio" name="<?= $field ?>" value="no" class="option-input" 
                                   <?= ($existing_record[$field] ?? '') === 'no' ? 'checked' : '' ?> required>
                            <i class="fas fa-times"></i>
                            <span><?= $isArabic ? 'لا' : 'No' ?></span>
                        </label>
                        <label class="option-label yes-option" onclick="selectOption(this, '<?= $field ?>', 'yes')">
                            <input type="radio" name="<?= $field ?>" value="yes" class="option-input"
                                   <?= ($existing_record[$field] ?? '') === 'yes' ? 'checked' : '' ?> required>
                            <i class="fas fa-check"></i>
                            <span><?= $isArabic ? 'نعم' : 'Yes' ?></span>
                        </label>
                    </div>
                    
                    <!-- Details fields for specific questions -->
                    <?php if ($field === 'has_chronic_diseases'): ?>
                    <div class="details-input <?= ($existing_record[$field] ?? '') === 'yes' ? 'show' : '' ?>" id="chronicDetails">
                        <textarea name="chronic_diseases_details" class="form-control" rows="3" 
                                  placeholder="<?= $isArabic ? 'يرجى ذكر الأمراض المزمنة التي تعاني منها...' : 'Please specify the chronic diseases you have...' ?>"><?= e($existing_record['chronic_diseases_details'] ?? '') ?></textarea>
                    </div>
                    <?php endif; ?>
                    
                    <?php if ($field === 'has_family_diseases'): ?>
                    <div class="details-input <?= ($existing_record[$field] ?? '') === 'yes' ? 'show' : '' ?>" id="familyDiseasesDetails">
                        <textarea name="family_diseases_details" class="form-control" rows="3" 
                                  placeholder="<?= $isArabic ? 'يرجى ذكر الأمراض الوراثية في العائلة...' : 'Please specify the genetic diseases in the family...' ?>"><?= e($existing_record['family_diseases_details'] ?? '') ?></textarea>
                    </div>
                    <?php endif; ?>
                </div>
                <?php 
                $question_number++;
                endforeach; 
                ?>

                <!-- Additional Notes (Optional - doesn't affect progress) -->
                <div class="medical-question optional-question">
                    <div class="question-text">
                        <div class="question-arabic">
                            <span class="question-number">١٠</span>
                            ملاحظات إضافية (اختياري)
                        </div>
                        <div class="question-english">
                            Additional notes (optional)
                        </div>
                    </div>
                    <textarea name="additional_notes" class="form-control" rows="4" 
                              placeholder="<?= $isArabic ? 'أي معلومات طبية إضافية تود إضافتها...' : 'Any additional medical information you would like to add...' ?>"><?= e($existing_record['additional_notes'] ?? '') ?></textarea>
                </div>

                <!-- Reset Section -->
                <div class="reset-section">
                    <h5 class="mb-3"><?= $isArabic ? 'إعادة تعيين النموذج' : 'Reset Form' ?></h5>
                    <p class="text-muted mb-3"><?= $isArabic ? 'يمكنك إعادة تعيين جميع الإجابات والبدء من جديد' : 'You can reset all answers and start over' ?></p>
                    <button type="button" class="btn btn-warning" onclick="resetForm()">
                        <i class="fas fa-redo"></i> <?= $isArabic ? 'إعادة تعيين النموذج' : 'Reset Form' ?>
                    </button>
                </div>

                <!-- Form Actions -->
                <div class="form-actions">
                    <div class="row justify-content-center">
                        <div class="col-auto">
                            <a href="student_profile4.php" class="btn btn-secondary btn-lg">
                                <i class="fas fa-arrow-right"></i> <?= $isArabic ? 'العودة للصفحة الشخصية' : 'Back to Profile' ?>
                            </a>
                        </div>
                        <div class="col-auto">
                            <button type="submit" class="btn btn-success btn-lg">
                                <i class="fas fa-save"></i> <?= $isArabic ? 'حفظ البيانات الطبية' : 'Save Medical Data' ?>
                            </button>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <script>
    function selectOption(element, fieldName, value) {
        // Remove selected class from all options in this question
        const question = element.closest('.medical-question');
        question.querySelectorAll('.option-label').forEach(label => {
            label.classList.remove('selected');
        });
        
        // Add selected class to clicked option
        element.classList.add('selected');
        
        // Check the radio input
        const radioInput = element.querySelector('input[type="radio"]');
        radioInput.checked = true;
        
        // Show/hide details fields based on selection
        if (fieldName === 'has_chronic_diseases' && value === 'yes') {
            document.getElementById('chronicDetails').classList.add('show');
        } else if (fieldName === 'has_chronic_diseases' && value === 'no') {
            document.getElementById('chronicDetails').classList.remove('show');
        }
        
        if (fieldName === 'has_family_diseases' && value === 'yes') {
            document.getElementById('familyDiseasesDetails').classList.add('show');
        } else if (fieldName === 'has_family_diseases' && value === 'no') {
            document.getElementById('familyDiseasesDetails').classList.remove('show');
        }
        
        // Update progress
        updateProgress();
    }

    function updateProgress() {
        // Only count required questions (first 9 questions)
        const requiredQuestions = document.querySelectorAll('.medical-question.required-question');
        let answeredCount = 0;
        
        requiredQuestions.forEach(question => {
            const checkedInput = question.querySelector('input[type="radio"]:checked');
            if (checkedInput) {
                answeredCount++;
            }
        });
        
        const progress = Math.round((answeredCount / requiredQuestions.length) * 100);
        const progressBar = document.getElementById('progressBar');
        const progressText = document.getElementById('progressText');
        
        if (progressBar) {
            progressBar.style.width = progress + '%';
            progressBar.setAttribute('aria-valuenow', progress);
            
            // Update progress bar color based on completion
            if (progress === 100) {
                progressBar.style.background = 'linear-gradient(90deg, var(--uofg-success), #28a745)';
            } else {
                progressBar.style.background = 'linear-gradient(90deg, var(--uofg-success), var(--uofg-primary))';
            }
        }
        
        if (progressText) {
            progressText.textContent = progress + '% <?= $isArabic ? "مكتمل" : "Complete" ?>';
        }
    }

    function resetForm() {
        if (confirm('<?= $isArabic ? "هل أنت متأكد من إعادة تعيين النموذج؟ سيتم حذف جميع الإجابات." : "Are you sure you want to reset the form? All answers will be cleared." ?>')) {
            // Clear all radio buttons
            document.querySelectorAll('.option-input').forEach(input => {
                input.checked = false;
            });
            
            // Remove selected classes
            document.querySelectorAll('.option-label').forEach(label => {
                label.classList.remove('selected');
            });
            
            // Clear textareas
            document.querySelectorAll('textarea').forEach(textarea => {
                textarea.value = '';
            });
            
            // Hide details sections
            document.querySelectorAll('.details-input').forEach(section => {
                section.classList.remove('show');
            });
            
            // Reset progress
            updateProgress();
            
            // Show success message
            alert('<?= $isArabic ? "تم إعادة تعيين النموذج بنجاح" : "Form has been reset successfully" ?>');
        }
    }

    function changeLanguage(lang) {
        window.location.href = 'student_medical_form.php?lang=' + lang;
    }

    // Initialize form
    document.addEventListener('DOMContentLoaded', function() {
        // Set initial selected states
        document.querySelectorAll('.option-input:checked').forEach(input => {
            input.closest('.option-label').classList.add('selected');
        });
        
        // Update progress on load
        updateProgress();
        
        // Add change event listeners to all radio inputs
        document.querySelectorAll('.option-input').forEach(input => {
            input.addEventListener('change', updateProgress);
        });

        // Form submission handling
        document.getElementById('medicalForm').addEventListener('submit', function(e) {
            const requiredQuestions = document.querySelectorAll('.medical-question.required-question');
            let allAnswered = true;
            
            requiredQuestions.forEach(question => {
                const checkedInput = question.querySelector('input[type="radio"]:checked');
                if (!checkedInput) {
                    allAnswered = false;
                    // Highlight unanswered questions
                    question.style.borderColor = 'var(--uofg-danger)';
                    question.style.backgroundColor = 'rgba(220, 53, 69, 0.05)';
                } else {
                    // Reset styling for answered questions
                    question.style.borderColor = '';
                    question.style.backgroundColor = '';
                }
            });
            
            if (!allAnswered) {
                e.preventDefault();
                alert('<?= $isArabic ? "يرجى الإجابة على جميع الأسئلة الإلزامية قبل الحفظ" : "Please answer all required questions before saving" ?>');
                
                // Scroll to first unanswered question
                const firstUnanswered = document.querySelector('.medical-question.required-question input[type="radio"]:not(:checked)');
                if (firstUnanswered) {
                    firstUnanswered.closest('.medical-question').scrollIntoView({ 
                        behavior: 'smooth', 
                        block: 'center' 
                    });
                }
                return false;
            }
            
            // Show loading state
            const submitBtn = this.querySelector('button[type="submit"]');
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> <?= $isArabic ? "جاري الحفظ..." : "Saving..." ?>';
        });
    });
    </script>
</body>
</html>

<?php } // End of regular page request condition ?>