<?php
// print_registration_certificate.php - نسخة محسنة مع إضافة التخصص وحماية SQL Injection
error_reporting(E_ALL);
ini_set('display_errors', 1);

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

// ==================== SECURITY FUNCTIONS ====================
function validateInt($value, $default = null) {
    if ($value === null || $value === '') return $default;
    $int = filter_var($value, FILTER_VALIDATE_INT);
    return $int !== false ? $int : $default;
}

function validateString($value, $max_length = 255) {
    if ($value === null) return '';
    $value = trim((string)$value);
    // Remove any null bytes and control characters
    $value = preg_replace('/[\x00-\x1F\x7F]/u', '', $value);
    return substr($value, 0, $max_length);
}

function validateStudentId($value) {
    if ($value === null) return '';
    $value = trim((string)$value);
    // Allow only alphanumeric, dashes, and underscores for student IDs
    $value = preg_replace('/[^a-zA-Z0-9\-_]/', '', $value);
    return substr($value, 0, 50);
}

// Function to get the best available image for a student
function getStudentPhoto($student_id) {
    // Sanitize student_id for file path (remove any path traversal attempts)
    $student_id = preg_replace('/[^a-zA-Z0-9\-_]/', '', $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) && is_file($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) - SANITIZED
$student_ids = isset($_GET['student_ids']) ? $_GET['student_ids'] : '';
$student_ids_array = [];

if (!empty($student_ids)) {
    // Split and sanitize each ID
    $raw_ids = explode(',', $student_ids);
    foreach ($raw_ids as $id) {
        $clean_id = validateStudentId($id);
        if (!empty($clean_id)) {
            $student_ids_array[] = $clean_id;
        }
    }
    // Remove duplicates
    $student_ids_array = array_unique($student_ids_array);
}

// 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 = implode(',', array_fill(0, count($student_ids_array), '?'));

// First, check database structure safely
$hasProgramsTable = false;
$hasProgramInStudents = false;
$hasProgramInBatches = false;
$hasSpecializationsTable = false;

try {
    $checkProgramsTable = $mysqli1->query("SHOW TABLES LIKE 'programs'");
    $hasProgramsTable = $checkProgramsTable && $checkProgramsTable->num_rows > 0;
    
    $checkProgramInStudents = $mysqli1->query("SHOW COLUMNS FROM students LIKE 'program_id'");
    $hasProgramInStudents = $checkProgramInStudents && $checkProgramInStudents->num_rows > 0;
    
    $checkProgramInBatches = $mysqli1->query("SHOW COLUMNS FROM batches LIKE 'program_id'");
    $hasProgramInBatches = $checkProgramInBatches && $checkProgramInBatches->num_rows > 0;
    
    $checkSpecializationsTable = $mysqli1->query("SHOW TABLES LIKE 'specializations'");
    $hasSpecializationsTable = $checkSpecializationsTable && $checkSpecializationsTable->num_rows > 0;
} catch (Exception $e) {
    error_log("Error checking database structure: " . $e->getMessage());
}

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

// Add program_id if it exists in students table
if ($hasProgramInStudents) {
    $select_fields .= ", s.program_id";
}

// Add specialization fields if the table exists
if ($hasSpecializationsTable) {
    $select_fields .= ", sp.specialization_name_ar AS specialization_name";
}

$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
";

if ($hasSpecializationsTable) {
    $query .= " LEFT JOIN specializations sp ON sp.specialization_id = s.specialization_id";
}

$query .= " 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 using call_user_func_array
    $types = str_repeat('s', count($student_ids_array));
    $params = array_merge([$types], $student_ids_array);
    
    $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) {
    error_log("Error fetching students: " . $e->getMessage());
    die("خطأ في جلب البيانات: " . $e->getMessage());
}

// Get last semester and registration date for each student
foreach ($students as &$student) {
    // Get the latest semester and registration date
    $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;
    }
    
    // Get student photo
    $student['photo'] = getStudentPhoto($student['student_id']);
}

// دالة لتحويل رقم الفصل الدراسي إلى كلمة عربية
function convertSemesterToArabic($semester) {
    if (empty($semester)) {
        return null;
    }
    
    // Extract number from text if it contains numbers and words
    preg_match('/\d+/', $semester, $matches);
    $number = isset($matches[0]) ? (int)$matches[0] : (int)$semester;
    
    // Convert number to Arabic word
    $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] ?? $month) . ' ' . $year;
}

// Convert semesters to Arabic words and format dates
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'));
}

// Get program names for students
foreach ($students as &$student) {
    $student['program_name'] = null; // Default value
    
    // Method 1: If programs table exists and student has 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'];
            }
        }
    }
    // Method 2: If program_id is in batches table
    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'];
            }
        }
    }
    // Method 3: Try to get from section
    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'];
            }
        }
    }
}

// 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 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;
        }
        
        .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;
            color: #1a5276;
            padding: 1px 3px;
            background: #f8f9fa;
            border-radius: 2px;
            border: 1px solid #dee2e6;
            font-size: 9px;
        }
        
        .highlight-value {
            background: linear-gradient(135deg, #e3f2fd, #bbdefb);
            border-color: #2196f3;
            color: #0d47a1;
        }
        
        /* 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;
        }
        
        /* NEW: Specialization section */
        .specialization-section {
            background: linear-gradient(135deg, #f3e8ff, #e9d5ff);
            border: 1px solid #9333ea;
            border-radius: 4px;
            padding: 3px;
            margin: 4px 0;
        }
        
        .specialization-label {
            font-size: 8px;
            color: #6b21a8;
            font-weight: 600;
            text-align: center;
        }
        
        .specialization-value {
            font-size: 9px;
            font-weight: 800;
            color: #6b21a8;
            text-align: center;
        }
        
        /* 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 foreach ($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"><?= htmlspecialchars($university_info['name'], ENT_QUOTES, 'UTF-8') ?></h1>
                            <div class="academic-affairs"><?= htmlspecialchars($university_info['academic_affairs'], ENT_QUOTES, 'UTF-8') ?></div>
                            <h3 class="certificate-title">شهادة القيد والتسجيل</h3>
                            <div class="certificate-number">
                                <i class="fas fa-id-card"></i>
                                رقم الشهادة: <?= htmlspecialchars(strtoupper(substr(md5($student['student_id'] . time()), 0, 6)), ENT_QUOTES, 'UTF-8') ?>
                            </div>
                        </div>
                        
                        <!-- Date -->
                        <div class="date-section">
                            <i class="fas fa-calendar-day"></i>
                            تاريخ اليوم: <?= htmlspecialchars($student['today_date'] ?? '', ENT_QUOTES, 'UTF-8') ?>
                        </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="<?= htmlspecialchars($student['photo']['path'], ENT_QUOTES, 'UTF-8') ?>" 
                                         alt="صورة الطالب <?= htmlspecialchars($student['student_name'] ?? '', ENT_QUOTES, 'UTF-8') ?>"
                                         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>
                                    <?= htmlspecialchars($student['student_name'] ?? '', ENT_QUOTES, 'UTF-8') ?>
                                </div>
                                
                                <div class="student-info-grid">
                                    <div class="student-info-item">
                                        <div class="student-info-label">رقم الطالب:</div>
                                        <div class="student-info-value highlight-value"><?= htmlspecialchars($student['student_id'] ?? '', ENT_QUOTES, 'UTF-8') ?></div>
                                    </div>
                                    
                                    <div class="student-info-item">
                                        <div class="student-info-label">رقم الهوية:</div>
                                        <div class="student-info-value"><?= !empty($student['national_id']) ? htmlspecialchars($student['national_id'], ENT_QUOTES, 'UTF-8') : '---' ?></div>
                                    </div>
                                    
                                    <div class="student-info-item">
                                        <div class="student-info-label">الكلية:</div>
                                        <div class="student-info-value"><?= !empty($student['college_name']) ? htmlspecialchars($student['college_name'], ENT_QUOTES, 'UTF-8') : 'غير محدد' ?></div>
                                    </div>
                                    
                                    <div class="student-info-item">
                                        <div class="student-info-label">القسم:</div>
                                        <div class="student-info-value"><?= !empty($student['section_name']) ? htmlspecialchars($student['section_name'], ENT_QUOTES, 'UTF-8') : 'غير محدد' ?></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> <?= htmlspecialchars($student['program_name'], ENT_QUOTES, 'UTF-8') ?>
                                        <?php else: ?>
                                            غير محدد
                                        <?php endif; ?>
                                    </div>
                                </div>
                                
                                <div class="academic-item">
                                    <div class="academic-label">الدفعة:</div>
                                    <div class="academic-value">
                                        <?= !empty($student['batch_name']) ? 'دفعة ' . htmlspecialchars($student['batch_name'], ENT_QUOTES, 'UTF-8') : 'غير محدد' ?>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- NEW: Specialization Information -->
                            <?php if (!empty($student['specialization_name'])): ?>
                            <div class="specialization-section">
                                <div class="specialization-label">
                                    <i class="fas fa-microscope"></i> التخصص
                                </div>
                                <div class="specialization-value">
                                    <?= htmlspecialchars($student['specialization_name'], ENT_QUOTES, 'UTF-8') ?>
                                </div>
                            </div>
                            <?php endif; ?>
                        </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>
                                    الفصل <?= htmlspecialchars($student['last_semester_arabic'], ENT_QUOTES, 'UTF-8') ?>
                                </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">
                                    <?= htmlspecialchars($student['registration_date_formatted'], ENT_QUOTES, 'UTF-8') ?>
                                </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> <?= htmlspecialchars($university_info['address'], ENT_QUOTES, 'UTF-8') ?></div>
                                <div><i class="fas fa-phone"></i> <?= htmlspecialchars($university_info['phone'], ENT_QUOTES, 'UTF-8') ?></div>
                                <div><i class="fas fa-globe"></i> <?= htmlspecialchars($university_info['website'], ENT_QUOTES, 'UTF-8') ?></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"><?= htmlspecialchars($university_info['name'], ENT_QUOTES, 'UTF-8') ?></h1>
                            <div class="academic-affairs"><?= htmlspecialchars($university_info['academic_affairs'], ENT_QUOTES, 'UTF-8') ?></div>
                            <h3 class="certificate-title">شهادة القيد والتسجيل</h3>
                            <div class="certificate-number">
                                <i class="fas fa-id-card"></i>
                                رقم الشهادة: <?= htmlspecialchars(strtoupper(substr(md5($student['student_id'] . time() . 'copy2'), 0, 6)), ENT_QUOTES, 'UTF-8') ?>
                            </div>
                        </div>
                        
                        <!-- Date -->
                        <div class="date-section">
                            <i class="fas fa-calendar-day"></i>
                            تاريخ اليوم: <?= htmlspecialchars($student['today_date'] ?? '', ENT_QUOTES, 'UTF-8') ?>
                        </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="<?= htmlspecialchars($student['photo']['path'], ENT_QUOTES, 'UTF-8') ?>" 
                                         alt="صورة الطالب <?= htmlspecialchars($student['student_name'] ?? '', ENT_QUOTES, 'UTF-8') ?>"
                                         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>
                                    <?= htmlspecialchars($student['student_name'] ?? '', ENT_QUOTES, 'UTF-8') ?>
                                </div>
                                
                                <div class="student-info-grid">
                                    <div class="student-info-item">
                                        <div class="student-info-label">رقم الطالب:</div>
                                        <div class="student-info-value highlight-value"><?= htmlspecialchars($student['student_id'] ?? '', ENT_QUOTES, 'UTF-8') ?></div>
                                    </div>
                                    
                                    <div class="student-info-item">
                                        <div class="student-info-label">رقم الهوية:</div>
                                        <div class="student-info-value"><?= !empty($student['national_id']) ? htmlspecialchars($student['national_id'], ENT_QUOTES, 'UTF-8') : '---' ?></div>
                                    </div>
                                    
                                    <div class="student-info-item">
                                        <div class="student-info-label">الكلية:</div>
                                        <div class="student-info-value"><?= !empty($student['college_name']) ? htmlspecialchars($student['college_name'], ENT_QUOTES, 'UTF-8') : 'غير محدد' ?></div>
                                    </div>
                                    
                                    <div class="student-info-item">
                                        <div class="student-info-label">القسم:</div>
                                        <div class="student-info-value"><?= !empty($student['section_name']) ? htmlspecialchars($student['section_name'], ENT_QUOTES, 'UTF-8') : 'غير محدد' ?></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> <?= htmlspecialchars($student['program_name'], ENT_QUOTES, 'UTF-8') ?>
                                        <?php else: ?>
                                            غير محدد
                                        <?php endif; ?>
                                    </div>
                                </div>
                                
                                <div class="academic-item">
                                    <div class="academic-label">الدفعة:</div>
                                    <div class="academic-value">
                                        <?= !empty($student['batch_name']) ? 'دفعة ' . htmlspecialchars($student['batch_name'], ENT_QUOTES, 'UTF-8') : 'غير محدد' ?>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- NEW: Specialization Information -->
                            <?php if (!empty($student['specialization_name'])): ?>
                            <div class="specialization-section">
                                <div class="specialization-label">
                                    <i class="fas fa-microscope"></i> التخصص
                                </div>
                                <div class="specialization-value">
                                    <?= htmlspecialchars($student['specialization_name'], ENT_QUOTES, 'UTF-8') ?>
                                </div>
                            </div>
                            <?php endif; ?>
                        </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>
                                    الفصل <?= htmlspecialchars($student['last_semester_arabic'], ENT_QUOTES, 'UTF-8') ?>
                                </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">
                                    <?= htmlspecialchars($student['registration_date_formatted'], ENT_QUOTES, 'UTF-8') ?>
                                </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> <?= htmlspecialchars($university_info['address'], ENT_QUOTES, 'UTF-8') ?></div>
                                <div><i class="fas fa-phone"></i> <?= htmlspecialchars($university_info['phone'], ENT_QUOTES, 'UTF-8') ?></div>
                                <div><i class="fas fa-globe"></i> <?= htmlspecialchars($university_info['website'], ENT_QUOTES, 'UTF-8') ?></div>
                            </div>
                            <div class="print-date">تم الطباعة: <?= date('Y/m/d - h:i A') ?></div>
                        </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();
                }, 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>
