<?php
// Display errors for debugging
ini_set('display_errors', 1);
error_reporting(E_ALL);

$pageTitle = 'وثائق الطالب';
include '../../includes/header.php';

if (session_status() == PHP_SESSION_NONE) {
    session_start();
}
checkLogin();

// Get Student ID
$student_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if ($student_id == 0) {
    echo "<div class='container mt-5'><div class='alert alert-danger'>رقم الطالب غير صالح.</div></div>";
    include '../../includes/footer.php';
    exit();
}

$db = getDB();

// 1. Fetch Student Info (Expanded)
$student_sql = "SELECT 
                    full_name, national_id_number, College, Departement, 
                    enrollment_date, gender, Yearly_Cost, grade_level, 
                    addmission, status 
                FROM students WHERE id = ?";

$student = $db->select($student_sql, [$student_id])[0] ?? null;

if (!$student) {
    echo "<div class='container mt-5'><div class='alert alert-danger'>الطالب غير موجود.</div></div>";
    include '../../includes/footer.php';
    exit();
}

// 2. Fetch Documents (BLOBs)
$docs_sql = "SELECT * FROM students_docs WHERE Student_ID = ?";
$docs = $db->select($docs_sql, [$student_id])[0] ?? null;

// Helper function to render BLOB data (Compact View + Full Screen Click)
function renderDoc($blobData, $title) {
    if (empty($blobData)) {
        return '<div class="alert alert-warning text-center p-2 mb-0"><small>غير متوفر</small></div>';
    }

    $finfo = new finfo(FILEINFO_MIME_TYPE);
    $mimeType = $finfo->buffer($blobData);
    $base64 = base64_encode($blobData);
    $src = 'data:' . $mimeType . ';base64,' . $base64;

    // Fixed height for compact look (200px)
    $containerStyle = 'height: 200px; display: flex; align-items: center; justify-content: center; overflow: hidden; background: #f8f9fa; border: 1px solid #dee2e6; border-radius: 4px;';

    // If PDF
    if ($mimeType === 'application/pdf') {
        return '<div style="' . $containerStyle . '">
                    <embed src="' . $src . '" type="application/pdf" width="100%" height="100%" />
                </div>
                <div class="mt-2 text-center">
                    <a href="' . $src . '" download="' . $title . '.pdf" class="btn btn-sm btn-outline-danger w-100"><i class="fas fa-file-pdf"></i> تحميل PDF</a>
                </div>';
    } 
    // If Image
    elseif (strpos($mimeType, 'image/') === 0) {
        // Added onclick event and cursor pointer
        return '<div style="' . $containerStyle . '">
                    <img src="' . $src . '" 
                         style="max-height: 100%; max-width: 100%; object-fit: contain; cursor: pointer;" 
                         alt="' . $title . '"
                         onclick="viewImage(this.src, \'' . $title . '\')"
                         title="انقر للعرض بحجم كامل">
                </div>
                <div class="mt-2 text-center">
                    <a href="' . $src . '" download="' . $title . '.jpg" class="btn btn-sm btn-outline-primary w-100"><i class="fas fa-download"></i> تحميل</a>
                </div>';
    } 
    // Unknown
    else {
        return '<div class="alert alert-secondary text-center mb-0"><small>نوع ملف غير مدعوم</small> <a href="' . $src . '" download>تحميل</a></div>';
    }
}
?>

<div class="content-area">
    <div class="page-header mb-4">
        <h2 class="page-title">ملف الطالب: <?php echo htmlspecialchars($student['full_name']); ?></h2>
        <nav aria-label="breadcrumb">
            <ol class="breadcrumb">
                <li class="breadcrumb-item"><a href="index.php">إدارة الطلاب</a></li>
                <li class="breadcrumb-item active">التفاصيل والوثائق</li>
            </ol>
        </nav>
    </div>

    <div class="card shadow-sm mb-4">
        <div class="card-header bg-primary text-white">
            <h5 class="mb-0"><i class="fas fa-user-circle me-2"></i> المعلومات الشخصية والأكاديمية</h5>
        </div>
        <div class="card-body">
            <div class="row g-3">
                <div class="col-md-3 col-6">
                    <label class="text-muted small">الرقم الوطني</label>
                    <div class="fw-bold"><?php echo htmlspecialchars($student['national_id_number']); ?></div>
                </div>
                <div class="col-md-3 col-6">
                    <label class="text-muted small">الكلية</label>
                    <div class="fw-bold"><?php echo htmlspecialchars($student['College']); ?></div>
                </div>
                <div class="col-md-3 col-6">
                    <label class="text-muted small">القسم</label>
                    <div class="fw-bold"><?php echo htmlspecialchars($student['Departement']); ?></div>
                </div>
                <div class="col-md-3 col-6">
                    <label class="text-muted small">المرحلة الدراسية</label>
                    <div class="fw-bold text-primary"><?php echo htmlspecialchars($student['grade_level']); ?></div>
                </div>

                <div class="col-12"><hr class="my-1"></div>

                <div class="col-md-3 col-6">
                    <label class="text-muted small">تاريخ التسجيل</label>
                    <div><?php echo htmlspecialchars($student['enrollment_date']); ?></div>
                </div>
                <div class="col-md-3 col-6">
                    <label class="text-muted small">الجنس</label>
                    <div><?php echo ($student['gender'] === 'male') ? 'ذكر' : 'أنثى'; ?></div>
                </div>
                <div class="col-md-3 col-6">
                    <label class="text-muted small">نوع القبول</label>
                    <div><?php echo htmlspecialchars($student['addmission']); ?></div>
                </div>
                <div class="col-md-3 col-6">
                    <label class="text-muted small">الحالة</label>
                    <div>
                        <?php if ($student['status'] == 1): ?>
                            <span class="badge bg-success">نشط / مستمر</span>
                        <?php else: ?>
                            <span class="badge bg-secondary">منقطع / مؤجل</span>
                        <?php endif; ?>
                    </div>
                </div>

                 <div class="col-12"><hr class="my-1"></div>

                <div class="col-md-3 col-6">
                    <label class="text-muted small">التكلفة السنوية</label>
                    <div class="text-success fw-bold"><?php echo number_format((float)$student['Yearly_Cost']); ?> د.ع</div>
                </div>
            </div>
        </div>
    </div>

    <?php if ($docs): ?>
    <div class="row g-3">
        <div class="col-12"><h5 class="text-muted border-bottom pb-2 mb-3">الوثائق المرفقة</h5></div>

        <div class="col-xl-3 col-md-4 col-sm-6">
            <div class="card h-100 shadow-sm border-0">
                <div class="card-header bg-dark text-white py-1 text-center">
                    <small><i class="fas fa-file-alt me-1"></i> الوثيقة المدرسية</small>
                </div>
                <div class="card-body p-2">
                    <?php echo renderDoc($docs['School_doc'], 'School_Document'); ?>
                </div>
            </div>
        </div>

        <div class="col-xl-3 col-md-4 col-sm-6">
            <div class="card h-100 shadow-sm border-0">
                <div class="card-header bg-dark text-white py-1 text-center">
                    <small><i class="fas fa-id-card me-1"></i> الهوية الوطنية</small>
                </div>
                <div class="card-body p-2">
                    <?php echo renderDoc($docs['National_ID_Card'], 'National_ID'); ?>
                </div>
            </div>
        </div>

        <div class="col-xl-3 col-md-4 col-sm-6">
            <div class="card h-100 shadow-sm border-0">
                <div class="card-header bg-secondary text-white py-1 text-center">
                    <small><i class="fas fa-user-md me-1"></i> الفحص الطبي</small>
                </div>
                <div class="card-body p-2">
                    <?php echo renderDoc($docs['Medical_exam'], 'Medical_Exam'); ?>
                </div>
            </div>
        </div>

        <div class="col-xl-3 col-md-4 col-sm-6">
            <div class="card h-100 shadow-sm border-0">
                <div class="card-header bg-secondary text-white py-1 text-center">
                    <small><i class="fas fa-clipboard-list me-1"></i> بطاقة الوزاري</small>
                </div>
                <div class="card-body p-2">
                    <?php echo renderDoc($docs['Ministry_exam_card'], 'Ministry_Exam_Card'); ?>
                </div>
            </div>
        </div>
    </div>
    <?php else: ?>
        <div class="alert alert-warning text-center mt-4">
            <h4><i class="fas fa-exclamation-triangle"></i> لا توجد وثائق محفوظة لهذا الطالب.</h4>
        </div>
    <?php endif; ?>
    
    <div class="mt-5 text-end">
        <a href="edit_student.php?id=<?php echo $student_id; ?>" class="btn btn-warning px-4"><i class="fas fa-edit"></i> تعديل البيانات</a>
        <a href="index.php" class="btn btn-secondary px-4">عودة للقائمة</a>
    </div>
</div>

<div class="modal fade" id="imagePreviewModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-fullscreen">
        <div class="modal-content bg-dark">
            <div class="modal-header border-0 bg-black">
                <h5 class="modal-title text-white" id="imagePreviewTitle">عرض الصورة</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body d-flex justify-content-center align-items-center" style="background-color: #222;">
                <img id="imagePreviewFull" src="" class="img-fluid" style="max-height: 90vh; max-width: 90vw; object-fit: contain; box-shadow: 0 0 20px rgba(0,0,0,0.5);">
            </div>
        </div>
    </div>
</div>

<script>
// Function to open the modal with the image
function viewImage(src, title) {
    var modalImg = document.getElementById('imagePreviewFull');
    var modalTitle = document.getElementById('imagePreviewTitle');
    
    modalImg.src = src;
    modalTitle.textContent = title;
    
    var myModal = new bootstrap.Modal(document.getElementById('imagePreviewModal'));
    myModal.show();
}
</script>

<?php include '../../includes/footer.php'; ?>