<?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') {
    // Validate CSRF token
    if (!isset($_POST['csrf']) || $_POST['csrf'] !== csrf_token()) {
        die("Invalid CSRF token");
    }
    
    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'] ?? '')
        ];
        
        // 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'";
            $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)";
            $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 = 1
                              WHERE student_id = '$student_id'";
            $mysqli1->query($update_student);
            
            $_SESSION['success_message'] = $isArabic ? 'تم حفظ البيانات الطبية بنجاح' : 'Medical data saved successfully';
            header('Location: student_profile.php');
            exit;
        } else {
            throw new Exception($isArabic ? 'خطأ في حفظ البيانات: ' : 'Error saving data: ' . $mysqli1->error);
        }
    } catch (Exception $e) {
        $error_message = $e->getMessage();
    }
}

// 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();
}

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' ?> - National University - Sudan</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-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 {
            height: 8px;
            margin: 0 20px 20px 20px;
        }
        
        .progress-bar {
            background: linear-gradient(90deg, var(--uofg-success), var(--uofg-primary));
        }
        
        .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);
        }
        
        @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">
            <!-- Header -->
            <div class="form-header position-relative">
                <div class="language-switcher">
                    <div class="btn-group btn-group-sm" role="group">
                        <button type="button" class="btn btn-outline-light <?= $isArabic ? 'active' : '' ?>" onclick="changeLanguage('ar')">
                            <i class="fas fa-language"></i> العربية
                        </button>
                        <button type="button" class="btn btn-outline-light <?= !$isArabic ? 'active' : '' ?>" onclick="changeLanguage('en')">
                            <i class="fas fa-language"></i> English
                        </button>
                    </div>
                </div>
                <h1><i class="fas fa-file-medical"></i> <?= $isArabic ? 'النموذج الطبي' : 'Medical Form' ?></h1>
                <p><?= $isArabic ? 'الجامعة الوطنية - قسم الشؤون الطبية' : 'National University - Sudan - Medical Affairs Department' ?></p>
            </div>

            <!-- 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="progress">
                        <div class="progress-bar" id="progressBar" role="progressbar" style="width: 0%"></div>
                    </div>
                    <div class="text-center mt-2 text-muted" id="progressText"><?= $isArabic ? '0% مكتمل' : '0% Complete' ?></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">
                    <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 -->
                <div class="medical-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>

                <!-- Form Actions -->
                <div class="form-actions">
                    <div class="row justify-content-center">
                        <div class="col-auto">
                            <a href="student_profile.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() {
        const questions = document.querySelectorAll('.medical-question');
        let answeredCount = 0;
        
        questions.forEach(question => {
            const checkedInput = question.querySelector('input[type="radio"]:checked');
            if (checkedInput) {
                answeredCount++;
            }
        });
        
        const progress = Math.round((answeredCount / questions.length) * 100);
        document.getElementById('progressBar').style.width = progress + '%';
        document.getElementById('progressText').textContent = progress + '% <?= $isArabic ? "مكتمل" : "Complete" ?>';
    }

    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');
            let allAnswered = true;
            
            requiredQuestions.forEach(question => {
                const checkedInput = question.querySelector('input[type="radio"]:checked');
                if (!checkedInput && !question.querySelector('textarea')) {
                    allAnswered = false;
                }
            });
            
            if (!allAnswered) {
                e.preventDefault();
                alert('<?= $isArabic ? "يرجى الإجابة على جميع الأسئلة الإلزامية قبل الحفظ" : "Please answer all required questions before saving" ?>');
                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>