<?php
// print_registration_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: registration_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;

// بناء الاستعلام بناءً على هيكل قاعدة البيانات
$select_fields = "
    s.student_id,
    s.student_name,
    s.national_id,
    s.college_id,
    s.section_id,
    s.batch_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";
}

$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());
}

// Get last semester and registration date for each student
foreach ($students as &$student) {
    // الحصول على آخر فصل دراسي وتاريخ التسجيل
    $reg_query = "SELECT MAX(semester_id) as max_semester, MAX(start) as registration_date 
                  FROM registrations 
                  WHERE student_id = ?";
    $reg_stmt = $mysqli1->prepare($reg_query);
    if ($reg_stmt) {
        $reg_stmt->bind_param('s', $student['student_id']);
        $reg_stmt->execute();
        $reg_result = $reg_stmt->get_result()->fetch_assoc();
        $reg_stmt->close();
        
        $student['last_semester'] = $reg_result['max_semester'] ?? null;
        $student['registration_date'] = $reg_result['registration_date'] ?? null;
    } else {
        $student['last_semester'] = null;
        $student['registration_date'] = null;
    }
    
    // الحصول على صورة الطالب
    $student['photo'] = getStudentPhoto($student['student_id']);
}

// دالة لتحويل رقم الفصل الدراسي إلى كلمة عربية
function convertSemesterToArabic($semester) {
    if (empty($semester)) {
        return null;
    }
    
    // استخراج الرقم من النص إذا كان النص يحتوي على أرقام وكلمات
    preg_match('/\d+/', $semester, $matches);
    $number = isset($matches[0]) ? (int)$matches[0] : (int)$semester;
    
    // تحويل الرقم إلى كلمة عربية
    $arabic_numbers = [
        1 => 'الأول',
        2 => 'الثاني',
        3 => 'الثالث',
        4 => 'الرابع',
        5 => 'الخامس',
        6 => 'السادس',
        7 => 'السابع',
        8 => 'الثامن',
        9 => 'التاسع',
        10 => 'العاشر',
        11 => 'الحادي عشر',
        12 => 'الثاني عشر',
        13 => 'الثالث عشر',
        14 => 'الرابع عشر',
        15 => 'الخامس عشر'
    ];
    
    return isset($arabic_numbers[$number]) ? $arabic_numbers[$number] : $semester;
}

// دالة لتنسيق التاريخ باللغة العربية
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;
}

// تحويل الفصول الدراسية إلى كلمات عربية
foreach ($students as &$student) {
    $student['last_semester_arabic'] = convertSemesterToArabic($student['last_semester']);
    $student['registration_date_formatted'] = formatArabicDate($student['registration_date']);
}

// الحصول على أسماء البرامج للطلاب
foreach ($students as &$student) {
    $student['program_name'] = null; // قيمة افتراضية
    
    // الطريقة 1: إذا كان هناك جدول برامج وحقل program_id في الطلاب
    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'];
            }
        }
    }
    // الطريقة 2: إذا كان حقل program_id في جدول الدفعات
    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'];
            }
        }
    }
    // الطريقة 3: محاولة الحصول من أي مصدر آخر
    else if ($hasProgramsTable) {
        // محاولة الحصول على البرنامج من خلال القسم
        if (!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'];
                }
            }
        }
    }
}

// University information for الجامعة الوطنية
$university_info = [
    'name' => 'الجامعة الوطنية',
    'arabic_name' => 'الجامعة الوطنية',
    'academic_affairs' => 'أمانة الشؤون العلمية',
    '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 210mm) - Compact Design */
        @page {
            size: A4;
            margin: 5mm;
        }
        
        * {
            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: 12px;
            padding: 5mm;
        }
        
        /* Certificate Container - Compact Half A4 */
        .certificate-container {
            width: 138mm; /* 148mm - margins */
            height: 200mm; /* 210mm - margins */
            margin: 0 15mm 15mm 0;
            background: white;
            position: relative;
            page-break-inside: avoid;
            box-shadow: 0 0 5px rgba(0,0,0,0.1);
            border: 2px solid #1a5276;
            border-radius: 8px;
            overflow: hidden;
        }
        
        /* Certificate Background */
        .watermark {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%) rotate(-45deg);
            font-size: 50px;
            color: rgba(26, 82, 118, 0.1);
            font-weight: 900;
            white-space: nowrap;
            z-index: 1;
        }
        
        .border-design {
            position: absolute;
            top: 3px;
            left: 3px;
            right: 3px;
            bottom: 3px;
            border: 1px solid #1a5276;
            z-index: 1;
            border-radius: 5px;
            pointer-events: none;
        }
        
        /* Certificate Content - Compact Layout */
        .certificate-content {
            position: relative;
            z-index: 2;
            padding: 8px;
            height: 100%;
            display: flex;
            flex-direction: column;
        }
        
        /* Header Section */
        .header-section {
            text-align: center;
            margin-bottom: 8px;
            padding-bottom: 6px;
            border-bottom: 2px solid #1a5276;
        }
        
        .university-name {
            font-size: 18px;
            font-weight: 900;
            color: #1a5276;
            margin-bottom: 2px;
            text-shadow: 1px 1px 2px rgba(0,0,0,0.1);
        }
        
        .university-name-en {
            font-size: 12px;
            color: #7f8c8d;
            margin-bottom: 4px;
            font-weight: 600;
        }
        
        .certificate-title {
            font-size: 15px;
            font-weight: 800;
            color: #d35400;
            margin: 4px 0;
            padding: 4px 0;
            border-top: 1px solid #eee;
            border-bottom: 1px solid #eee;
        }
        
        .student-id-header {
            background: #1a5276;
            color: white;
            padding: 4px 10px;
            border-radius: 4px;
            display: inline-block;
            margin: 3px auto;
            font-weight: 600;
            font-size: 12px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        
        /* Student Info with Photo */
        .student-info-with-photo {
            display: grid;
            grid-template-columns: 35mm auto;
            gap: 8px;
            margin-bottom: 8px;
            align-items: start;
        }
        
        .student-photo-container {
            background: #f8f9fa;
            border: 2px solid #1a5276;
            border-radius: 8px;
            padding: 4px;
            text-align: center;
            height: 40mm;
            display: flex;
            flex-direction: column;
            justify-content: space-between;
        }
        
        .photo-label {
            font-size: 9px;
            color: #6c757d;
            font-weight: 600;
            margin-bottom: 2px;
            background: #e9ecef;
            padding: 2px 4px;
            border-radius: 4px;
        }
        
        .student-photo {
            width: 100%;
            height: 30mm;
            object-fit: contain;
            border: 1px solid #dee2e6;
            border-radius: 5px;
            background: #fff;
        }
        
        .no-photo {
            width: 100%;
            height: 30mm;
            background: #f0f0f0;
            border: 2px dashed #ccc;
            border-radius: 5px;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            color: #999;
            font-size: 10px;
        }
        
        .no-photo i {
            font-size: 20px;
            margin-bottom: 5px;
            color: #ccc;
        }
        
        .student-id-display {
            font-size: 11px;
            font-weight: 600;
            color: #1a5276;
            background: #e3f2fd;
            padding: 3px 6px;
            border-radius: 4px;
            margin-top: 3px;
        }
        
        /* Compact Grid Layout */
        .compact-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 6px;
            margin-bottom: 8px;
        }
        
        .info-card {
            background: #f8f9fa;
            border: 1px solid #dee2e6;
            border-radius: 5px;
            padding: 6px;
            position: relative;
        }
        
        .info-card-header {
            background: #e9ecef;
            padding: 3px 6px;
            margin: -6px -6px 4px -6px;
            border-radius: 5px 5px 0 0;
            border-bottom: 1px solid #dee2e6;
            font-weight: 600;
            font-size: 10px;
            color: #495057;
            display: flex;
            align-items: center;
            gap: 4px;
        }
        
        .info-item {
            margin-bottom: 4px;
        }
        
        .info-label {
            font-size: 9px;
            color: #6c757d;
            margin-bottom: 2px;
            font-weight: 600;
        }
        
        .info-value {
            font-size: 11px;
            font-weight: 700;
            color: #2c3e50;
            padding: 3px 5px;
            background: white;
            border-radius: 3px;
            border: 1px solid #ced4da;
            min-height: 25px;
            display: flex;
            align-items: center;
        }
        
        .highlight-value {
            background: linear-gradient(135deg, #ffecb3, #ffcc80);
            border-color: #ff9800;
            color: #bf360c;
            font-size: 12px;
        }
        
        .registration-date-value {
            background: linear-gradient(135deg, #e8f5e9, #c8e6c9);
            border-color: #4caf50;
            color: #1b5e20;
            font-weight: 800;
            font-size: 11px;
        }
        
        /* Status Badges - Compact */
        .status-badges {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 4px;
            margin: 6px 0;
        }
        
        .status-badge {
            padding: 4px 2px;
            border-radius: 4px;
            font-weight: 600;
            font-size: 9px;
            text-align: center;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            min-height: 35px;
            line-height: 1.1;
        }
        
        .status-badge i {
            font-size: 10px;
            margin-bottom: 2px;
        }
        
        /* Semester Section - Prominent */
        .semester-section {
            background: linear-gradient(135deg, #e3f2fd, #bbdefb);
            border: 2px solid #2196f3;
            border-radius: 6px;
            padding: 8px;
            margin: 8px 0;
            text-align: center;
        }
        
        .semester-label {
            font-size: 10px;
            color: #0d47a1;
            font-weight: 600;
            margin-bottom: 4px;
        }
        
        .semester-value {
            font-size: 22px;
            font-weight: 900;
            color: #0d47a1;
            background: white;
            padding: 6px 12px;
            border-radius: 6px;
            border: 2px solid #2196f3;
            display: inline-block;
            margin: 4px 0;
        }
        
        .semester-status {
            font-size: 11px;
            font-weight: 600;
            color: #1b5e20;
            background: #c8e6c9;
            padding: 3px 8px;
            border-radius: 15px;
            display: inline-block;
        }
        
        /* Registration Date Section */
        .registration-date-section {
            background: linear-gradient(135deg, #f3e5f5, #e1bee7);
            border: 2px solid #9c27b0;
            border-radius: 6px;
            padding: 6px;
            margin: 6px 0;
            text-align: center;
        }
        
        .registration-date-label {
            font-size: 10px;
            color: #4a148c;
            font-weight: 600;
            margin-bottom: 3px;
        }
        
        .registration-date-value-large {
            font-size: 18px;
            font-weight: 900;
            color: #4a148c;
            background: white;
            padding: 5px 10px;
            border-radius: 6px;
            border: 2px solid #9c27b0;
            display: inline-block;
            margin: 3px 0;
        }
        
        /* Footer - Compact */
        .footer-section {
            margin-top: auto;
            padding-top: 8px;
            border-top: 1px solid #1a5276;
            text-align: center;
        }
        
        .footer-info {
            display: flex;
            justify-content: space-around;
            font-size: 8px;
            color: #6c757d;
            margin-bottom: 6px;
        }
        
        .print-date {
            font-size: 9px;
            color: #495057;
            font-weight: 600;
            margin-bottom: 4px;
        }
        
        .serial-number {
            font-size: 8px;
            color: #adb5bd;
            font-family: monospace;
            background: #f8f9fa;
            padding: 2px 6px;
            border-radius: 3px;
            display: inline-block;
        }
        
        /* Control Buttons (Non-print) */
        .control-buttons {
            position: fixed;
            top: 10px;
            left: 10px;
            z-index: 1000;
            display: flex;
            gap: 6px;
            background: white;
            padding: 8px;
            border-radius: 6px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.15);
        }
        
        .btn {
            padding: 5px 10px;
            border: none;
            border-radius: 5px;
            font-family: 'Cairo', sans-serif;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.2s ease;
            display: inline-flex;
            align-items: center;
            gap: 5px;
            font-size: 11px;
        }
        
        .btn-print {
            background: #1a5276;
            color: white;
        }
        
        .btn-print:hover {
            background: #154360;
            transform: translateY(-1px);
        }
        
        .btn-back {
            background: #95a5a6;
            color: white;
        }
        
        .btn-back:hover {
            background: #7f8c8d;
            transform: translateY(-1px);
        }
        
        /* Print Styles */
        @media print {
            .control-buttons {
                display: none;
            }
            
            body {
                background: white;
                padding: 0;
            }
            
            .certificate-container {
                box-shadow: none;
                border: 2px solid #1a5276;
                margin: 0;
                width: 148mm;
                height: 210mm;
            }
            
            .certificate-container:last-child {
                page-break-after: auto;
            }
            
            /* Ensure photos print correctly */
            .student-photo, .no-photo {
                -webkit-print-color-adjust: exact;
                print-color-adjust: exact;
            }
        }
        
        /* Empty value styling */
        .empty-value {
            color: #adb5bd;
            font-style: italic;
            font-weight: normal;
            font-size: 10px;
        }
        
        /* Color coding for status */
        .status-green { background: #d4edda; color: #155724; border: 1px solid #c3e6cb; }
        .status-red { background: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; }
        .status-yellow { background: #fff3cd; color: #856404; border: 1px solid #ffeaa7; }
        .status-blue { background: #d1ecf1; color: #0c5460; border: 1px solid #bee5eb; }
        
        /* Grid adjustments for smaller screens */
        @media (max-width: 160mm) {
            .compact-grid {
                grid-template-columns: 1fr;
            }
            
            .status-badges {
                grid-template-columns: repeat(2, 1fr);
            }
            
            .student-info-with-photo {
                grid-template-columns: 1fr;
            }
        }
        
        /* Signature area */
        .signature-area {
            margin-top: 12px;
            padding-top: 8px;
            border-top: 1px dashed #dee2e6;
            text-align: center;
        }
        
        .signature-box {
            text-align: center;
            margin: 0 auto;
            width: 60%;
        }
        
        .signature-line {
            width: 100%;
            height: 1px;
            background: #333;
            margin: 25px auto 3px auto;
        }
        
        .signature-label {
            font-size: 10px;
            color: #6c757d;
            font-weight: 600;
        }
        
        /* Program info styling */
        .program-highlight {
            background: #e8f5e9 !important;
            border: 2px solid #4caf50 !important;
            color: #1b5e20 !important;
            font-weight: 800 !important;
        }
        
        /* Student info without photo */
        .student-info-header {
            background: #e3f2fd;
            border: 1px solid #2196f3;
            border-radius: 5px;
            padding: 30px;
            margin-bottom: 8px;
        }
        
        .student-name-large {
            font-size: 18px;
            font-weight: 700;
            color: #1a5276;
            margin-bottom: 4px;
        }
    </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='registration_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 foreach ($students as $index => $student): ?>
            <div class="certificate-container">
                <!-- Background -->
                <div class="watermark">الجامعة الوطنية</div>
                <div class="border-design"></div>
                
                <!-- Certificate Content -->
                <div class="certificate-content">
                    <!-- Header -->
                    <div class="header-section">
                        <h1 class="university-name"><?= e($university_info['name']) ?></h1>
                        <h2 class="university-name-en"><?= e($university_info['academic_affairs']) ?></h2>
                        
                        <h3 class="certificate-title">شهادة القيد والتسجيل</h3>
                        
                        <div class="student-id-header">
                            <i class="fas fa-id-card"></i>
                            شهادة رقم: <?= strtoupper(substr(md5($student['student_id'] . time()), 0, 8)) ?>
                        </div>
                    </div>
                    
                    <!-- Student Information 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.src='data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTAwIiBoZWlnaHQ9IjEyMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48cmVjdCB3aWR0aD0iMTAwIiBoZWlnaHQ9IjEyMCIgZmlsbD0iI2YwZjBmMCIvPjx0ZXh0IHg9IjUwIiB5PSI2MCIgZm9udC1mYW1pbHk9IkFyaWFsIiBmb250LXNpemU9IjE0IiB0ZXh0LWFuY2hvcj0ibWlkZGxlIiBmaWxsPSIjOTk5Ij5ObyBQaG90bzwvdGV4dD48L3N2Zz4=';">
                            <?php else: ?>
                                <div class="no-photo">
                                    <i class="fas fa-user-circle"></i>
                                    <span>لا توجد صورة</span>
                                </div>
                            <?php endif; ?>
                          
                        </div>
                        
                        <!-- Student Basic 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-id-display">
                                 <strong class="student-name-large" dir="RTL"> <i class="fas fa-id-badge"></i><?= e($student['student_id']) ?></strong>
                            </div>
                            
                            
                            <!-- Registration Date -->
                            <?php if (!empty($student['registration_date_formatted'])): ?>
                                <div style="margin-top: 6px; padding: 4px; background: #f3e5f5; border-radius: 4px; text-align: center;">
                                    <span style="font-size: 10px; color: #7b1fa2; font-weight: 600;">
                                        <i class="fas fa-calendar-alt"></i> تاريخ التسجيل:
                                    </span>
                                    <span style="font-size: 12px; color: #4a148c; font-weight: 700; margin-right: 5px;">
                                        <?= e($student['registration_date_formatted']) ?>
                                    </span>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                    
                    <!-- Student Information - Compact Grid -->
                    <div class="compact-grid">
                        <!-- Personal Info Card -->
                        <div class="info-card">
                            <div class="info-card-header">
                                <i class="fas fa-id-card"></i>
                                المعلومات الأساسية
                            </div>
                            
                            <div class="info-item">
                                <div class="info-label">اسم الطالب :</div>
                                <div class="info-value highlight-value">
                                    <?= e($student['student_name']) ?>
                                </div>
                            </div>
                            
                            <div class="info-item">
                                <div class="info-label">رقم الطالب  :</div>
                                <div class="info-value">
                                   <strong class="d-block fs-6" dir="RTL"><?= e($student['student_id']) ?></strong>
                                </div>
                            </div>
                            
                            
                            
                            <div class="info-item">
                                <div class="info-label">رقم الهوية الوطنية:</div>
                                <div class="info-value">
                                    <?= !empty($student['national_id']) ? e($student['national_id']) : '<span class="empty-value">---</span>' ?>
                                </div>
                            </div>
                            
                            <?php if (!empty($student['registration_date'])): ?>
                                <div class="info-item">
                                    <div class="info-label">تاريخ التسجيل:</div>
                                    <div class="info-value registration-date-value">
                                        <i class="fas fa-calendar-check"></i>
                                        <?= e($student['registration_date_formatted']) ?>
                                    </div>
                                </div>
                            <?php endif; ?>
                        </div>
                        
                        <!-- Academic Info Card -->
                        <div class="info-card">
                            <div class="info-card-header">
                                <i class="fas fa-graduation-cap"></i>
                                المعلومات الأكاديمية
                            </div>
                            
                            <div class="info-item">
                                <div class="info-label">الكلية:</div>
                                <div class="info-value">
                                    <?= !empty($student['college_name']) ? e($student['college_name']) : '<span class="empty-value">غير محدد</span>' ?>
                                </div>
                            </div>
                            
                            <div class="info-item">
                                <div class="info-label">القسم:</div>
                                <div class="info-value">
                                    <?= !empty($student['section_name']) ? e($student['section_name']) : '<span class="empty-value">غير محدد</span>' ?>
                                </div>
                            </div>
                            
                            <div class="info-item">
                                <div class="info-label">البرنامج:</div>
                                <div class="info-value <?= !empty($student['program_name']) ? 'program-highlight' : '' ?>">
                                    <?php if (!empty($student['program_name'])): ?>
                                        <i class="fas fa-book"></i> <?= e($student['program_name']) ?>
                                    <?php else: ?>
                                        <span class="empty-value">غير محدد</span>
                                    <?php endif; ?>
                                </div>
                            </div>
                            
                            <div class="info-item">
                                <div class="info-label">الدفعة:</div>
                                <div class="info-value">
                                    <?= !empty($student['batch_name']) ? 'دفعة ' . e($student['batch_name']) : '<span class="empty-value">غير محدد</span>' ?>
                                </div>
                            </div>
                        </div>
                    </div>
                    

                    
                    <!-- Semester Information - Prominent -->
                    <div class="semester-section">
                        <div class="semester-label">آخر فصل دراسي مسجل:</div>
                        <?php if (!empty($student['last_semester_arabic'])): ?>
                            <div class="semester-value">الفصل <?= e($student['last_semester_arabic']) ?></div>
                            <div class="semester-status">
                                <i class="fas fa-check-circle"></i> الطالب مسجل في النظام الأكاديمي
                            </div>
                        <?php else: ?>
                            <div class="semester-value" style="color: #d32f2f; background: #ffcdd2; border-color: #f44336;">
                                غير مسجل
                            </div>
                            <div class="semester-status" style="color: #d32f2f; background: #ffcdd2;">
                                <i class="fas fa-exclamation-circle"></i> الطالب غير مسجل في أي فصل دراسي
                            </div>
                        <?php endif; ?>
                    </div>
                    
                    <!-- Signature Area (Only Registration Officer) -->
                    <div class="signature-area">
                        <div class="signature-box">
                            <div class="signature-line"></div>
                            <div class="signature-label">توقيع ضابط التسجيل والإمتحانات</div>
                        </div>
                    </div>
                    
                    <!-- Footer -->
                    <div class="footer-section">
                        <div class="footer-info">
                            <div class="footer-item">
                                <i class="fas fa-map-marker-alt"></i>
                                <?= e($university_info['address']) ?>
                            </div>
                            
                            <div class="footer-item">
                                <i class="fas fa-phone"></i>
                                <?= e($university_info['phone']) ?>
                            </div>
                            
                            <div class="footer-item">
                                <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 class="serial-number">
                            رمز الشهادة: <?= strtoupper(substr(md5($student['student_id'] . time()), 0, 8)) ?>
                        </div>
                    </div>
                </div>
            </div>
        <?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();
                }, 800);
            });
        }
        
        // Add keyboard shortcuts
        document.addEventListener('keydown', function(e) {
            // Ctrl+P to print
            if ((e.ctrlKey || e.metaKey) && e.key === 'p') {
                e.preventDefault();
                window.print();
            }
            // Escape to go back
            if (e.key === 'Escape') {
                window.history.back();
            }
        });
        
        // Show print preview message
        window.addEventListener('beforeprint', function() {
            console.log('جاري التحضير للطباعة...');
        });
        
        window.addEventListener('afterprint', function() {
            console.log('تمت الطباعة بنجاح');
            // Optional: Close window after printing
            if (urlParams.has('auto_print')) {
                setTimeout(() => window.close(), 1000);
            }
        });
    </script>
</body>
</html>
