<?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;
}

// دالة لتحويل كود الجنس إلى نص عربي
function getGenderArabic($gender_code) {
    switch($gender_code) {
        case 0:
            return 'غير محدد';
        case 1:
            return 'ذكر';
        case 2:
            return 'أنثى';
        default:
            return 'غير محدد';
    }
}

// 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.gender,
    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']);
    
    // تحويل كود الجنس إلى نص عربي
    $student['gender_arabic'] = getGenderArabic($student['gender'] ?? 0);
    
    // إنشاء نص الجنس للعرض
    $student['gender_display'] = $student['gender_arabic'];
    
    // إضافة أيقونة ولون حسب الجنس
    switch($student['gender'] ?? 0) {
        case 1:
            $student['gender_icon'] = 'fa-male';
            $student['gender_color'] = '#1a5276'; // أزرق للذكر
            $student['gender_bg_color'] = '#e3f2fd';
            break;
        case 2:
            $student['gender_icon'] = 'fa-female';
            $student['gender_color'] = '#d81b60'; // وردي للأنثى
            $student['gender_bg_color'] = '#fce4ec';
            break;
        default:
            $student['gender_icon'] = 'fa-user';
            $student['gender_color'] = '#6c757d'; // رمادي لغير محدد
            $student['gender_bg_color'] = '#f5f5f5';
            break;
    }
}

// دالة لتحويل رقم الفصل الدراسي إلى كلمة عربية
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']);
    $student['today_date'] = formatArabicDate(date('Y-m-d'));
}

// الحصول على أسماء البرامج للطلاب
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-',
    'website' => 'su.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', Arial, 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;
        }
        
        .academic-affairs {
            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 */
        .student-info-grid {
            display: grid;
            grid-template-columns: 1fr 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;
            padding: 1px 3px;
            background: #f8f9fa;
            border-radius: 2px;
            border: 1px solid #dee2e6;
            font-size: 9px;
            min-height: 18px;
            display: flex;
            align-items: center;
            gap: 4px;
        }
        
        .highlight-value {
            background: linear-gradient(135deg, #e3f2fd, #bbdefb);
            border-color: #2196f3;
            color: #0d47a1;
        }
        
        .gender-value {
            justify-content: center;
        }
        
        /* Academic Info Section */
        .academic-section {
            margin: 4px 0;
        }
        
        .academic-section-title {
            background: #1a5276;
            color: white;
            padding: 3px 5px;
            border-radius: 3px;
            text-align: center;
            font-weight: 800;
            font-size: 10px;
            margin-bottom: 3px;
        }
        
        .academic-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 3px;
            margin: 3px 0;
        }
        
        .academic-item {
            background: #f8f9fa;
            border: 1px solid #dee2e6;
            border-radius: 3px;
            padding: 3px;
        }
        
        .academic-label {
            font-size: 8px;
            color: #666;
            font-weight: 700;
            margin-bottom: 1px;
        }
        
        .academic-value {
            font-size: 9px;
            font-weight: 800;
            color: #1a5276;
        }
        
        /* Semester Information */
        .semester-section {
            background: linear-gradient(135deg, #e3f2fd, #bbdefb);
            border: 1px solid #2196f3;
            border-radius: 4px;
            padding: 4px;
            margin: 4px 0;
            text-align: center;
        }
        
        .semester-label {
            font-size: 9px;
            color: #0d47a1;
            font-weight: 600;
            margin-bottom: 2px;
        }
        
        .semester-value {
            font-size: 12px;
            font-weight: 900;
            color: #0d47a1;
            background: white;
            padding: 3px 6px;
            border-radius: 4px;
            border: 1px solid #2196f3;
            display: inline-block;
        }
        
        /* Registration Date Section */
        .registration-date-section {
            background: linear-gradient(135deg, #f3e5f5, #e1bee7);
            border: 1px solid #9c27b0;
            border-radius: 4px;
            padding: 4px;
            margin: 4px 0;
            text-align: center;
        }
        
        .registration-date-label {
            font-size: 9px;
            color: #4a148c;
            font-weight: 600;
            margin-bottom: 2px;
        }
        
        .registration-date-value {
            font-size: 10px;
            font-weight: 900;
            color: #4a148c;
            background: white;
            padding: 2px 4px;
            border-radius: 3px;
            border: 1px solid #9c27b0;
        }
        
        /* 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;
            }
        }
    </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 
        // 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="academic-affairs"><?= e($university_info['academic_affairs']) ?></div>
                                <h3 class="certificate-title">شهادة القيد والتسجيل</h3>
                                <div class="certificate-number">
                                    <i class="fas fa-id-card"></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">
                                        <div class="student-info-item">
                                            <div class="student-info-label">رقم الطالب:</div>
                                            <div class="student-info-value highlight-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['national_id']) ? e($student['national_id']) : '---' ?></div>
                                        </div>
                                        
                                        <div class="student-info-item">
                                            <div class="student-info-label">الجنس:</div>
                                            <div class="student-info-value gender-value" style="color: <?= e($student['gender_color']) ?>; background: <?= e($student['gender_bg_color']) ?>; border-color: <?= e($student['gender_color']) ?>;">
                                                <i class="fas <?= e($student['gender_icon']) ?>"></i>
                                                <?= e($student['gender_display']) ?>
                                            </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>
                                    
                                    <div class="student-info-grid">
                                        <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">
                                            <div class="student-info-label">الدفعة:</div>
                                            <div class="student-info-value"><?= !empty($student['batch_name']) ? 'دفعة ' . e($student['batch_name']) : 'غير محدد' ?></div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Academic Information -->
                            <div class="academic-section">
                                <div class="academic-section-title">
                                    <i class="fas fa-graduation-cap"></i>
                                    المعلومات الأكاديمية
                                </div>
                                
                                <div class="academic-grid">
                                    <div class="academic-item">
                                        <div class="academic-label">البرنامج:</div>
                                        <div class="academic-value">
                                            <?php if (!empty($student['program_name'])): ?>
                                                <i class="fas fa-book"></i> <?= e($student['program_name']) ?>
                                            <?php else: ?>
                                                غير محدد
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                    
                                    <div class="academic-item">
                                        <div class="academic-label">الحالة:</div>
                                        <div class="academic-value">
                                            <?php if (!empty($student['profile_completed']) && $student['profile_completed'] == 1): ?>
                                                <i class="fas fa-check-circle text-success"></i> مكتمل
                                            <?php else: ?>
                                                <i class="fas fa-clock text-warning"></i> غير مكتمل
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Semester Information -->
                            <div class="semester-section">
                                <div class="semester-label">آخر فصل دراسي مسجل:</div>
                                <?php if (!empty($student['last_semester_arabic'])): ?>
                                    <div class="semester-value">
                                        <i class="fas fa-calendar-alt"></i>
                                        الفصل <?= e($student['last_semester_arabic']) ?>
                                    </div>
                                <?php else: ?>
                                    <div class="semester-value" style="color: #d32f2f;">
                                        <i class="fas fa-exclamation-circle"></i>
                                        غير مسجل
                                    </div>
                                <?php endif; ?>
                            </div>
                            
                            <!-- Registration Date -->
                            <?php if (!empty($student['registration_date_formatted'])): ?>
                                <div class="registration-date-section">
                                    <div class="registration-date-label">
                                        <i class="fas fa-calendar-check"></i>
                                        تاريخ التسجيل:
                                    </div>
                                    <div class="registration-date-value">
                                        <?= e($student['registration_date_formatted']) ?>
                                    </div>
                                </div>
                            <?php endif; ?>
                            
                            <!-- Officer 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="academic-affairs"><?= e($university_info['academic_affairs']) ?></div>
                                <h3 class="certificate-title">شهادة القيد والتسجيل</h3>
                                <div class="certificate-number">
                                    <i class="fas fa-id-card"></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">
                                        <div class="student-info-item">
                                            <div class="student-info-label">رقم الطالب:</div>
                                            <div class="student-info-value highlight-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['national_id']) ? e($student['national_id']) : '---' ?></div>
                                        </div>
                                        
                                        <div class="student-info-item">
                                            <div class="student-info-label">الجنس:</div>
                                            <div class="student-info-value gender-value" style="color: <?= e($student['gender_color']) ?>; background: <?= e($student['gender_bg_color']) ?>; border-color: <?= e($student['gender_color']) ?>;">
                                                <i class="fas <?= e($student['gender_icon']) ?>"></i>
                                                <?= e($student['gender_display']) ?>
                                            </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>
                                    
                                    <div class="student-info-grid">
                                        <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">
                                            <div class="student-info-label">الدفعة:</div>
                                            <div class="student-info-value"><?= !empty($student['batch_name']) ? 'دفعة ' . e($student['batch_name']) : 'غير محدد' ?></div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Academic Information -->
                            <div class="academic-section">
                                <div class="academic-section-title">
                                    <i class="fas fa-graduation-cap"></i>
                                    المعلومات الأكاديمية
                                </div>
                                
                                <div class="academic-grid">
                                    <div class="academic-item">
                                        <div class="academic-label">البرنامج:</div>
                                        <div class="academic-value">
                                            <?php if (!empty($student['program_name'])): ?>
                                                <i class="fas fa-book"></i> <?= e($student['program_name']) ?>
                                            <?php else: ?>
                                                غير محدد
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                    
                                    <div class="academic-item">
                                        <div class="academic-label">الحالة:</div>
                                        <div class="academic-value">
                                            <?php if (!empty($student['profile_completed']) && $student['profile_completed'] == 1): ?>
                                                <i class="fas fa-check-circle text-success"></i> مكتمل
                                            <?php else: ?>
                                                <i class="fas fa-clock text-warning"></i> غير مكتمل
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Semester Information -->
                            <div class="semester-section">
                                <div class="semester-label">آخر فصل دراسي مسجل:</div>
                                <?php if (!empty($student['last_semester_arabic'])): ?>
                                    <div class="semester-value">
                                        <i class="fas fa-calendar-alt"></i>
                                        الفصل <?= e($student['last_semester_arabic']) ?>
                                    </div>
                                <?php else: ?>
                                    <div class="semester-value" style="color: #d32f2f;">
                                        <i class="fas fa-exclamation-circle"></i>
                                        غير مسجل
                                    </div>
                                <?php endif; ?>
                            </div>
                            
                            <!-- Registration Date -->
                            <?php if (!empty($student['registration_date_formatted'])): ?>
                                <div class="registration-date-section">
                                    <div class="registration-date-label">
                                        <i class="fas fa-calendar-check"></i>
                                        تاريخ التسجيل:
                                    </div>
                                    <div class="registration-date-value">
                                        <?= e($student['registration_date_formatted']) ?>
                                    </div>
                                </div>
                            <?php endif; ?>
                            
                            <!-- Officer 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>