<?php
// interview_review.php - Enhanced version with complete student data including medical information
 
session_start();

// Include helpers for CSRF and e() function
require 'helpers.php';

// Simple database connection
 
require 'db.php';
 
$mysqli = $mysqli1;

// File detection functions with error handling
function get_student_file_url($studentId, $fileType) {
    $basePath = $_SERVER['DOCUMENT_ROOT'] . '/admission/uploads/';
    $baseUrl = '/admission/uploads/';
    
    $filePatterns = [
        'N' => ['_N.pdf', '_N.jpg', '_N.jpeg', '_N.png', '_N.webp'],
        'M' => ['_M.pdf', '_M.jpg', '_M.jpeg', '_M.png', '_M.webp'],
        'P' => ['_P.png', '_P.jpg', '_P.jpeg', '_P.webp']
    ];
    
    if (!isset($filePatterns[$fileType])) {
        return '';
    }
    
    foreach ($filePatterns[$fileType] as $pattern) {
        $filename = $studentId . $pattern;
        $fullPath = $basePath . $filename;
        
        if (file_exists($fullPath)) {
            return $baseUrl . $filename;
        }
    }
    
    return '';
}

function get_student_photo_url($studentId) {
    return get_student_file_url($studentId, 'P');
}

function get_national_id_url($studentId) {
    return get_student_file_url($studentId, 'N');
}

function get_medical_document_url($studentId) {
    return get_student_file_url($studentId, 'M');
}

// Get student_id from URL
$student_id = trim($_GET['student_id'] ?? $_GET['id'] ?? '');
if (empty($student_id)) {
    die('Missing student ID parameter');
}

// Basic authentication check
if (empty($_SESSION['committee_id'])) {
    header('Location: committee_login.php');
    exit;
}

// Fetch complete student data including medical records
$sql = "
    SELECT 
        s.*,
        c.name AS college_name,
        p.name AS program_name,
        st.name AS state_name,
        co.name AS country_name,
        l.name AS locality_name,
        sec.name AS section_name,
        b.id AS batch_id,
        m.*
    FROM students s
    LEFT JOIN colleges c ON c.id = s.college_id
    LEFT JOIN programs p ON p.id = s.program_id
    LEFT JOIN states st ON st.id = s.state_id
    LEFT JOIN countries co ON co.id = s.country_id
    LEFT JOIN localities l ON l.id = s.locality_id
    LEFT JOIN sections sec ON sec.id = s.section_id
    LEFT JOIN batches b ON b.id = s.batch_id
    LEFT JOIN student_medical_records m ON s.student_id = m.student_id
    WHERE s.student_id = ?
    LIMIT 1
";

$stmt = $mysqli->prepare($sql);
if (!$stmt) {
    // If table doesn't exist, use fallback query
    $sql_fallback = "
        SELECT 
            s.*,
            c.name AS college_name,
            p.name AS program_name,
            st.name AS state_name,
            co.name AS country_name,
            l.name AS locality_name,
            sec.name AS section_name,
            b.id AS batch_id
        FROM students s
        LEFT JOIN colleges c ON c.id = s.college_id
        LEFT JOIN programs p ON p.id = s.program_id
        LEFT JOIN states st ON st.id = s.state_id
        LEFT JOIN countries co ON co.id = s.country_id
        LEFT JOIN localities l ON l.id = s.locality_id
        LEFT JOIN sections sec ON sec.id = s.section_id
        LEFT JOIN batches b ON b.id = s.batch_id
        WHERE s.student_id = ?
        LIMIT 1
    ";
    
    $stmt = $mysqli->prepare($sql_fallback);
    if (!$stmt) {
        die("SQL prepare error: " . $mysqli->error);
    }
}

$stmt->bind_param("s", $student_id);
$stmt->execute();
$student = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$student) {
    die('Student not found with ID: ' . htmlspecialchars($student_id));
}

// Get document URLs with error handling
$photoUrl = get_student_photo_url($student_id);
$nationalIdUrl = get_national_id_url($student_id);
$medicalDocUrl = get_medical_document_url($student_id);

// Get file extensions for display
$nidExt = $nationalIdUrl ? strtolower(pathinfo($nationalIdUrl, PATHINFO_EXTENSION)) : '';
$medicalExt = $medicalDocUrl ? strtolower(pathinfo($medicalDocUrl, PATHINFO_EXTENSION)) : '';

// Medical questions in both languages
$medical_questions = [
    'has_disability' => [
        'ar' => 'إعاقة حركية',
        'en' => 'Physical Disability'
    ],
    'has_chronic_diseases' => [
        'ar' => 'أمراض مزمنة', 
        'en' => 'Chronic Diseases'
    ],
    'has_psychological_diseases' => [
        'ar' => 'أمراض نفسية',
        'en' => 'Psychological Diseases'
    ],
    'has_vision_problems' => [
        'ar' => 'مشاكل في الرؤية',
        'en' => 'Vision Problems'
    ],
    'has_hearing_problems' => [
        'ar' => 'مشاكل في السمع',
        'en' => 'Hearing Problems'
    ],
    'covid_vaccinated' => [
        'ar' => 'تطعيم كوفيد-19',
        'en' => 'COVID-19 Vaccination'
    ],
    'has_diabetes' => [
        'ar' => 'سكري',
        'en' => 'Diabetes'
    ],
    'has_blood_pressure' => [
        'ar' => 'ضغط الدم',
        'en' => 'Blood Pressure'
    ],
    'has_family_diseases' => [
        'ar' => 'أمراض وراثية في العائلة',
        'en' => 'Family Genetic Diseases'
    ]
];

// Helper function to format gender
function get_gender_text($gender) {
    switch($gender) {
        case 1: return 'ذكر';
        case 2: return 'أنثى';
        default: return 'غير محدد';
    }
}

// Helper function to format boolean values
function get_boolean_text($value) {
    if ($value === null) return 'غير محدد';
    return $value ? 'نعم' : 'لا';
}

// Helper function to format date
function format_date($date) {
    if (empty($date) || $date === '0000-00-00') return '—';
    return date('Y-m-d', strtotime($date));
}

// Helper function to format currency
function format_currency($amount) {
    if ($amount === null || $amount === '') return '—';
    return number_format($amount, 2) . ' SDG';
}

// Helper function to get medical status text
function get_medical_status_text($medically_fit, $medical_status) {
    if ($medically_fit == 1 && $medical_status == 'completed') {
        return ['text' => 'مقبول طبيًا', 'class' => 'bg-success'];
    } elseif ($medically_fit == 0 && $medical_status == 'completed') {
        return ['text' => 'غير لائق', 'class' => 'bg-danger'];
    } else {
        return ['text' => 'بانتظار الفحص', 'class' => 'bg-warning text-dark'];
    }
}

// Check if medical data exists
$has_medical_data = isset($student['medical_date']) && !empty($student['medical_date']);
$has_medical_table = isset($student['has_disability']); // Check if medical table columns exist

// Helper function to get batch name
function get_batch_name($batch_id) {
    if (!$batch_id) return '—';
    return 'الدفعة ' . $batch_id;
}

// Generate stable placeholder URLs
$placeholderPhoto = "data:image/svg+xml;charset=UTF-8," . urlencode('<svg width="150" height="150" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 150 150"><rect width="150" height="150" fill="#1F3A2E"/><text x="50%" y="50%" dominant-baseline="middle" text-anchor="middle" font-family="Arial" font-size="14" fill="white">No Image</text></svg>');
$placeholderDocument = "data:image/svg+xml;charset=UTF-8," . urlencode('<svg width="400" height="300" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 400 300"><rect width="400" height="300" fill="#f8fafc" stroke="#e2e8f0" stroke-width="2"/><text x="50%" y="45%" dominant-baseline="middle" text-anchor="middle" font-family="Arial" font-size="16" fill="#6b7280">No Document</text><text x="50%" y="55%" dominant-baseline="middle" text-anchor="middle" font-family="Arial" font-size="12" fill="#9ca3af">لم يتم رفع المستند</text></svg>');
?>

<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
 
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>مراجعة الطلب - الجامعة الجزيرة</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;700&display=swap" rel="stylesheet">
    <style>
        body { 
            font-family: 'Cairo', sans-serif; 
            background: #f8fafc; 
            min-height: 100vh;
        }
        .profile-header { 
            background: linear-gradient(135deg, #1F3A2E, #3E6B54); 
            border-radius: 15px; 
            color: white; 
            padding: 2rem; 
            margin-bottom: 1.5rem; 
        }
        .info-card { 
            background: white; 
            border-radius: 12px; 
            padding: 1.5rem; 
            margin-bottom: 1rem; 
            box-shadow: 0 2px 10px rgba(0,0,0,0.1); 
        }
        
        /* Alert styles for success/error messages */
        .alert { border: none; border-radius: 10px; }
        .alert-success { background: linear-gradient(135deg, #d1fae5, #a7f3d0); color: #065f46; border-left: 4px solid #10b981; }
        .alert-danger { background: linear-gradient(135deg, #fee2e2, #fecaca); color: #991b1b; border-left: 4px solid #ef4444; }
        .alert-warning { background: linear-gradient(135deg, #fef3c7, #fde68a); color: #92400e; border-left: 4px solid #f59e0b; }
        .alert-info { background: linear-gradient(135deg, #dbeafe, #e0e7ff); color: #3730a3; border-left: 4px solid #4f46e5; }
        
        /* Document preview styles */
        .document-preview {
            background: #f8fafc;
            border: 2px dashed #e2e8f0;
            border-radius: 10px;
            padding: 1.5rem;
            text-align: center;
            min-height: 300px;
            display: flex;
            align-items: center;
            justify-content: center;
            position: relative;
        }
        .document-preview.has-content {
            border-style: solid;
            border-color: #d1fae5;
        }
        .nav-tabs .nav-link {
            border: none;
            color: #6b7280;
            font-weight: 600;
            padding: 12px 20px;
        }
        .nav-tabs .nav-link.active {
            border-bottom: 3px solid #1F3A2E;
            color: #1F3A2E;
            background: transparent;
        }
        .nav-tabs .nav-link:hover {
            color: #1F3A2E;
            border-bottom: 3px solid #e5e7eb;
        }
        .info-row {
            border-bottom: 1px solid #f1f5f9;
            padding: 8px 0;
        }
        .info-row:last-child {
            border-bottom: none;
        }
        
        /* Medical questions styles */
        .question-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 12px 0;
            border-bottom: 1px solid #f1f5f9;
        }
        .question-item:last-child {
            border-bottom: none;
        }
        .question-text {
            flex: 1;
        }
        .question-arabic {
            font-size: 1rem;
            font-weight: 600;
            color: #2c3e50;
            margin-bottom: 4px;
        }
        .question-english {
            font-size: 0.85rem;
            font-weight: 500;
            color: #6c757d;
            font-style: italic;
        }
        .answer-badge {
            padding: 6px 12px;
            border-radius: 20px;
            font-size: 0.85rem;
            font-weight: 600;
            min-width: 70px;
            text-align: center;
        }
        .answer-yes {
            background: #dc3545;
            color: white;
        }
        .answer-no {
            background: #198754;
            color: white;
        }
        .details-box {
            background: #f8f9fa;
            border: 1px solid #e9ecef;
            border-radius: 6px;
            padding: 12px;
            margin-top: 8px;
            font-size: 0.9rem;
        }
        
        /* Medical decision styles */
        .medical-decision-card {
            background: linear-gradient(135deg, #f0f9ff, #e0f2fe);
            border: 2px solid #0ea5e9;
            border-radius: 10px;
            padding: 1.5rem;
            margin-bottom: 1.5rem;
        }
        .decision-badge {
            font-size: 1.1rem;
            padding: 8px 16px;
            border-radius: 8px;
            font-weight: 700;
        }
        
        /* Enhanced Medical Decision Styles */
        .medical-decision-card {
            background: linear-gradient(135deg, #f8fafc, #f1f5f9);
            border: 2px solid #e2e8f0;
            border-radius: 12px;
            padding: 1.5rem;
            margin-bottom: 1.5rem;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }

        .decision-badge {
            font-size: 1.1rem;
            padding: 10px 20px;
            border-radius: 10px;
            font-weight: 700;
            display: inline-flex;
            align-items: center;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }

        .status-indicator {
            padding: 15px;
            border-radius: 10px;
            background: white;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            min-width: 100px;
        }

        .status-success { border-left: 4px solid #10b981; }
        .status-danger { border-left: 4px solid #ef4444; }
        .status-warning { border-left: 4px solid #f59e0b; }

        .stat-number {
            font-size: 1.5rem;
            font-weight: bold;
            margin-bottom: 5px;
        }

        .stat-label {
            font-size: 0.85rem;
            color: #6b7280;
        }

        /* Enhanced Medical Form Section */
        .medical-form-section {
            background: white;
            border-radius: 10px;
            padding: 1.5rem;
            border: 1px solid #e5e7eb;
        }

        /* Enhanced Question Items */
        .question-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 15px;
            border-bottom: 1px solid #f1f5f9;
            transition: background-color 0.2s;
            border-radius: 8px;
            margin-bottom: 5px;
        }

        .question-item:hover {
            background-color: #f8fafc;
        }

        .question-text {
            flex: 1;
        }

        .question-arabic {
            font-size: 1rem;
            font-weight: 600;
            color: #1f2937;
            margin-bottom: 4px;
            display: flex;
            align-items: center;
        }

        .question-english {
            font-size: 0.85rem;
            font-weight: 500;
            color: #6b7280;
            font-style: italic;
        }

        .answer-badge {
            padding: 8px 16px;
            border-radius: 20px;
            font-size: 0.9rem;
            font-weight: 600;
            min-width: 80px;
            text-align: center;
            display: flex;
            align-items: center;
            justify-content: center;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
        }

        .answer-yes {
            background: #dc3545;
            color: white;
        }

        .answer-no {
            background: #198754;
            color: white;
        }

        .details-box {
            background: #f8f9fa;
            border: 1px solid #e9ecef;
            border-radius: 8px;
            padding: 15px;
            margin: 10px 0;
            font-size: 0.9rem;
            border-left: 4px solid #0ea5e9;
        }
        
        /* Image stability */
        .student-photo {
            width: 120px;
            height: 120px;
            object-fit: cover;
            border: 3px solid rgba(255,255,255,0.3);
            background: #1F3A2E;
        }
        .document-image {
            max-height: 400px;
            max-width: 100%;
            object-fit: contain;
            background: white;
        }
        
        /* Stable placeholder styles */
        .placeholder-container {
            width: 100%;
            height: 100%;
            display: flex;
            align-items: center;
            justify-content: center;
            flex-direction: column;
        }
        .placeholder-icon {
            font-size: 3rem;
            color: #9ca3af;
            margin-bottom: 1rem;
        }
        .placeholder-text {
            color: #6b7280;
            font-size: 1rem;
        }
        
        /* Fixed dimensions for stability */
        .fixed-photo {
            width: 120px;
            height: 120px;
            flex-shrink: 0;
        }
        .fixed-document-preview {
            min-height: 300px;
            height: 300px;
            overflow: hidden;
        }
    </style>
</head>
<body>
    <div class="container py-4">
        <!-- Display success/error messages -->
        <?php if (isset($_SESSION['decision_main_message'])): ?>
            <div class="alert <?= $_SESSION['decision_success'] ? 'alert-success' : 'alert-danger' ?> alert-dismissible fade show" role="alert">
                <strong><?= e($_SESSION['decision_main_message']) ?></strong>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
            <?php 
            unset($_SESSION['decision_main_message']);
            unset($_SESSION['decision_success']);
            ?>
        <?php endif; ?>

        <!-- Header -->
        <div class="d-flex align-items-center mb-4">
            <a href="committee_dashboard.php" class="btn btn-outline-secondary btn-sm me-3">
                <i class="fas fa-arrow-right me-2"></i>العودة للوحة
            </a>
            <h5 class="mb-0 text-muted">مراجعة طلب الطالب</h5>
        </div>

        <!-- Student Profile Header -->
        <div class="profile-header">
            <div class="row align-items-center">
                <div class="col-auto">
               <div class="fixed-photo">
    <img src="<?= e($photoUrl ?: 'uploads/avatar.png') ?>" 
         alt="صورة الطالب" 
         class="rounded-circle student-photo"
         onerror="this.src='uploads/avatar.png'">
</div>
                </div>
                <div class="col">
                    <h4 class="mb-2">
                        <?= e($student['student_name']) ?>
                        <?php if (!empty($student['student_name_eng'])): ?>
                            <small class="opacity-75">/ <?= e($student['student_name_eng']) ?></small>
                        <?php endif; ?>
                    </h4>
                    <div class="mb-3">
                        <span class="badge bg-light text-dark me-2"><?= e($student['student_id']) ?></span>
                        <span class="badge bg-light text-dark me-2"><?= e($student['college_name'] ?? '—') ?></span>
                        <span class="badge bg-light text-dark"><?= e($student['program_name'] ?? '—') ?></span>
                    </div>
                    <div class="d-flex flex-wrap gap-2">
                        <?php
                        $status = $student['interview_status'] ?? $student['decision_status'] ?? 'pending';
                        $statusClass = 'bg-warning';
                        $statusText = 'قيد المراجعة';
                        if ($status === 'accepted') {
                            $statusClass = 'bg-success';
                            $statusText = 'مقبول';
                        } elseif ($status === 'rejected') {
                            $statusClass = 'bg-danger';
                            $statusText = 'مرفوض';
                        }
                        ?>
                        <span class="badge <?= $statusClass ?>"><?= $statusText ?></span>
                        
                        <?php
                        $medicalStatus = get_medical_status_text($student['medically_fit'], $student['medical_status'] ?? '');
                        ?>
                        <span class="badge <?= $medicalStatus['class'] ?>"><?= $medicalStatus['text'] ?></span>
                        
                        <?php if ($student['profile_completed'] ?? 0): ?>
                            <span class="badge bg-info">الملف مكتمل</span>
                        <?php else: ?>
                            <span class="badge bg-secondary">الملف غير مكتمل</span>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>

        <!-- Documents Section -->
        <div class="info-card">
            <h6 class="mb-3"><i class="fas fa-folder me-2"></i>الوثائق والمستندات</h6>
            
            <ul class="nav nav-tabs mb-3" id="docTabs" role="tablist">
                <li class="nav-item" role="presentation">
                    <button class="nav-link active" id="national-tab" data-bs-toggle="tab" data-bs-target="#national" type="button" role="tab">
                        <i class="fas fa-id-card me-2"></i>الهوية الوطنية
                    </button>
                </li>
                <li class="nav-item" role="presentation">
                    <button class="nav-link" id="medical-info-tab" data-bs-toggle="tab" data-bs-target="#medical-info" type="button" role="tab">
                        <i class="fas fa-stethoscope me-2"></i>المعلومات الطبية
                    </button>
                </li>
            </ul>
            
            <div class="tab-content" id="docTabsContent">
                <!-- National ID Tab -->
                <div class="tab-pane fade show active" id="national" role="tabpanel">
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <div>
                            <strong>وثيقة الهوية الوطنية</strong>
                            <?php if ($nationalIdUrl): ?>
                                <span class="badge bg-success ms-2">موجود</span>
                            <?php else: ?>
                                <span class="badge bg-danger ms-2">غير موجود</span>
                            <?php endif; ?>
                        </div>
                        <?php if ($nationalIdUrl): ?>
                            <a href="<?= e($nationalIdUrl) ?>" target="_blank" class="btn btn-outline-primary btn-sm">
                                <i class="fas fa-download me-2"></i>تحميل
                            </a>
                        <?php endif; ?>
                    </div>
                    
                    <div class="document-preview fixed-document-preview <?= $nationalIdUrl ? 'has-content' : '' ?>">
                        <?php if ($nationalIdUrl): ?>
                            <?php if (in_array($nidExt, ['jpg', 'jpeg', 'png', 'webp'])): ?>
                                <img src="<?= e($nationalIdUrl) ?>" 
                                     alt="الهوية الوطنية" 
                                     class="document-image rounded"
                                     onerror="this.parentElement.innerHTML='<?= addslashes($placeholderDocument) ?>'"
                                     onclick="window.open('<?= e($nationalIdUrl) ?>', '_blank')">
                                <div class="mt-2 text-muted">انقر على الصورة لتكبيرها</div>
                            <?php elseif ($nidExt === 'pdf'): ?>
                                <div class="ratio ratio-16x9 w-100">
                                    <iframe src="<?= e($nationalIdUrl) ?>#toolbar=0" 
                                            style="border: 1px solid #ddd; border-radius: 8px;"
                                            onerror="this.parentElement.parentElement.innerHTML='<div class=\'placeholder-container\'><i class=\'fas fa-file-pdf placeholder-icon\'></i><div class=\'placeholder-text\'>خطأ في تحميل ملف PDF</div></div>'"></iframe>
                                </div>
                            <?php else: ?>
                                <div class="alert alert-info w-100">
                                    <i class="fas fa-download me-2"></i>
                                    <a href="<?= e($nationalIdUrl) ?>" target="_blank" class="alert-link">اضغط لتحميل المستند</a>
                                </div>
                            <?php endif; ?>
                        <?php else: ?>
                            <div class="placeholder-container">
                                <i class="fas fa-file-excel placeholder-icon"></i>
                                <div class="placeholder-text">لم يتم رفع وثيقة الهوية الوطنية</div>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Medical Information Tab -->
                <div class="tab-pane fade" id="medical-info" role="tabpanel">
                    <!-- Medical Decision Card - Enhanced -->
                    <div class="medical-decision-card">
                        <div class="row align-items-center">
                            <div class="col-md-12">
                                <div class="d-flex align-items-center justify-content-between">
                                    <div>
                                        <h6 class="mb-2"><i class="fas fa-user-md me-2"></i>القرار الطبي النهائي</h6>
                                        <?php
                                        $medicalStatus = get_medical_status_text($student['medically_fit'], $student['medical_status'] ?? '');
                                        $decisionIcon = '';
                                        $decisionColor = '';
                                        
                                        if ($student['medically_fit'] == 1) {
                                            $decisionIcon = 'fa-check-circle';
                                            $decisionColor = 'success';
                                        } elseif ($student['medically_fit'] == 0) {
                                            $decisionIcon = 'fa-times-circle';
                                            $decisionColor = 'danger';
                                        } else {
                                            $decisionIcon = 'fa-clock';
                                            $decisionColor = 'warning';
                                        }
                                        ?>
                                        <div class="d-flex align-items-center gap-3">
                                            <span class="decision-badge bg-<?= $decisionColor ?> text-white">
                                                <i class="fas <?= $decisionIcon ?> me-2"></i>
                                                <?= $medicalStatus['text'] ?>
                                            </span>
                                            
                                            <?php if ($student['medical_checked_at']): ?>
                                                <div class="text-muted">
                                                    <small><i class="fas fa-calendar me-1"></i> تاريخ القرار: <?= format_date($student['medical_checked_at']) ?></small>
                                                </div>
                                            <?php endif; ?>
                                            
                                            <?php if ($student['medical_checked_at'] && $student['medically_fit'] !== null): ?>
                                                <div class="text-muted">
                                                    <small><i class="fas fa-user-md me-1"></i> تم الفحص الطبي</small>
                                                </div>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                    
                                    <!-- Status Indicator -->
                                    <div class="text-center">
                                        <div class="status-indicator status-<?= $decisionColor ?>">
                                            <i class="fas <?= $decisionIcon ?> fa-2x mb-2"></i>
                                            <div class="small">الحالة الطبية</div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Quick Stats -->
                        <?php if ($has_medical_data && $has_medical_table): ?>
                            <div class="row mt-3">
                                <div class="col-md-4">
                                    <div class="text-center">
                                        <div class="stat-number text-primary"><?= $student['medical_date'] ? '✓' : '—' ?></div>
                                        <div class="stat-label">تم تعبئة النموذج</div>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="text-center">
                                        <div class="stat-number text-<?= $decisionColor ?>">
                                            <?= $student['medically_fit'] === null ? '⏳' : ($student['medically_fit'] == 1 ? '✓' : '✗') ?>
                                        </div>
                                        <div class="stat-label">الفحص الطبي</div>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="text-center">
                                        <div class="stat-number text-info"><?= $medicalDocUrl ? '✓' : '—' ?></div>
                                        <div class="stat-label">المستندات</div>
                                    </div>
                                </div>
                            </div>
                        <?php endif; ?>
                    </div>

                    <!-- Doctor's Notes - Enhanced -->
                    <?php if (!empty($student['medical_notes'])): ?>
                        <div class="alert alert-info mb-3 border-0 shadow-sm">
                            <div class="d-flex align-items-start">
                                <i class="fas fa-notes-medical fa-lg mt-1 me-3 text-info"></i>
                                <div class="flex-grow-1">
                                    <h6 class="alert-heading mb-2 text-info">ملاحظات الطبيب</h6>
                                    <p class="mb-0 lh-base"><?= nl2br(e($student['medical_notes'])) ?></p>
                                </div>
                            </div>
                        </div>
                    <?php endif; ?>

                    <!-- Medical Form Data -->
                    <div class="medical-form-section">
                        <div class="d-flex justify-content-between align-items-center mb-3">
                            <div class="d-flex align-items-center">
                                <i class="fas fa-clipboard-list me-2 text-primary"></i>
                                <h6 class="mb-0">المعلومات الطبية المدخلة</h6>
                            </div>
                            <div>
                                <?php if ($has_medical_data && $has_medical_table): ?>
                                    <span class="badge bg-success">
                                        <i class="fas fa-check me-1"></i>تم تعبئة النموذج
                                    </span>
                                    <small class="text-muted ms-2"><?= format_date($student['medical_date']) ?></small>
                                <?php else: ?>
                                    <span class="badge bg-danger">
                                        <i class="fas fa-times me-1"></i>لم يتم تعبئة النموذج
                                    </span>
                                <?php endif; ?>
                            </div>
                        </div>

                        <?php if ($has_medical_data && $has_medical_table): ?>
                            <div class="medical-questions">
                                <?php foreach ($medical_questions as $field => $text): ?>
                                    <?php if (isset($student[$field])): ?>
                                        <div class="question-item">
                                            <div class="question-text">
                                                <div class="question-arabic">
                                                    <i class="fas fa-arrow-left me-2 text-muted"></i>
                                                    <?= e($text['ar']) ?>
                                                </div>
                                                <div class="question-english"><?= e($text['en']) ?></div>
                                            </div>
                                            <div class="answer-badge <?= $student[$field] === 'yes' ? 'answer-yes' : 'answer-no' ?>">
                                                <i class="fas <?= $student[$field] === 'yes' ? 'fa-check' : 'fa-times' ?> me-1"></i>
                                                <?= $student[$field] === 'yes' ? 'نعم' : 'لا' ?>
                                            </div>
                                        </div>
                                        
                                        <!-- Show details for specific questions -->
                                        <?php if ($field === 'has_chronic_diseases' && $student[$field] === 'yes' && !empty($student['chronic_diseases_details'])): ?>
                                            <div class="details-box">
                                                <strong><i class="fas fa-info-circle me-2 text-primary"></i>تفاصيل الأمراض المزمنة:</strong>
                                                <p class="mb-0 mt-2"><?= nl2br(e($student['chronic_diseases_details'])) ?></p>
                                            </div>
                                        <?php endif; ?>
                                        
                                        <?php if ($field === 'has_family_diseases' && $student[$field] === 'yes' && !empty($student['family_diseases_details'])): ?>
                                            <div class="details-box">
                                                <strong><i class="fas fa-dna me-2 text-primary"></i>تفاصيل الأمراض الوراثية في العائلة:</strong>
                                                <p class="mb-0 mt-2"><?= nl2br(e($student['family_diseases_details'])) ?></p>
                                            </div>
                                        <?php endif; ?>
                                    <?php endif; ?>
                                <?php endforeach; ?>
                            </div>

                            <!-- Additional Notes -->
                            <?php if (!empty($student['additional_notes'])): ?>
                                <div class="details-box mt-3" style="background: #f0f9ff; border-color: #0ea5e9;">
                                    <strong><i class="fas fa-sticky-note me-2 text-primary"></i>ملاحظات إضافية من الطالب:</strong>
                                    <p class="mb-0 mt-2"><?= nl2br(e($student['additional_notes'])) ?></p>
                                </div>
                            <?php endif; ?>

                        <?php else: ?>
                            <div class="text-center text-muted py-5">
                                <i class="fas fa-file-medical fa-3x mb-3 text-muted"></i>
                                <h6 class="text-muted">لم يقم الطالب بتعبئة النموذج الطبي بعد</h6>
                                <p class="small">لا توجد معلومات طبية مدخلة في النظام</p>
                                <?php if (!$has_medical_table): ?>
                                    <div class="alert alert-warning mt-3 mx-auto" style="max-width: 400px;">
                                        <i class="fas fa-exclamation-triangle me-2"></i>
                                        <small>جدول السجلات الطبية غير متوفر في قاعدة البيانات</small>
                                    </div>
                                <?php endif; ?>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>

        <!-- Personal Information -->
        <div class="info-card">
            <h6><i class="fas fa-user me-2"></i>المعلومات الشخصية</h6>
            <div class="row">
                <div class="col-md-6">
                    <div class="info-row">
                        <div class="row">
                            <div class="col-5 text-muted">البريد الإلكتروني:</div>
                            <div class="col-7"><?= e($student['email'] ?? '—') ?></div>
                        </div>
                    </div>
                    <div class="info-row">
                        <div class="row">
                            <div class="col-5 text-muted">رقم الهاتف الأساسي:</div>
                            <div class="col-7"><?= e($student['phone_number'] ?? '—') ?></div>
                        </div>
                    </div>
                    <div class="info-row">
                        <div class="row">
                            <div class="col-5 text-muted">رقم الهاتف الثانوي:</div>
                            <div class="col-7"><?= e($student['phone_number2'] ?? '—') ?></div>
                        </div>
                    </div>
                    <div class="info-row">
                        <div class="row">
                            <div class="col-5 text-muted">الجنسية:</div>
                            <div class="col-7"><?= e($student['nationality'] ?? '—') ?></div>
                        </div>
                    </div>
                    <div class="info-row">
                        <div class="row">
                            <div class="col-5 text-muted">رقم الهوية:</div>
                            <div class="col-7"><?= e($student['national_id'] ?? '—') ?></div>
                        </div>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="info-row">
                        <div class="row">
                            <div class="col-5 text-muted">تاريخ الميلاد:</div>
                            <div class="col-7"><?= format_date($student['date_of_birth']) ?></div>
                        </div>
                    </div>
                    <div class="info-row">
                        <div class="row">
                            <div class="col-5 text-muted">الجنس:</div>
                            <div class="col-7"><?= get_gender_text($student['gender']) ?></div>
                        </div>
                    </div>
                    <div class="info-row">
                        <div class="row">
                            <div class="col-5 text-muted">فصيلة الدم:</div>
                            <div class="col-7"><?= e($student['blood_type'] ?? '—') ?></div>
                        </div>
                    </div>
                    <div class="info-row">
                        <div class="row">
                            <div class="col-5 text-muted">البلد:</div>
                            <div class="col-7"><?= e($student['country_name'] ?? '—') ?></div>
                        </div>
                    </div>
                    <div class="info-row">
                        <div class="row">
                            <div class="col-5 text-muted">الولاية:</div>
                            <div class="col-7"><?= e($student['state_name'] ?? '—') ?></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Guardian Information -->
        <div class="info-card">
            <h6><i class="fas fa-users me-2"></i>معلومات ولي الأمر</h6>
            <div class="row">
                <div class="col-md-6">
                    <div class="info-row">
                        <div class="row">
                            <div class="col-5 text-muted">اسم ولي الأمر:</div>
                            <div class="col-7"><?= e($student['guardian_name'] ?? '—') ?></div>
                        </div>
                    </div>
                    <div class="info-row">
                        <div class="row">
                            <div class="col-5 text-muted">هاتف ولي الأمر:</div>
                            <div class="col-7"><?= e($student['guardian_phone_number'] ?? '—') ?></div>
                        </div>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="info-row">
                        <div class="row">
                            <div class="col-5 text-muted">عنوان ولي الأمر:</div>
                            <div class="col-7"><?= e($student['guardian_address'] ?? '—') ?></div>
                        </div>
                    </div>
                    <div class="info-row">
                        <div class="row">
                            <div class="col-5 text-muted">عنوان السكن:</div>
                            <div class="col-7"><?= e($student['home_address'] ?? '—') ?></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Academic Information -->
        <div class="info-card">
            <h6><i class="fas fa-graduation-cap me-2"></i>المعلومات الأكاديمية</h6>
            <div class="row">
                <div class="col-md-6">
                    <div class="info-row">
                        <div class="row">
                            <div class="col-5 text-muted">الكلية:</div>
                            <div class="col-7"><?= e($student['college_name'] ?? '—') ?></div>
                        </div>
                    </div>
                    <div class="info-row">
                        <div class="row">
                            <div class="col-5 text-muted">البرنامج:</div>
                            <div class="col-7"><?= e($student['program_name'] ?? '—') ?></div>
                        </div>
                    </div>
                    <div class="info-row">
                        <div class="row">
                            <div class="col-5 text-muted">القسم:</div>
                            <div class="col-7"><?= e($student['section_name'] ?? '—') ?></div>
                        </div>
                    </div>
                    <div class="info-row">
                        <div class="row">
                            <div class="col-5 text-muted">الدفعة:</div>
                            <div class="col-7"><?= get_batch_name($student['batch_id'] ?? null) ?></div>
                        </div>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="info-row">
                        <div class="row">
                            <div class="col-5 text-muted">درجة القبول:</div>
                            <div class="col-7"><?= e($student['admission_degree'] ?? '—') ?></div>
                        </div>
                    </div>
                    <div class="info-row">
                        <div class="row">
                            <div class="col-5 text-muted">نسبة القبول:</div>
                            <div class="col-7"><?= e($student['acceptance_rate'] ? ($student['acceptance_rate'] * 100) . '%' : '—') ?></div>
                        </div>
                    </div>
                    <div class="info-row">
                        <div class="row">
                            <div class="col-5 text-muted">نوع القبول:</div>
                            <div class="col-7"><?= e($student['addmission_type'] ?? '—') ?></div>
                        </div>
                    </div>
                    <div class="info-row">
                        <div class="row">
                            <div class="col-5 text-muted">تاريخ القبول:</div>
                            <div class="col-7"><?= format_date($student['addmission_date']) ?></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Financial Information -->
        <div class="info-card">
            <h6><i class="fas fa-money-bill me-2"></i>المعلومات المالية</h6>
            <div class="row">
                <div class="col-md-6">
                    <div class="info-row">
                        <div class="row">
                            <div class="col-5 text-muted">رسوم البرنامج:</div>
                            <div class="col-7"><?= format_currency($student['program_fees']) ?></div>
                        </div>
                    </div>
                    <div class="info-row">
                        <div class="row">
                            <div class="col-5 text-muted">رسوم التسجيل:</div>
                            <div class="col-7"><?= format_currency($student['registration_fees']) ?></div>
                        </div>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="info-row">
                        <div class="row">
                            <div class="col-5 text-muted">رسوم التأمين:</div>
                            <div class="col-7"><?= format_currency($student['insurance_fees']) ?></div>
                        </div>
                    </div>
                    <div class="info-row">
                        <div class="row">
                            <div class="col-5 text-muted">الخصم:</div>
                            <div class="col-7"><?= e($student['discount'] ? $student['discount'] . '%' : '—') ?></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Decision Form -->
      <!-- Decision Form -->
<div class="info-card">
    <h6><i class="fas fa-clipboard-check me-2"></i>قرار اللجنة</h6>
    
    <?php if ($student['medically_fit'] === null): ?>
        <div class="alert alert-warning">
            <i class="fas fa-exclamation-triangle me-2"></i>
            ملاحظة: الفحص الطبي لم يتم بعد.
        </div>
    <?php endif; ?>
    
    <form method="post" action="interview_decide.php" id="decisionForm">
        <!-- Use csrf_token() function from helpers.php -->
        <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
        <input type="hidden" name="pk" value="<?= e($student['id']) ?>">
        <input type="hidden" name="student_id" value="<?= e($student_id) ?>">
        
        <div class="mb-3">
            <label class="form-label">ملاحظات اللجنة</label>
            <textarea name="comment" class="form-control" rows="3" 
                      placeholder="يرجى كتابة سبب الرفض في حال رفض الطلب..."><?= e($student['committee_comment'] ?? '') ?></textarea>
            <div class="form-text">هذا الحقل إلزامي في حالة الرفض</div>
        </div>
        
        <div class="d-flex gap-2 justify-content-end">
            <a href="committee_dashboard.php" class="btn btn-outline-secondary">إلغاء</a>
            <button type="submit" name="decision" value="rejected" class="btn btn-danger">رفض</button>
            <button type="submit" name="decision" value="accepted" class="btn btn-success">قبول</button>
        </div>
    </form>
</div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Enhanced error handling for images and documents
        document.addEventListener('DOMContentLoaded', function() {
            // Handle image errors
            const images = document.querySelectorAll('img');
            images.forEach(img => {
                img.addEventListener('error', function() {
                    if (this.classList.contains('student-photo')) {
                        this.src = '<?= e($placeholderPhoto) ?>';
                    } else if (this.classList.contains('document-image')) {
                        const placeholder = document.createElement('div');
                        placeholder.className = 'placeholder-container';
                        placeholder.innerHTML = '<i class="fas fa-file-image placeholder-icon"></i><div class="placeholder-text">خطأ في تحميل الصورة</div>';
                        this.parentElement.replaceChild(placeholder, this);
                    }
                });
                
                // Ensure images are loaded before showing
                img.addEventListener('load', function() {
                    this.style.opacity = '1';
                });
            });

            // Handle iframe errors
            const iframes = document.querySelectorAll('iframe');
            iframes.forEach(iframe => {
                iframe.addEventListener('error', function() {
                    const placeholder = document.createElement('div');
                    placeholder.className = 'placeholder-container';
                    placeholder.innerHTML = '<i class="fas fa-file-pdf placeholder-icon"></i><div class="placeholder-text">خطأ في تحميل المستند</div>';
                    this.parentElement.parentElement.replaceChild(placeholder, this.parentElement);
                });
            });
        });

        // Form validation
 // Form validation
document.getElementById('decisionForm').addEventListener('submit', function(e) {
    const submitter = e.submitter.value;
    if (submitter === 'rejected') { // FIXED: Check for 'rejected' not 'reject'
        const comment = this.comment.value.trim();
        if (!comment) {
            e.preventDefault();
            alert('يرجى كتابة سبب الرفض في حقل الملاحظات');
            this.comment.focus();
        }
    }
});
    </script>
</body>
</html>