<?php
// print_medical_certificate.php
error_reporting(E_ALL);
ini_set('display_errors', 1);

require 'db.php';
require 'helpers.php';
require_committee(); // Using same authentication as committee

// Function to get the best available image for a student
function getStudentPhoto($student_id) {
    // Define the upload directory
    $upload_dir = "IDCard/uploads/";
    
    // Define preferred image formats in order of preference
    $preferred_formats = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
    
    // Check for images with student_id as filename
    foreach ($preferred_formats as $format) {
        $filename = $student_id . '.' . $format;
        $filepath = $upload_dir . $filename;
        
        if (file_exists($filepath)) {
            return [
                'path' => $filepath,
                'format' => $format,
                'filename' => $filename
            ];
        }
    }
    
    // Check for images with student_id followed by underscore or dash
    $patterns = [
        $student_id . '_*.{jpg,jpeg,png,gif,webp,bmp}',
        $student_id . '-*.{jpg,jpeg,png,gif,webp,bmp}',
        $student_id . '*.{jpg,jpeg,png,gif,webp,bmp}'
    ];
    
    foreach ($patterns as $pattern) {
        $files = glob($upload_dir . $pattern, GLOB_BRACE);
        if (!empty($files)) {
            // Sort by modification time (newest first)
            usort($files, function($a, $b) {
                return filemtime($b) - filemtime($a);
            });
            
            $filepath = $files[0];
            $filename = basename($filepath);
            $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
            
            return [
                'path' => $filepath,
                'format' => $extension,
                'filename' => $filename
            ];
        }
    }
    
    // No image found
    return null;
}

// Get student IDs from GET parameter (comma-separated)
$student_ids = isset($_GET['student_ids']) ? $_GET['student_ids'] : '';
$student_ids_array = $student_ids ? explode(',', $student_ids) : [];

// If no students selected, redirect back
if (empty($student_ids_array)) {
    header('Location: medical_certificate_dashboard.php');
    exit;
}

// Prepare the database connection
$mysqli1->set_charset('utf8mb4');
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

// Build a safe query that works with your database structure
$placeholders = str_repeat('?,', count($student_ids_array) - 1) . '?';

// First, check database structure
$hasProgramsTable = $mysqli1->query("SHOW TABLES LIKE 'programs'")->num_rows > 0;
$hasProgramInStudents = $mysqli1->query("SHOW COLUMNS FROM students LIKE 'program_id'")->num_rows > 0;
$hasProgramInBatches = $mysqli1->query("SHOW COLUMNS FROM batches LIKE 'program_id'")->num_rows > 0;

// NEW: Check for specializations
$hasSpecializationsTable = $mysqli1->query("SHOW TABLES LIKE 'specializations'")->num_rows > 0;
$hasSpecializationInStudents = $mysqli1->query("SHOW COLUMNS FROM students LIKE 'specialization_id'")->num_rows > 0;

// بناء الاستعلام بناءً على هيكل قاعدة البيانات
$select_fields = "
    s.student_id,
    s.student_name,
    s.student_name_eng,
    s.national_id,
    s.college_id,
    s.section_id,
    s.batch_id,
    s.program_id,
    s.specialization_id,
    s.interview_status,
    s.medically_fit,
    s.profile_completed,
    sec.name AS section_name,
    b.value AS batch_name,
    c.name AS college_name
";

// إضافة حقل program_id إذا كان موجوداً في جدول الطلاب
if ($hasProgramInStudents) {
    $select_fields .= ", s.program_id";
}

// Check if medical columns exist
try {
    $medical_columns = $mysqli1->query("SHOW COLUMNS FROM students LIKE 'medical_%'");
    $hasMedicalColumns = $medical_columns->num_rows > 0;
    
    // Add medical columns if they exist
    if ($hasMedicalColumns) {
        $medical_columns_result = $mysqli1->query("SELECT COLUMN_NAME 
                                                  FROM INFORMATION_SCHEMA.COLUMNS 
                                                  WHERE TABLE_NAME = 'students' 
                                                  AND TABLE_SCHEMA = DATABASE()
                                                  AND COLUMN_NAME LIKE 'medical_%'");
        
        while ($column = $medical_columns_result->fetch_assoc()) {
            $select_fields .= ", s." . $column['COLUMN_NAME'];
        }
    }
} catch (Exception $e) {
    $hasMedicalColumns = false;
}

$query = "
    SELECT $select_fields
    FROM students s
    LEFT JOIN sections sec ON sec.id = s.section_id
    LEFT JOIN batches b ON b.id = s.batch_id
    LEFT JOIN colleges c ON c.id = s.college_id
    WHERE s.student_id IN ($placeholders)
    ORDER BY s.student_id
";

try {
    $stmt = $mysqli1->prepare($query);
    if (!$stmt) {
        throw new Exception("خطأ في إعداد الاستعلام: " . $mysqli1->error);
    }
    
    // Bind parameters correctly
    $types = str_repeat('s', count($student_ids_array));
    $params = array_merge([$types], $student_ids_array);
    
    // Use call_user_func_array to bind parameters
    $refs = [];
    foreach($params as $key => $value) {
        $refs[$key] = &$params[$key];
    }
    
    call_user_func_array([$stmt, 'bind_param'], $refs);
    
    $stmt->execute();
    $students_result = $stmt->get_result();
    $students = $students_result->fetch_all(MYSQLI_ASSOC);
    $stmt->close();
} catch (Exception $e) {
    die("خطأ في جلب البيانات: " . $e->getMessage());
}

// الحصول على صورة الطالب
foreach ($students as &$student) {
    $student['photo'] = getStudentPhoto($student['student_id']);
    
    // تعيين قيم افتراضية للحقول الطبية إذا لم تكن موجودة
    if (!isset($student['medical_diagnosis'])) {
        $student['medical_diagnosis'] = null;
    }
    if (!isset($student['doctor_decision'])) {
        $student['doctor_decision'] = null;
    }
    if (!isset($student['medical_notes'])) {
        $student['medical_notes'] = null;
    }
    if (!isset($student['medical_date'])) {
        $student['medical_date'] = null;
    }
}

// دالة لتنسيق التاريخ باللغة العربية
function formatArabicDate($date) {
    if (empty($date)) {
        return null;
    }
    
    $months_arabic = [
        'January' => 'يناير',
        'February' => 'فبراير',
        'March' => 'مارس',
        'April' => 'أبريل',
        'May' => 'مايو',
        'June' => 'يونيو',
        'July' => 'يوليو',
        'August' => 'أغسطس',
        'September' => 'سبتمبر',
        'October' => 'أكتوبر',
        'November' => 'نوفمبر',
        'December' => 'ديسمبر'
    ];
    
    $timestamp = strtotime($date);
    $day = date('d', $timestamp);
    $month = date('F', $timestamp);
    $year = date('Y', $timestamp);
    
    return $day . ' ' . $months_arabic[$month] . ' ' . $year;
}

// دالة لتحديد حالة الطبية
function getMedicalStatus($medically_fit) {
    switch($medically_fit) {
        case 'yes':
            return ['text' => 'لائق طبياً', 'class' => 'status-green', 'icon' => 'fa-check-circle'];
        case 'no':
            return ['text' => 'غير لائق طبياً', 'class' => 'status-red', 'icon' => 'fa-times-circle'];
        case 'pending':
            return ['text' => 'في انتظار الفحص', 'class' => 'status-yellow', 'icon' => 'fa-clock'];
        default:
            return ['text' => 'لم يتم الفحص', 'class' => 'status-blue', 'icon' => 'fa-question-circle'];
    }
}

// تنسيق التواريخ
foreach ($students as &$student) {
    $student['medical_date_formatted'] = formatArabicDate($student['medical_date']);
    $student['medical_status'] = getMedicalStatus($student['medically_fit']);
    $student['today_date'] = formatArabicDate(date('Y-m-d'));
}

// الحصول على أسماء البرامج للطلاب
foreach ($students as &$student) {
    $student['program_name'] = null; // قيمة افتراضية
    $student['specialization_name'] = null; // NEW: قيمة افتراضية للتخصص
    
    // الحصول على اسم البرنامج
    if ($hasProgramsTable && $hasProgramInStudents && !empty($student['program_id'])) {
        $program_query = "SELECT name FROM programs WHERE id = ?";
        $program_stmt = $mysqli1->prepare($program_query);
        if ($program_stmt) {
            $program_stmt->bind_param('i', $student['program_id']);
            $program_stmt->execute();
            $program_result = $program_stmt->get_result()->fetch_assoc();
            $program_stmt->close();
            
            if ($program_result) {
                $student['program_name'] = $program_result['name'];
            }
        }
    }
    else if ($hasProgramsTable && $hasProgramInBatches && !empty($student['batch_id'])) {
        $batch_program_query = "SELECT p.name 
                               FROM batches b 
                               LEFT JOIN programs p ON p.id = b.program_id 
                               WHERE b.id = ?";
        $batch_program_stmt = $mysqli1->prepare($batch_program_query);
        if ($batch_program_stmt) {
            $batch_program_stmt->bind_param('i', $student['batch_id']);
            $batch_program_stmt->execute();
            $batch_program_result = $batch_program_stmt->get_result()->fetch_assoc();
            $batch_program_stmt->close();
            
            if ($batch_program_result && $batch_program_result['name']) {
                $student['program_name'] = $batch_program_result['name'];
            }
        }
    }
    else if ($hasProgramsTable && !empty($student['section_id'])) {
        $section_program_query = "SELECT p.name 
                                 FROM sections s 
                                 LEFT JOIN programs p ON p.id = s.program_id 
                                 WHERE s.id = ?";
        $section_program_stmt = $mysqli1->prepare($section_program_query);
        if ($section_program_stmt) {
            $section_program_stmt->bind_param('i', $student['section_id']);
            $section_program_stmt->execute();
            $section_program_result = $section_program_stmt->get_result()->fetch_assoc();
            $section_program_stmt->close();
            
            if ($section_program_result && $section_program_result['name']) {
                $student['program_name'] = $section_program_result['name'];
            }
        }
    }
    
    // NEW: الحصول على اسم التخصص
    if ($hasSpecializationsTable && $hasSpecializationInStudents && !empty($student['specialization_id'])) {
        $spec_query = "SELECT specialization_name_ar FROM specializations WHERE specialization_id = ?";
        $spec_stmt = $mysqli1->prepare($spec_query);
        if ($spec_stmt) {
            $spec_stmt->bind_param('i', $student['specialization_id']);
            $spec_stmt->execute();
            $spec_result = $spec_stmt->get_result()->fetch_assoc();
            $spec_stmt->close();
            
            if ($spec_result) {
                $student['specialization_name'] = $spec_result['specialization_name_ar'];
            }
        }
    }
}

// University information for الجامعة الوطنية
$university_info = [
    'name' => 'الجامعة الوطنية',
    'arabic_name' => 'الجامعة الوطنية',
    'medical_unit' => 'ادارة الخدمات الصحية ',
    'address' => 'السودان- ودمدني',
    'phone' => '00249-155772782 ',
    'website' => 'nu.edu.sd',
    'motto' => 'القمة الأخرى للتعليم العالي في السودان'
];
?>

<!DOCTYPE html>
<html dir="rtl" lang="ar">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>شهادة طبية - الجامعة الوطنية</title>
    <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@300;400;600;700;800&display=swap" rel="stylesheet">
    <style>
        /* Half A4 Page Size (148mm x 105mm per half) */
        @page {
            size: A4;
            margin: 0;
        }
        
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Cairo', sans-serif;
            background: #f5f5f5;
            color: #333;
            line-height: 1.4;
            -webkit-print-color-adjust: exact;
            print-color-adjust: exact;
            font-size: 10px;
        }
        
        /* Main container for A4 page with two halves */
        .page-container {
            width: 210mm;
            height: 297mm;
            margin: 0 auto;
            background: white;
            position: relative;
        }
        
        /* Half Page Certificate Container */
        .certificate-container {
            width: 100%;
            height: 50%; /* نصف الصفحة */
            position: relative;
            border-bottom: 1px dashed #ccc;
            padding: 8mm;
            overflow: hidden;
            page-break-inside: avoid;
        }
        
        .certificate-container:last-child {
            border-bottom: none;
        }
        
        /* Certificate inner box */
        .certificate-inner {
            width: 100%;
            height: 100%;
            border: 2px solid #1a5276;
            border-radius: 8px;
            position: relative;
            overflow: hidden;
            background: white;
            padding: 5px;
        }
        
        /* Background watermark */
        .watermark {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%) rotate(-45deg);
            font-size: 30px;
            color: rgba(26, 82, 118, 0.1);
            font-weight: 900;
            white-space: nowrap;
            z-index: 1;
            pointer-events: none;
        }
        
        /* Header Section - Compact */
        .header-section {
            text-align: center;
            margin-bottom: 5px;
            padding-bottom: 3px;
            border-bottom: 1px solid #1a5276;
        }
        
        .university-name {
            font-size: 14px;
            font-weight: 900;
            color: #1a5276;
            margin-bottom: 1px;
        }
        
        .medical-unit {
            font-size: 11px;
            color: #d35400;
            margin-bottom: 2px;
            font-weight: 700;
        }
        
        .certificate-title {
            font-size: 12px;
            font-weight: 800;
            color: #d35400;
            margin: 2px 0;
        }
        
        .certificate-number {
            background: #1a5276;
            color: white;
            padding: 2px 8px;
            border-radius: 3px;
            display: inline-block;
            margin: 2px auto;
            font-weight: 600;
            font-size: 9px;
        }
        
        /* Date section */
        .date-section {
            background: #fff3e0;
            border: 1px solid #ff9800;
            border-radius: 4px;
            padding: 3px 5px;
            margin: 3px 0;
            text-align: center;
            font-size: 9px;
        }
        
        /* Student info with photo */
        .student-info-with-photo {
            display: grid;
            grid-template-columns: 25mm auto;
            gap: 4px;
            margin: 4px 0;
            align-items: start;
        }
        
        .student-photo-container {
            background: #f8f9fa;
            border: 1px solid #1a5276;
            border-radius: 5px;
            padding: 2px;
            text-align: center;
            height: 25mm;
        }
        
        .photo-label {
            font-size: 8px;
            color: #6c757d;
            font-weight: 600;
            margin-bottom: 1px;
        }
        
        .student-photo {
            width: 100%;
            height: 20mm;
            object-fit: contain;
            border: 1px solid #dee2e6;
            border-radius: 3px;
            background: #fff;
        }
        
        .no-photo {
            width: 100%;
            height: 22mm;
            background: #f0f0f0;
            border: 1px dashed #ccc;
            border-radius: 3px;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            color: #999;
            font-size: 8px;
        }
        
        .no-photo i {
            font-size: 14px;
            margin-bottom: 2px;
        }
        
        /* Student info header */
        .student-info-header {
            padding: 3px;
        }
        
        .student-name-large {
            font-size: 14px;
            font-weight: 800;
            color: #1a5276;
            margin-bottom: 3px;
            text-align: center;
        }
        
        /* Student info grid - 3 أعمدة */
        .student-info-grid {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 3px;
            margin: 3px 0;
        }
        
        .student-info-item {
            font-size: 8px;
        }
        
        .student-info-label {
            color: #666;
            font-weight: 700;
            margin-bottom: 1px;
        }
        
        .student-info-value {
            font-weight: 800;
            color: #1a5276;
            padding: 1px 3px;
            background: #f8f9fa;
            border-radius: 2px;
            border: 1px solid #dee2e6;
            font-size: 9px;
            min-height: 18px;
            display: flex;
            align-items: center;
        }
        
        /* حقل البرنامج يأخذ عمودين في الصف الثاني */
        .program-specialization-row {
            grid-column: span 3; /* يأخذ الصف كاملاً */
            margin-top: 2px;
        }
        
        .program-specialization-container {
            display: grid;
            grid-template-columns: 1fr 1fr; /* نصفين متساويين */
            gap: 3px;
        }
        
        .program-value {
            background: linear-gradient(135deg, #e3f2fd, #bbdefb);
            border-color: #2196f3;
            color: #0d47a1;
            font-weight: 900;
        }
        
        /* NEW: Specialization styling */
        .specialization-value {
            background: linear-gradient(135deg, #f3e8ff, #e9d5ff);
            border-color: #9333ea;
            color: #6b21a8;
            font-weight: 900;
        }
        
        .batch-value {
            background: linear-gradient(135deg, #e8f5e9, #c8e6c9);
            border-color: #4caf50;
            color: #1b5e20;
            font-weight: 900;
        }
        
        /* الصف الثالث: الدفعة */
        .batch-row {
            grid-column: span 3;
        }
        
        /* Medical sections */
        .medical-section {
            margin: 4px 0;
        }
        
        .medical-section-title {
            background: #1a5276;
            color: white;
            padding: 3px 5px;
            border-radius: 3px;
            text-align: center;
            font-weight: 800;
            font-size: 10px;
            margin-bottom: 3px;
        }
        
        .blank-lines {
            background: white;
            border: 1px dashed #666;
            border-radius: 4px;
            min-height: 20mm;
            padding: 3px;
        }
        
        .blank-line {
            height: 1px;
            background: repeating-linear-gradient(
                to right,
                #ccc 0px,
                #ccc 3px,
                transparent 3px,
                transparent 7px
            );
            margin: 15px 0;
        }
        
        /* Doctor decision section */
        .doctor-decision-section {
            margin: 4px 0;
        }
        
        .doctor-decision-title {
            font-size: 10px;
            color: #1b5e20;
            font-weight: 800;
            margin-bottom: 3px;
            display: flex;
            align-items: center;
            gap: 5px;
        }
        
        .doctor-decision-content {
            padding: 3px;
            background: white;
            border-radius: 4px;
            border: 1px dashed #4caf50;
            min-height: 20mm;
        }
        
        /* Signature section */
        .signature-section {
            margin-top: 8px;
            text-align: center;
        }
        
        .signature-line {
            width: 60%;
            height: 1px;
            background: #333;
            margin: 15px auto 2px auto;
        }
        
        .signature-label {
            font-size: 10px;
            color: #1a5276;
            font-weight: 800;
        }
        
        /* Footer */
        .footer-section {
            margin-top: 5px;
            padding-top: 3px;
            border-top: 1px solid #eee;
            text-align: center;
        }
        
        .footer-info {
            display: flex;
            justify-content: space-around;
            font-size: 8px;
            color: #6c757d;
            margin-bottom: 3px;
        }
        
        .print-date {
            font-size: 7px;
            color: #495057;
            font-weight: 700;
        }
        
        /* Control Buttons (Non-print) */
        .control-buttons {
            position: fixed;
            top: 10px;
            left: 10px;
            z-index: 1000;
            display: flex;
            gap: 5px;
            background: white;
            padding: 5px;
            border-radius: 5px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.15);
        }
        
        .btn {
            padding: 4px 8px;
            border: none;
            border-radius: 4px;
            font-family: 'Cairo', sans-serif;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.2s ease;
            display: inline-flex;
            align-items: center;
            gap: 4px;
            font-size: 10px;
        }
        
        .btn-print {
            background: #1a5276;
            color: white;
        }
        
        .btn-print:hover {
            background: #154360;
        }
        
        .btn-back {
            background: #95a5a6;
            color: white;
        }
        
        .btn-back:hover {
            background: #7f8c8d;
        }
        
        /* Print Styles */
        @media print {
            .control-buttons {
                display: none;
            }
            
            body {
                background: white;
                margin: 0;
                padding: 0;
            }
            
            .page-container {
                box-shadow: none;
                margin: 0;
                padding: 0;
                width: 210mm;
                height: 297mm;
            }
            
            .certificate-container {
                padding: 8mm;
            }
            
            /* Add cut line between halves */
            .certificate-container:first-child::after {
                content: '';
                position: absolute;
                bottom: 0;
                left: 5%;
                right: 5%;
                height: 1px;
                background: repeating-linear-gradient(
                    to right,
                    transparent 0px,
                    transparent 5px,
                    #ccc 5px,
                    #ccc 10px
                );
                z-index: 10;
            }
            
            /* Add cut line indicator text */
            .certificate-container:first-child::before {
                content: '━━━━━━━━━━━━━━━ قص هنا ━━━━━━━━━━━━━━━';
                position: absolute;
                bottom: -3px;
                left: 50%;
                transform: translateX(-50%);
                font-size: 10px;
                color: #999;
                background: white;
                padding: 0 5px;
                z-index: 11;
                white-space: nowrap;
            }
        }
        
        /* Responsive adjustments */
        @media screen and (max-width: 210mm) {
            .page-container {
                width: 100%;
                height: auto;
                min-height: 297mm;
            }
        }
        
        /* Additional styles */
        .empty-value {
            color: #adb5bd;
            font-style: italic;
            font-weight: normal;
        }
        
        .info-icon {
            margin-left: 3px;
            font-size: 9px;
        }
    </style>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
</head>
<body>
    <!-- Control Buttons (Non-print) -->
    <div class="control-buttons no-print">
        <button class="btn btn-print" onclick="window.print()">
            <i class="fas fa-print"></i> طباعة
        </button>
        <button class="btn btn-back" onclick="window.history.back()">
            <i class="fas fa-arrow-right"></i> رجوع
        </button>
        <button class="btn btn-back" onclick="window.location.href='medical_certificate_dashboard.php'">
            <i class="fas fa-home"></i> لوحة التحكم
        </button>
    </div>
    
    <?php if (empty($students)): ?>
        <div style="text-align: center; padding: 50px; color: #d32f2f;">
            <h3><i class="fas fa-exclamation-triangle"></i> لم يتم العثور على بيانات الطلاب</h3>
            <p>يرجى التحقق من الأرقام الجامعية المحددة</p>
        </div>
    <?php else: ?>
        <?php 
        // Group students two per page (each student appears twice on the same page)
        $pages = array_chunk($students, 1); // One student per page (but appears twice)
        ?>
        
        <?php foreach ($pages as $page_students): ?>
            <?php foreach ($page_students as $student): ?>
                <!-- Page container with two halves -->
                <div class="page-container">
                    <!-- Top Half (First Copy) -->
                    <div class="certificate-container">
                        <div class="certificate-inner">
                            <div class="watermark">شهادة طبية</div>
                            
                            <!-- Header -->
                            <div class="header-section">
                                <h1 class="university-name"><?= e($university_info['name']) ?></h1>
                                <div class="medical-unit"><?= e($university_info['medical_unit']) ?></div>
                                <h3 class="certificate-title">شهادة طبية</h3>
                                <div class="certificate-number">
                                    <i class="fas fa-file-medical"></i>
                                    رقم: <?= strtoupper(substr(md5($student['student_id'] . time()), 0, 6)) ?>
                                </div>
                            </div>
                            
                            <!-- Date -->
                            <div class="date-section">
                                <i class="fas fa-calendar-day"></i>
                                تاريخ اليوم: <?= e($student['today_date']) ?>
                            </div>
                            
                            <!-- Student Info with Photo -->
                            <div class="student-info-with-photo">
                                <!-- Student Photo -->
                                <div class="student-photo-container">
                                    <div class="photo-label">صورة الطالب</div>
                                    <?php if (!empty($student['photo'])): ?>
                                        <img src="<?= e($student['photo']['path']) ?>" 
                                             alt="صورة الطالب <?= e($student['student_name']) ?>"
                                             class="student-photo"
                                             onerror="this.onerror=null; this.src='data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTAwIiBoZWlnaHQ9IjEyMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48cmVjdCB3aWR0aD0iMTAwIiBoZWlnaHQ9IjEyMCIgZmlsbD0iI2YwZjBmMCIvPjx0ZXh0IHg9IjUwIiB5PSI2MCIgZm9udC1mYW1pbHk9IkFyaWFsIiBmb250LXNpemU9IjEyIiB0ZXh0LWFuY2hvcj0ibWlkZGxlIiBmaWxsPSIjOTk5Ij5ObyBQaG90bzwvdGV4dD48L3N2Zz4=';">
                                    <?php else: ?>
                                        <div class="no-photo">
                                            <i class="fas fa-user-circle"></i>
                                            <span>لا توجد صورة</span>
                                        </div>
                                    <?php endif; ?>
                                </div>
                                
                                <!-- Student Info -->
                                <div class="student-info-header">
                                    <div class="student-name-large">
                                        <i class="fas fa-user"></i>
                                        <?= e($student['student_name']) ?>
                                    </div>
                                    
                                    <div class="student-info-grid">
                                        <!-- الصف الأول: 3 حقول -->
                                        <div class="student-info-item">
                                            <div class="student-info-label">رقم الطالب:</div>
                                            <div class="student-info-value">
                                                <?= e($student['student_id']) ?>
                                            </div>
                                        </div>
                                        
                                        <div class="student-info-item">
                                            <div class="student-info-label">الكلية:</div>
                                            <div class="student-info-value">
                                                <?= !empty($student['college_name']) ? e($student['college_name']) : 'غير محدد' ?>
                                            </div>
                                        </div>
                                        
                                        <div class="student-info-item">
                                            <div class="student-info-label">القسم:</div>
                                            <div class="student-info-value">
                                                <?= !empty($student['section_name']) ? e($student['section_name']) : 'غير محدد' ?>
                                            </div>
                                        </div>
                                        
                                        <!-- الصف الثاني: البرنامج والتخصص في سطر واحد -->
                                        <div class="student-info-item program-specialization-row">
                                            <div class="program-specialization-container">
                                                <div>
                                                    <div class="student-info-label">البرنامج:</div>
                                                    <div class="student-info-value program-value">
                                                        <?php if (!empty($student['program_name'])): ?>
                                                            <i class="fas fa-book info-icon"></i>
                                                            <?= e($student['program_name']) ?>
                                                        <?php else: ?>
                                                            <span class="empty-value">غير محدد</span>
                                                        <?php endif; ?>
                                                    </div>
                                                </div>
                                                
                                                <!-- NEW: Specialization field -->
                                                <div>
                                                    <div class="student-info-label">التخصص:</div>
                                                    <div class="student-info-value specialization-value">
                                                        <?php if (!empty($student['specialization_name'])): ?>
                                                            <i class="fas fa-microscope info-icon"></i>
                                                            <?= e($student['specialization_name']) ?>
                                                        <?php else: ?>
                                                            <span class="empty-value">غير محدد</span>
                                                        <?php endif; ?>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <!-- الصف الثالث: الدفعة -->
                                        <div class="student-info-item batch-row">
                                            <div class="student-info-label">الدفعة:</div>
                                            <div class="student-info-value batch-value">
                                                <?php if (!empty($student['batch_name'])): ?>
                                                    <i class="fas fa-calendar-alt info-icon"></i>
                                                    دفعة <?= e($student['batch_name']) ?>
                                                <?php else: ?>
                                                    <span class="empty-value">غير محدد</span>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Diagnosis Section -->
                            <div class="medical-section">
                                <div class="medical-section-title">
                                    <i class="fas fa-stethoscope"></i>
                                    التشخيص الطبي:
                                </div>
                                <div class="blank-lines">
                                    <?php if (!empty($student['medical_diagnosis'])): ?>
                                        <div style="padding: 5px; font-size: 9px; line-height: 1.4;">
                                            <?= nl2br(e($student['medical_diagnosis'])) ?>
                                        </div>
                                    <?php else: ?>
                                        <div class="blank-line"></div> 
                                        <div class="blank-line"></div> 
                                        <div class="blank-line"></div>
                                    <?php endif; ?>
                                </div>
                            </div>
                            
                            <!-- Doctor Decision -->
                            <div class="doctor-decision-section">
                                <div class="doctor-decision-title">
                                    <i class="fas fa-user-md"></i>
                                    قرار الطبيب:
                                </div>
                                <div class="doctor-decision-content">
                                    <?php if (!empty($student['doctor_decision'])): ?>
                                        <div style="padding: 5px; font-size: 9px; line-height: 1.4;">
                                            <?= nl2br(e($student['doctor_decision'])) ?>
                                        </div>
                                    <?php else: ?>
                                        <div class="blank-lines">
                                            <div class="blank-line"></div>
                                            <div class="blank-line"></div>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                            
                            <!-- Doctor Signature -->
                            <div class="signature-section">
                                <div class="signature-line"></div>
                                <div class="signature-label">
                                    توقيع الطبيب - ادارة الخدمات الصحية
                                </div>
                            </div>
                            
                            <!-- Footer -->
                            <div class="footer-section">
                                <div class="footer-info">
                                    <div><i class="fas fa-map-marker-alt"></i> <?= e($university_info['address']) ?></div>
                                    <div><i class="fas fa-phone"></i> <?= e($university_info['phone']) ?></div>
                                    <div><i class="fas fa-globe"></i> <?= e($university_info['website']) ?></div>
                                </div>
                                <div class="print-date">تم الطباعة: <?= date('Y/m/d - h:i A') ?></div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Bottom Half (Second Copy - Same data) -->
                    <div class="certificate-container">
                        <div class="certificate-inner">
                            <div class="watermark">شهادة طبية</div>
                            
                            <!-- Header -->
                            <div class="header-section">
                                <h1 class="university-name"><?= e($university_info['name']) ?></h1>
                                <div class="medical-unit"><?= e($university_info['medical_unit']) ?></div>
                                <h3 class="certificate-title">شهادة طبية</h3>
                                <div class="certificate-number">
                                    <i class="fas fa-file-medical"></i>
                                    رقم: <?= strtoupper(substr(md5($student['student_id'] . time()), 0, 6)) ?>
                                </div>
                            </div>
                            
                            <!-- Date -->
                            <div class="date-section">
                                <i class="fas fa-calendar-day"></i>
                                تاريخ اليوم: <?= e($student['today_date']) ?>
                            </div>
                            
                            <!-- Student Info with Photo -->
                            <div class="student-info-with-photo">
                                <!-- Student Photo -->
                                <div class="student-photo-container">
                                    <div class="photo-label">صورة الطالب</div>
                                    <?php if (!empty($student['photo'])): ?>
                                        <img src="<?= e($student['photo']['path']) ?>" 
                                             alt="صورة الطالب <?= e($student['student_name']) ?>"
                                             class="student-photo"
                                             onerror="this.onerror=null; this.src='data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTAwIiBoZWlnaHQ9IjEyMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48cmVjdCB3aWR0aD0iMTAwIiBoZWlnaHQ9IjEyMCIgZmlsbD0iI2YwZjBmMCIvPjx0ZXh0IHg9IjUwIiB5PSI2MCIgZm9udC1mYW1pbHk9IkFyaWFsIiBmb250LXNpemU9IjEyIiB0ZXh0LWFuY2hvcj0ibWlkZGxlIiBmaWxsPSIjOTk5Ij5ObyBQaG90bzwvdGV4dD48L3N2Zz4=';">
                                    <?php else: ?>
                                        <div class="no-photo">
                                            <i class="fas fa-user-circle"></i>
                                            <span>لا توجد صورة</span>
                                        </div>
                                    <?php endif; ?>
                                </div>
                                
                                <!-- Student Info -->
                                <div class="student-info-header">
                                    <div class="student-name-large">
                                        <i class="fas fa-user"></i>
                                        <?= e($student['student_name']) ?>
                                    </div>
                                    
                                    <div class="student-info-grid">
                                        <!-- الصف الأول: 3 حقول -->
                                        <div class="student-info-item">
                                            <div class="student-info-label">رقم الطالب:</div>
                                            <div class="student-info-value">
                                                <?= e($student['student_id']) ?>
                                            </div>
                                        </div>
                                        
                                        <div class="student-info-item">
                                            <div class="student-info-label">الكلية:</div>
                                            <div class="student-info-value">
                                                <?= !empty($student['college_name']) ? e($student['college_name']) : 'غير محدد' ?>
                                            </div>
                                        </div>
                                        
                                        <div class="student-info-item">
                                            <div class="student-info-label">القسم:</div>
                                            <div class="student-info-value">
                                                <?= !empty($student['section_name']) ? e($student['section_name']) : 'غير محدد' ?>
                                            </div>
                                        </div>
                                        
                                        <!-- الصف الثاني: البرنامج والتخصص في سطر واحد -->
                                        <div class="student-info-item program-specialization-row">
                                            <div class="program-specialization-container">
                                                <div>
                                                    <div class="student-info-label">البرنامج:</div>
                                                    <div class="student-info-value program-value">
                                                        <?php if (!empty($student['program_name'])): ?>
                                                            <i class="fas fa-book info-icon"></i>
                                                            <?= e($student['program_name']) ?>
                                                        <?php else: ?>
                                                            <span class="empty-value">غير محدد</span>
                                                        <?php endif; ?>
                                                    </div>
                                                </div>
                                                
                                                <!-- NEW: Specialization field -->
                                                <div>
                                                    <div class="student-info-label">التخصص:</div>
                                                    <div class="student-info-value specialization-value">
                                                        <?php if (!empty($student['specialization_name'])): ?>
                                                            <i class="fas fa-microscope info-icon"></i>
                                                            <?= e($student['specialization_name']) ?>
                                                        <?php else: ?>
                                                            <span class="empty-value">غير محدد</span>
                                                        <?php endif; ?>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <!-- الصف الثالث: الدفعة -->
                                        <div class="student-info-item batch-row">
                                            <div class="student-info-label">الدفعة:</div>
                                            <div class="student-info-value batch-value">
                                                <?php if (!empty($student['batch_name'])): ?>
                                                    <i class="fas fa-calendar-alt info-icon"></i>
                                                    دفعة <?= e($student['batch_name']) ?>
                                                <?php else: ?>
                                                    <span class="empty-value">غير محدد</span>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Diagnosis Section -->
                            <div class="medical-section">
                                <div class="medical-section-title">
                                    <i class="fas fa-stethoscope"></i>
                                    التشخيص الطبي:
                                </div>
                                <div class="blank-lines">
                                    <?php if (!empty($student['medical_diagnosis'])): ?>
                                        <div style="padding: 5px; font-size: 9px; line-height: 1.4;">
                                            <?= nl2br(e($student['medical_diagnosis'])) ?>
                                        </div>
                                    <?php else: ?>
                                        <div class="blank-line"></div>
                                        <div class="blank-line"></div>
                                        <div class="blank-line"></div>
                                    <?php endif; ?>
                                </div>
                            </div>
                            
                            <!-- Doctor Decision -->
                            <div class="doctor-decision-section">
                                <div class="doctor-decision-title">
                                    <i class="fas fa-user-md"></i>
                                    قرار الطبيب:
                                </div>
                                <div class="doctor-decision-content">
                                    <?php if (!empty($student['doctor_decision'])): ?>
                                        <div style="padding: 5px; font-size: 9px; line-height: 1.4;">
                                            <?= nl2br(e($student['doctor_decision'])) ?>
                                        </div>
                                    <?php else: ?>
                                        <div class="blank-lines">
                                            <div class="blank-line"></div>
                                            <div class="blank-line"></div>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                            
                            <!-- Doctor Signature -->
                            <div class="signature-section">
                                <div class="signature-line"></div>
                                <div class="signature-label">
                                    توقيع الطبيب - ادارة الخدمات الصحية
                                </div>
                            </div>
                            
                            <!-- Footer -->
                            <div class="footer-section">
                                <div class="footer-info">
                                    <div><i class="fas fa-map-marker-alt"></i> <?= e($university_info['address']) ?></div>
                                    <div><i class="fas fa-phone"></i> <?= e($university_info['phone']) ?></div>
                                    <div><i class="fas fa-globe"></i> <?= e($university_info['website']) ?></div>
                                </div>
                                <div class="print-date">تم الطباعة: <?= date('Y/m/d - h:i A') ?></div>
                            </div>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        <?php endforeach; ?>
    <?php endif; ?>
    
    <script>
        // Auto-print if specified in URL
        const urlParams = new URLSearchParams(window.location.search);
        if (urlParams.has('auto_print') && urlParams.get('auto_print') === '1') {
            window.addEventListener('load', function() {
                setTimeout(function() {
                    window.print();
                }, 500);
            });
        }
        
        // Keyboard shortcuts
        document.addEventListener('keydown', function(e) {
            if ((e.ctrlKey || e.metaKey) && e.key === 'p') {
                e.preventDefault();
                window.print();
            }
            if (e.key === 'Escape') {
                window.history.back();
            }
        });
        
        // Print events
        window.addEventListener('beforeprint', function() {
            console.log('جاري التحضير للطباعة...');
            document.querySelectorAll('.no-print').forEach(el => {
                el.style.display = 'none';
            });
        });
        
        window.addEventListener('afterprint', function() {
            console.log('تمت الطباعة بنجاح');
            document.querySelectorAll('.no-print').forEach(el => {
                el.style.display = '';
            });
            if (urlParams.has('auto_print')) {
                setTimeout(() => window.close(), 1000);
            }
        });
        
        // Show cut line instruction
        document.addEventListener('DOMContentLoaded', function() {
            if (!urlParams.has('auto_print')) {
                console.log('ملاحظة: سيتم طباعة صفحة A4 تحتوي على نسختين من الشهادة.');
                console.log('بعد الطباعة، يمكن قص الصفحة من المنتصف للحصول على نسختين منفصلتين.');
            }
        });
    </script>
</body>
</html>
