<?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'];
$action = $_GET['action'] ?? 'new';

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

// Get existing medical record
$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();
}

// Define questions
$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?'
    ]
];
?>

<!-- Medical Form Content for Modal -->
<div class="medical-form-container">
    <!-- Student Information -->
    <div class="student-info">
        <div class="row">
            <div class="col-md-6">
                <strong>الاسم:</strong> <?= e($student_data['student_name']) ?>
            </div>
            <div class="col-md-6">
                <strong>الرقم الجامعي:</strong> <?= e($student_data['student_id']) ?>
            </div>
            <div class="col-md-6">
                <strong>الكليّة:</strong> <?= e($student_data['college_name']) ?>
            </div>
            <div class="col-md-6">
                <strong>البرنامج:</strong> <?= e($student_data['program_name']) ?>
            </div>
        </div>
    </div>

    <!-- Medical Form -->
    <form method="post" id="medicalFormModal">
        <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">تقدم تعبئة النموذج:</span>
                <span class="text-muted" id="progressTextModal">0% مكتمل</span>
            </div>
            <div class="progress">
                <div class="progress-bar" id="progressBarModal" role="progressbar" style="width: 0%"></div>
            </div>
        </div>

        <?php
        $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="selectOptionModal(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>لا</span>
                </label>
                <label class="option-label yes-option" onclick="selectOptionModal(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>نعم</span>
                </label>
            </div>
            
            <!-- Details fields -->
            <?php if ($field === 'has_chronic_diseases'): ?>
            <div class="details-input <?= ($existing_record[$field] ?? '') === 'yes' ? 'show' : '' ?>" id="chronicDetailsModal">
                <textarea name="chronic_diseases_details" class="form-control" rows="3" 
                          placeholder="يرجى ذكر الأمراض المزمنة التي تعاني منها..."><?= 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="familyDiseasesDetailsModal">
                <textarea name="family_diseases_details" class="form-control" rows="3" 
                          placeholder="يرجى ذكر الأمراض الوراثية في العائلة..."><?= e($existing_record['family_diseases_details'] ?? '') ?></textarea>
            </div>
            <?php endif; ?>
        </div>
        <?php 
        $question_number++;
        endforeach; 
        ?>

        <!-- Additional Notes -->
        <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="أي معلومات طبية إضافية تود إضافتها..."><?= e($existing_record['additional_notes'] ?? '') ?></textarea>
        </div>

        <!-- Reset Section -->
        <div class="reset-section">
            <h5 class="mb-3">إعادة تعيين النموذج</h5>
            <p class="text-muted mb-3">يمكنك إعادة تعيين جميع الإجابات والبدء من جديد</p>
            <button type="button" class="btn btn-warning" onclick="resetFormModal()">
                <i class="fas fa-redo"></i> إعادة تعيين النموذج
            </button>
        </div>

        <!-- Form Actions -->
        <div class="form-actions">
            <div class="row justify-content-center">
                <div class="col-auto">
                    <button type="button" class="btn btn-secondary btn-lg" data-bs-dismiss="modal">
                        <i class="fas fa-times me-1"></i> إلغاء
                    </button>
                </div>
                <div class="col-auto">
                    <button type="submit" class="btn btn-success btn-lg" id="submitBtnModal">
                        <i class="fas fa-save"></i> حفظ البيانات الطبية
                    </button>
                </div>
            </div>
        </div>
    </form>
</div>

<style>
.medical-form-container {
    background: white;
    border-radius: 10px;
    overflow: hidden;
}

.student-info {
    background: #f8f9fa;
    border: 1px solid #dee2e6;
    border-radius: 8px;
    padding: 20px;
    margin: 15px;
}

.medical-question {
    background: white;
    border: 1px solid #dee2e6;
    border-radius: 8px;
    padding: 20px;
    margin: 10px 15px;
    transition: all 0.2s ease;
}

.question-text {
    margin-bottom: 20px;
}

.question-number {
    background: #1e3a8a;
    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: #198754;
    background: rgba(25, 135, 84, 0.05);
}

.option-label.no-option:hover {
    border-color: #dc3545;
    background: rgba(220, 53, 69, 0.05);
}

.option-label.selected.yes-option {
    background: #198754;
    color: white;
    border-color: #198754;
}

.option-label.selected.no-option {
    background: #dc3545;
    color: white;
    border-color: #dc3545;
}

.option-input {
    display: none;
}

.details-input {
    margin-top: 20px;
    display: none;
}

.details-input.show {
    display: block;
}

.progress-container {
    padding: 0 20px 20px 20px;
}

.progress {
    height: 12px;
    background-color: #e9ecef;
    border-radius: 6px;
    overflow: hidden;
}

.progress-bar {
    background: linear-gradient(90deg, #198754, #1e3a8a) !important;
    transition: width 0.3s ease;
    border-radius: 6px;
}

.required-star {
    color: #dc3545;
    margin-left: 5px;
}

.reset-section {
    background: #f8f9fa;
    border: 1px solid #dee2e6;
    border-radius: 8px;
    padding: 20px;
    margin: 20px;
    text-align: center;
}

.form-actions {
    background: #f8f9fa;
    padding: 25px;
    border-top: 1px solid #dee2e6;
}
</style>

<script>
// Modal-specific functions
function selectOptionModal(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') {
        const details = document.getElementById('chronicDetailsModal');
        if (details) {
            if (value === 'yes') {
                details.classList.add('show');
            } else {
                details.classList.remove('show');
            }
        }
    }
    
    if (fieldName === 'has_family_diseases') {
        const details = document.getElementById('familyDiseasesDetailsModal');
        if (details) {
            if (value === 'yes') {
                details.classList.add('show');
            } else {
                details.classList.remove('show');
            }
        }
    }
    
    // Update progress
    updateProgressModal();
}

function updateProgressModal() {
    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('progressBarModal');
    const progressText = document.getElementById('progressTextModal');
    
    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, #198754, #28a745)';
        } else {
            progressBar.style.background = 'linear-gradient(90deg, #198754, #1e3a8a)';
        }
    }
    
    if (progressText) {
        progressText.textContent = progress + '% مكتمل';
    }
}

function resetFormModal() {
    if (confirm('هل أنت متأكد من إعادة تعيين النموذج؟ سيتم حذف جميع الإجابات.')) {
        // 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
        updateProgressModal();
        
        // Show success message
        alert('تم إعادة تعيين النموذج بنجاح');
    }
}

function showAlertModal(type, message) {
    const alertDiv = document.createElement('div');
    alertDiv.className = `alert alert-${type === 'success' ? 'success' : 'danger'} alert-dismissible fade show`;
    alertDiv.innerHTML = `
        <div class="d-flex align-items-center">
            <i class="fas fa-${type === 'success' ? 'check-circle' : 'exclamation-triangle'} me-2"></i>
            <div>${message}</div>
        </div>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;
    
    const modalBody = document.getElementById('medicalFormContent');
    modalBody.insertBefore(alertDiv, modalBody.firstChild);
}

// Initialize modal form when loaded
document.addEventListener('DOMContentLoaded', function() {
    // Set initial selected states
    document.querySelectorAll('.option-input:checked').forEach(input => {
        const label = input.closest('.option-label');
        if (label) {
            label.classList.add('selected');
        }
    });
    
    // Update progress on load
    updateProgressModal();
    
    // Add form submission handler
    const medicalForm = document.getElementById('medicalFormModal');
    if (medicalForm) {
        medicalForm.addEventListener('submit', function(e) {
            e.preventDefault();
            
            const formData = new FormData(this);
            const submitBtn = this.querySelector('button[type="submit"]');
            
            // Validate required questions
            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;
                    question.style.borderColor = '#dc3545';
                    question.style.backgroundColor = 'rgba(220, 53, 69, 0.05)';
                } else {
                    question.style.borderColor = '';
                    question.style.backgroundColor = '';
                }
            });
            
            if (!allAnswered) {
                alert('يرجى الإجابة على جميع الأسئلة الإلزامية قبل الحفظ');
                return false;
            }
            
            // Show loading state
            const originalText = submitBtn.innerHTML;
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> جاري الحفظ...';
            
            // Submit form via AJAX
            fetch('student_medical_form.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // Show success message
                    showAlertModal('success', data.message);
                    
                    // Close modal and reload page after delay
                    setTimeout(() => {
                        const modal = bootstrap.Modal.getInstance(document.getElementById('medicalFormModal'));
                        if (modal) {
                            modal.hide();
                        }
                        // Reload page to update medical status
                        window.location.reload();
                    }, 1500);
                } else {
                    showAlertModal('error', data.message);
                    submitBtn.disabled = false;
                    submitBtn.innerHTML = originalText;
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showAlertModal('error', 'حدث خطأ أثناء حفظ البيانات');
                submitBtn.disabled = false;
                submitBtn.innerHTML = originalText;
            });
        });
    }
});

// Force progress update after modal loads
setTimeout(updateProgressModal, 100);
</script>