<?php
session_start();
if (function_exists('opcache_reset')) { opcache_reset(); }
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

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

// DB Connection
$mysqli = new mysqli("uofg.edu.sd", "uofgedu_user8cer", "XI%ClX,e}R7oFkRSX", "uofgedu_registration");
$mysqli->set_charset("utf8mb4");

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $medical_data = [
        'student_name' => $mysqli->real_escape_string($_POST['student_name'] ?? ''),
        'student_phone' => $mysqli->real_escape_string($_POST['student_phone'] ?? ''),
        'student_email' => $mysqli->real_escape_string($_POST['student_email'] ?? ''),
        'language' => $lang
    ];
    
    // Medical examination fields
    $medical_fields = [
        'scalp', 'lymph_nodes', 'nose', 'trachea', 'ears_hearing', 
        'eyes_vision', 'thyroid', 'chest', 'abd', 'cns',
        'vaccinated', 'covid_vaccine', 'chronic_diseases', 
        'family_diseases', 'surgical_history', 'psychological_examination',
        'overall_health_status'
    ];
    
    foreach ($medical_fields as $field) {
        $medical_data[$field] = $mysqli->real_escape_string($_POST[$field] ?? '');
        $medical_data[$field . '_details'] = $mysqli->real_escape_string($_POST[$field . '_details'] ?? '');
        $medical_data[$field . '_notes'] = $mysqli->real_escape_string($_POST[$field . '_notes'] ?? '');
    }
    
    $medical_data['doctor_notes'] = $mysqli->real_escape_string($_POST['doctor_notes'] ?? '');
    $medical_data['recommendations'] = $mysqli->real_escape_string($_POST['recommendations'] ?? '');
    
    // Build insert query
    $columns = implode(', ', array_keys($medical_data));
    $values = "'" . implode("', '", array_values($medical_data)) . "'";
    
    $query = "INSERT INTO medical_records ($columns) VALUES ($values)";
    
    if ($mysqli->query($query)) {
        $success_message = $isArabic ? 
            "تم حفظ البيانات الطبية بنجاح" : 
            "Medical data saved successfully";
    } else {
        $error_message = $isArabic ? 
            "حدث خطأ في حفظ البيانات" : 
            "Error saving medical data";
    }
}
?>

<!DOCTYPE html>
<html lang="<?= $lang ?>" dir="<?= $dir ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title><?= $isArabic ? 'النموذج الطبي - جامعة الجزيرة' : 'Medical Form - University of Gezira' ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    
    <style>
        :root {
            --uofg-green: #006837;
            --uofg-dark-green: #004d26;
            --uofg-light: #f8f9fa;
        }
        
        * {
            font-family: 'Cairo', sans-serif;
        }
        
        body {
            background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
            min-height: 100vh;
        }
        
        .sidebar {
            background: var(--uofg-green);
            color: white;
            min-height: 100vh;
            box-shadow: 2px 0 10px rgba(0,0,0,0.1);
        }
        
        .sidebar .nav-link {
            color: white;
            padding: 1rem 1.5rem;
            border-radius: 0.5rem;
            margin: 0.25rem 0;
            transition: all 0.3s ease;
        }
        
        .sidebar .nav-link:hover, .sidebar .nav-link.active {
            background: rgba(255,255,255,0.1);
            transform: translateX(-5px);
        }
        
        .medical-section {
            background: white;
            border-radius: 1rem;
            padding: 2rem;
            margin-bottom: 2rem;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
        }
        
        .section-title {
            color: var(--uofg-green);
            border-bottom: 3px solid var(--uofg-green);
            padding-bottom: 0.5rem;
            margin-bottom: 1.5rem;
        }
        
        .medical-item {
            border: 2px solid #e9ecef;
            border-radius: 0.75rem;
            padding: 1.5rem;
            margin-bottom: 1rem;
            transition: all 0.3s ease;
        }
        
        .medical-item:hover {
            border-color: var(--uofg-green);
            box-shadow: 0 4px 15px rgba(0,104,55,0.1);
        }
        
        .btn-language {
            border-radius: 2rem;
            padding: 0.5rem 1.5rem;
            font-weight: 600;
        }
        
        [dir="rtl"] {
            text-align: right;
        }
        
        [dir="ltr"] {
            text-align: left;
        }
    </style>
</head>
<body dir="<?= $dir ?>">
    <div class="container-fluid">
        <div class="row">
            <!-- Sidebar -->
            <nav class="col-md-3 col-lg-2 d-md-block sidebar">
                <div class="position-sticky pt-3">
                    <div class="text-center mb-4">
                        <img src="https://uofg.edu.sd/wp-content/uploads/2023/08/cropped-UofG-Logo-1.png" height="50" class="mb-2" alt="Logo">
                        <h6 class="fw-bold"><?= $isArabic ? 'نظام الإدارة' : 'Management System' ?></h6>
                    </div>
                    
                    <ul class="nav flex-column">
                        <li class="nav-item">
                            <a class="nav-link" href="supervisor_dashboard.php?lang=<?= $lang ?>">
                                <i class="bi bi-speedometer2"></i>
                                <?= $isArabic ? 'لوحة التحكم' : 'Dashboard' ?>
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="supervisor_requests.php?lang=<?= $lang ?>">
                                <i class="bi bi-journal-text"></i>
                                <?= $isArabic ? 'إدارة الطلبات' : 'Requests Management' ?>
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="supervisor_payments.php?lang=<?= $lang ?>">
                                <i class="bi bi-credit-card"></i>
                                <?= $isArabic ? 'المدفوعات' : 'Payments' ?>
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="medical_records.php?lang=<?= $lang ?>">
                                <i class="bi bi-clipboard2-pulse"></i>
                                <?= $isArabic ? 'السجلات الطبية' : 'Medical Records' ?>
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link active" href="medical_form.php?lang=<?= $lang ?>">
                                <i class="bi bi-file-medical"></i>
                                <?= $isArabic ? 'نموذج طبي' : 'Medical Form' ?>
                            </a>
                        </li>
                    </ul>
                    
                    <!-- Language Switcher -->
                    <div class="mt-4 p-3">
                        <div class="d-grid gap-2">
                            <a href="?lang=ar" class="btn <?= $isArabic ? 'btn-light' : 'btn-outline-light' ?> btn-language">
                                <i class="bi bi-translate"></i> العربية
                            </a>
                            <a href="?lang=en" class="btn <?= !$isArabic ? 'btn-light' : 'btn-outline-light' ?> btn-language">
                                <i class="bi bi-translate"></i> English
                            </a>
                        </div>
                    </div>
                </div>
            </nav>

            <!-- Main Content -->
            <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4 py-4">
                <!-- Header -->
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <div>
                        <h2 class="fw-bold">
                            <?= $isArabic ? 'النموذج الطبي للطلاب' : 'Student Medical Form' ?>
                        </h2>
                        <p class="text-muted">
                            <?= $isArabic ? 
                                'جامعة الجزيرة - الفحص الطبي الشامل' : 
                                'University of Gezira - Comprehensive Medical Examination' ?>
                        </p>
                    </div>
                </div>

                <?php if (isset($success_message)): ?>
                <div class="alert alert-success alert-dismissible fade show">
                    <i class="bi bi-check-circle-fill"></i>
                    <?= $success_message ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
                <?php endif; ?>

                <?php if (isset($error_message)): ?>
                <div class="alert alert-danger alert-dismissible fade show">
                    <i class="bi bi-exclamation-triangle-fill"></i>
                    <?= $error_message ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
                <?php endif; ?>

                <!-- Medical Form -->
                <form method="post" id="medicalForm">
                    <!-- Student Information -->
                    <div class="medical-section">
                        <h4 class="section-title">
                            <i class="bi bi-person-vcard"></i>
                            <?= $isArabic ? 'معلومات الطالب' : 'Student Information' ?>
                        </h4>
                        
                        <div class="row">
                            <div class="col-md-4">
                                <label class="form-label fw-bold">
                                    <?= $isArabic ? 'اسم الطالب' : 'Student Name' ?>
                                </label>
                                <input type="text" name="student_name" class="form-control" required>
                            </div>
                            <div class="col-md-4">
                                <label class="form-label fw-bold">
                                    <?= $isArabic ? 'رقم الهاتف' : 'Phone Number' ?>
                                </label>
                                <input type="tel" name="student_phone" class="form-control" required>
                            </div>
                            <div class="col-md-4">
                                <label class="form-label fw-bold">
                                    <?= $isArabic ? 'البريد الإلكتروني' : 'Email Address' ?>
                                </label>
                                <input type="email" name="student_email" class="form-control">
                            </div>
                        </div>
                    </div>

                    <!-- Physical Examination -->
                    <div class="medical-section">
                        <h4 class="section-title">
                            <i class="bi bi-heart-pulse"></i>
                            <?= $isArabic ? 'الفحص البدني' : 'Physical Examination' ?>
                        </h4>
                        
                        <?php
                        $physical_exams = [
                            'scalp' => ['ar' => 'فروة الرأس', 'en' => 'Scalp'],
                            'lymph_nodes' => ['ar' => 'العقد الليمفاوية', 'en' => 'Lymph Nodes'],
                            'nose' => ['ar' => 'الأنف', 'en' => 'Nose'],
                            'trachea' => ['ar' => 'القصبة الهوائية', 'en' => 'Trachea'],
                            'ears_hearing' => ['ar' => 'الأذن (السمع)', 'en' => 'Ears (Hearing)'],
                            'eyes_vision' => ['ar' => 'العين (الإبصار)', 'en' => 'Eyes (Vision)'],
                            'thyroid' => ['ar' => 'الغدة الدرقية', 'en' => 'Thyroid'],
                            'chest' => ['ar' => 'الصدر', 'en' => 'Chest'],
                            'abd' => ['ar' => 'البطن', 'en' => 'Abdomen'],
                            'cns' => ['ar' => 'الجهاز العصبي المركزي', 'en' => 'Central Nervous System']
                        ];
                        
                        foreach ($physical_exams as $key => $labels):
                        ?>
                        <div class="medical-item">
                            <div class="row align-items-center">
                                <div class="col-md-3">
                                    <h6 class="fw-bold text-primary">
                                        <?= $isArabic ? $labels['ar'] : $labels['en'] ?>
                                    </h6>
                                </div>
                                <div class="col-md-3">
                                    <select name="<?= $key ?>" class="form-select" required>
                                        <option value=""><?= $isArabic ? 'اختر الحالة' : 'Select Status' ?></option>
                                        <option value="normal"><?= $isArabic ? 'طبيعي' : 'Normal' ?></option>
                                        <option value="abnormal"><?= $isArabic ? 'غير طبيعي' : 'Abnormal' ?></option>
                                    </select>
                                </div>
                                <div class="col-md-6">
                                    <textarea name="<?= $key ?>_notes" class="form-control" rows="2" 
                                              placeholder="<?= $isArabic ? 'ملاحظات إضافية...' : 'Additional notes...' ?>"></textarea>
                                </div>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>

                    <!-- Medical History -->
                    <div class="medical-section">
                        <h4 class="section-title">
                            <i class="bi bi-clipboard2-heart"></i>
                            <?= $isArabic ? 'التاريخ الطبي' : 'Medical History' ?>
                        </h4>
                        
                        <?php
                        $medical_history = [
                            'vaccinated' => [
                                'ar' => 'التطعيمات الأساسية', 
                                'en' => 'Basic Vaccinations',
                                'type' => 'yesno'
                            ],
                            'covid_vaccine' => [
                                'ar' => 'لقاح كوفيد-19', 
                                'en' => 'COVID-19 Vaccine',
                                'type' => 'covid'
                            ],
                            'chronic_diseases' => [
                                'ar' => 'أمراض مزمنة', 
                                'en' => 'Chronic Diseases',
                                'type' => 'yesno'
                            ],
                            'family_diseases' => [
                                'ar' => 'أمراض عائلية', 
                                'en' => 'Family Diseases',
                                'type' => 'yesno'
                            ],
                            'surgical_history' => [
                                'ar' => 'تاريخ جراحي', 
                                'en' => 'Surgical History',
                                'type' => 'yesno'
                            ],
                            'psychological_examination' => [
                                'ar' => 'فحص نفسي', 
                                'en' => 'Psychological Examination',
                                'type' => 'normalabnormal'
                            ]
                        ];
                        
                        foreach ($medical_history as $key => $data):
                        ?>
                        <div class="medical-item">
                            <div class="row align-items-center">
                                <div class="col-md-3">
                                    <h6 class="fw-bold text-primary">
                                        <?= $isArabic ? $data['ar'] : $data['en'] ?>
                                    </h6>
                                </div>
                                <div class="col-md-3">
                                    <select name="<?= $key ?>" class="form-select" required>
                                        <option value=""><?= $isArabic ? 'اختر' : 'Select' ?></option>
                                        <?php if ($data['type'] === 'yesno'): ?>
                                            <option value="yes"><?= $isArabic ? 'نعم' : 'Yes' ?></option>
                                            <option value="no"><?= $isArabic ? 'لا' : 'No' ?></option>
                                        <?php elseif ($data['type'] === 'covid'): ?>
                                            <option value="yes"><?= $isArabic ? 'مكتمل' : 'Completed' ?></option>
                                            <option value="partially"><?= $isArabic ? 'جزئي' : 'Partially' ?></option>
                                            <option value="no"><?= $isArabic ? 'لم يتلق' : 'Not Received' ?></option>
                                        <?php else: ?>
                                            <option value="normal"><?= $isArabic ? 'طبيعي' : 'Normal' ?></option>
                                            <option value="abnormal"><?= $isArabic ? 'غير طبيعي' : 'Abnormal' ?></option>
                                        <?php endif; ?>
                                    </select>
                                </div>
                                <div class="col-md-6">
                                    <textarea name="<?= $key ?>_details" class="form-control" rows="2" 
                                              placeholder="<?= $isArabic ? 'تفاصيل إضافية...' : 'Additional details...' ?>"></textarea>
                                </div>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>

                    <!-- Overall Assessment -->
                    <div class="medical-section">
                        <h4 class="section-title">
                            <i class="bi bi-clipboard2-check"></i>
                            <?= $isArabic ? 'التقييم النهائي' : 'Final Assessment' ?>
                        </h4>
                        
                        <div class="row">
                            <div class="col-md-6">
                                <label class="form-label fw-bold">
                                    <?= $isArabic ? 'الحالة الصحية العامة' : 'Overall Health Status' ?>
                                </label>
                                <select name="overall_health_status" class="form-select" required>
                                    <option value=""><?= $isArabic ? 'اختر الحالة' : 'Select Status' ?></option>
                                    <option value="excellent"><?= $isArabic ? 'ممتاز' : 'Excellent' ?></option>
                                    <option value="good"><?= $isArabic ? 'جيد' : 'Good' ?></option>
                                    <option value="fair"><?= $isArabic ? 'متوسط' : 'Fair' ?></option>
                                    <option value="poor"><?= $isArabic ? 'ضعيف' : 'Poor' ?></option>
                                </select>
                            </div>
                        </div>
                        
                        <div class="row mt-3">
                            <div class="col-md-6">
                                <label class="form-label fw-bold">
                                    <?= $isArabic ? 'ملاحظات الطبيب' : 'Doctor Notes' ?>
                                </label>
                                <textarea name="doctor_notes" class="form-control" rows="4" 
                                          placeholder="<?= $isArabic ? 'ملاحظات الطبيب...' : 'Doctor notes...' ?>"></textarea>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label fw-bold">
                                    <?= $isArabic ? 'التوصيات' : 'Recommendations' ?>
                                </label>
                                <textarea name="recommendations" class="form-control" rows="4" 
                                          placeholder="<?= $isArabic ? 'التوصيات الطبية...' : 'Medical recommendations...' ?>"></textarea>
                            </div>
                        </div>
                    </div>

                    <!-- Submit Button -->
                    <div class="text-center mt-4">
                        <button type="submit" class="btn btn-primary btn-lg px-5">
                            <i class="bi bi-save"></i>
                            <?= $isArabic ? 'حفظ البيانات الطبية' : 'Save Medical Data' ?>
                        </button>
                    </div>
                </form>
            </main>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Form validation and enhancement
        document.getElementById('medicalForm').addEventListener('submit', function(e) {
            const requiredFields = this.querySelectorAll('[required]');
            let valid = true;
            
            requiredFields.forEach(field => {
                if (!field.value.trim()) {
                    valid = false;
                    field.classList.add('is-invalid');
                } else {
                    field.classList.remove('is-invalid');
                }
            });
            
            if (!valid) {
                e.preventDefault();
                alert('<?= $isArabic ? "يرجى ملء جميع الحقول المطلوبة" : "Please fill all required fields" ?>');
            }
        });
    </script>
</body>
</html>