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

require 'db.php';
require 'helpers.php';

// Authentication check
if (!isset($_SESSION['committee_id'])) {
    header('Location: login.php');
    exit;
}

$committeeId = (int)($_SESSION['committee_id'] ?? 0);
$canAll = (bool)($_SESSION['committee_can_all'] ?? false);
$scopeCollege = isset($_SESSION['committee_college_id']) ? (int)$_SESSION['committee_college_id'] : null;

$mysqli1->set_charset('utf8mb4');
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

// Get student ID from query parameter
$student_id = trim($_GET['student_id'] ?? '');

if (empty($student_id)) {
    die("خطأ: الرقم الجامعي مطلوب");
}

/* ---------- Get Student Data ---------- */
$student = null;
$registration_data = null;

try {
    // Check if student exists and user has permission
    $where_conditions = "s.student_id = ?";
    $params = [$student_id];
    $types = "s";
    
    if (!$canAll && $scopeCollege !== null) {
        $where_conditions .= " AND s.college_id = ?";
        $params[] = $scopeCollege;
        $types .= "i";
    }
    
    // Get student data with all related information
    $sql = "
        SELECT 
            s.*,
            c.name AS college_name,
            c.name_ar AS college_name_ar,
            sec.name AS section_name,
            sec.name_ar AS section_name_ar,
            b.value AS batch_name,
            b.value_ar AS batch_name_ar,
            p.name AS program_name,
            p.name_ar AS program_name_ar,
            u.name AS university_name,
            u.name_ar AS university_name_ar
        FROM students s
        LEFT JOIN colleges c ON c.id = s.college_id
        LEFT JOIN sections sec ON sec.id = s.section_id
        LEFT JOIN batches b ON b.id = s.batch_id
        LEFT JOIN programs p ON p.id = s.program_id
        LEFT JOIN universities u ON u.id = c.university_id
        WHERE {$where_conditions}
        LIMIT 1
    ";
    
    $stmt = $mysqli1->prepare($sql);
    
    if ($types === "s") {
        $stmt->bind_param("s", $student_id);
    } else {
        $stmt->bind_param("si", $student_id, $scopeCollege);
    }
    
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows === 0) {
        die("خطأ: الطالب غير موجود أو ليس لديك صلاحية لعرض بياناته");
    }
    
    $student = $result->fetch_assoc();
    $stmt->close();
    
    // Get registration data - last semester enrolled
    $reg_sql = "
        SELECT 
            semester_id,
            registration_date,
            status,
            academic_year,
            semester_type
        FROM registrations 
        WHERE student_id = ?
        ORDER BY semester_id DESC
        LIMIT 1
    ";
    
    $reg_stmt = $mysqli1->prepare($reg_sql);
    $reg_stmt->bind_param("s", $student_id);
    $reg_stmt->execute();
    $reg_result = $reg_stmt->get_result();
    
    if ($reg_result->num_rows > 0) {
        $registration_data = $reg_result->fetch_assoc();
    }
    $reg_stmt->close();
    
    // Get all registration history
    $history_sql = "
        SELECT 
            semester_id,
            registration_date,
            status,
            academic_year,
            semester_type,
            created_at
        FROM registrations 
        WHERE student_id = ?
        ORDER BY semester_id ASC
    ";
    
    $history_stmt = $mysqli1->prepare($history_sql);
    $history_stmt->bind_param("s", $student_id);
    $history_stmt->execute();
    $registration_history = $history_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $history_stmt->close();
    
} catch (Exception $e) {
    die("خطأ في قاعدة البيانات: " . $e->getMessage());
}

// Format dates
$current_date = date('Y-m-d');
$current_date_hijri = date('d/m/Y'); // يمكن إضافة تحويل للتاريخ الهجري
$student_dob = $student['date_of_birth'] ?? '';
if ($student_dob) {
    $student_dob = date('d/m/Y', strtotime($student_dob));
}

$last_semester = $registration_data ? $registration_data['semester_id'] : 'غير مسجل';
$last_registration_date = $registration_data['registration_date'] ?? '';
if ($last_registration_date) {
    $last_registration_date = date('d/m/Y', strtotime($last_registration_date));
}

// Calculate academic status
$academic_status = 'غير مسجل';
if ($registration_data) {
    if ($registration_data['status'] === 'active') {
        $academic_status = 'نشط';
    } elseif ($registration_data['status'] === 'completed') {
        $academic_status = 'مكتمل';
    } elseif ($registration_data['status'] === 'frozen') {
        $academic_status = 'مجمد';
    } elseif ($registration_data['status'] === 'withdrawn') {
        $academic_status = 'منسحب';
    }
}
?>

<!DOCTYPE html>
<html dir="rtl" lang="ar">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>تقرير القيد والسجل - <?= e($student['student_name'] ?? '') ?></title>
    
    <!-- Fonts -->
    <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    
    <style>
        /* Print-specific styles */
        @media print {
            body {
                margin: 0;
                padding: 0;
                background: white !important;
                color: black !important;
                font-size: 12pt !important;
            }
            
            .no-print {
                display: none !important;
            }
            
            .print-container {
                border: none !important;
                box-shadow: none !important;
                padding: 0 !important;
                margin: 0 !important;
            }
            
            .page-break {
                page-break-before: always;
            }
            
            /* Ensure colors print correctly */
            .text-primary, .text-success, .text-info {
                color: #000 !important;
            }
            
            .bg-light {
                background-color: #f8f9fa !important;
                -webkit-print-color-adjust: exact;
                print-color-adjust: exact;
            }
            
            .border {
                border: 1px solid #000 !important;
            }
            
            table {
                break-inside: avoid;
            }
        }
        
        /* General styles */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Cairo', sans-serif;
            line-height: 1.6;
            background: #f5f5f5;
            color: #333;
            padding: 20px;
        }
        
        .print-container {
            max-width: 1000px;
            margin: 0 auto;
            background: white;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 0 20px rgba(0,0,0,0.1);
        }
        
        /* Header */
        .report-header {
            text-align: center;
            margin-bottom: 30px;
            padding-bottom: 20px;
            border-bottom: 3px double #333;
        }
        
        .university-name {
            font-size: 24px;
            font-weight: 800;
            color: #2c3e50;
            margin-bottom: 5px;
        }
        
        .report-title {
            font-size: 28px;
            font-weight: 700;
            color: #e74c3c;
            margin: 10px 0;
            text-decoration: underline;
        }
        
        .report-subtitle {
            font-size: 18px;
            color: #7f8c8d;
            margin-bottom: 10px;
        }
        
        .report-code {
            background: #2c3e50;
            color: white;
            padding: 5px 15px;
            border-radius: 20px;
            display: inline-block;
            font-weight: 600;
            margin-top: 10px;
        }
        
        /* Student Info Section */
        .info-section {
            margin-bottom: 30px;
            padding: 20px;
            border: 1px solid #ddd;
            border-radius: 8px;
            background: #f8f9fa;
        }
        
        .section-title {
            font-size: 20px;
            font-weight: 700;
            color: #2596be;
            margin-bottom: 15px;
            padding-bottom: 8px;
            border-bottom: 2px solid #2596be;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .section-title i {
            font-size: 22px;
        }
        
        .info-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 15px;
        }
        
        .info-row {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 8px 0;
            border-bottom: 1px dashed #ddd;
        }
        
        .info-label {
            font-weight: 600;
            color: #2c3e50;
            min-width: 180px;
        }
        
        .info-value {
            font-weight: 500;
            color: #34495e;
            text-align: left;
            flex: 1;
        }
        
        .highlight-value {
            background: #fff3cd;
            padding: 3px 10px;
            border-radius: 5px;
            font-weight: 700;
            color: #856404;
        }
        
        .success-value {
            background: #d4edda;
            padding: 3px 10px;
            border-radius: 5px;
            font-weight: 700;
            color: #155724;
        }
        
        .warning-value {
            background: #fff3cd;
            padding: 3px 10px;
            border-radius: 5px;
            font-weight: 700;
            color: #856404;
        }
        
        /* Academic Status */
        .status-box {
            padding: 15px;
            border-radius: 8px;
            margin: 15px 0;
            text-align: center;
        }
        
        .status-active {
            background: linear-gradient(135deg, #d4edda, #c3e6cb);
            border: 2px solid #28a745;
            color: #155724;
        }
        
        .status-inactive {
            background: linear-gradient(135deg, #f8d7da, #f5c6cb);
            border: 2px solid #dc3545;
            color: #721c24;
        }
        
        .status-warning {
            background: linear-gradient(135deg, #fff3cd, #ffeaa7);
            border: 2px solid #ffc107;
            color: #856404;
        }
        
        /* Registration History */
        .table-container {
            overflow-x: auto;
            margin: 20px 0;
        }
        
        .data-table {
            width: 100%;
            border-collapse: collapse;
            margin: 15px 0;
        }
        
        .data-table th {
            background: #2c3e50;
            color: white;
            padding: 12px;
            text-align: center;
            font-weight: 600;
            border: 1px solid #34495e;
        }
        
        .data-table td {
            padding: 10px;
            text-align: center;
            border: 1px solid #ddd;
        }
        
        .data-table tr:nth-child(even) {
            background: #f8f9fa;
        }
        
        .semester-badge {
            background: #2596be;
            color: white;
            padding: 4px 10px;
            border-radius: 15px;
            font-size: 12px;
            font-weight: 600;
        }
        
        /* Footer */
        .report-footer {
            margin-top: 40px;
            padding-top: 20px;
            border-top: 3px double #333;
            text-align: center;
        }
        
        .signature-area {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 30px;
            margin: 30px 0;
        }
        
        .signature-box {
            text-align: center;
            padding: 15px;
            border-top: 1px solid #333;
        }
        
        .signature-title {
            font-weight: 600;
            margin-bottom: 40px;
        }
        
        .footer-note {
            color: #7f8c8d;
            font-size: 14px;
            margin-top: 20px;
        }
        
        /* Print Controls */
        .print-controls {
            position: fixed;
            top: 20px;
            left: 20px;
            z-index: 1000;
            background: white;
            padding: 15px;
            border-radius: 10px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
            display: flex;
            gap: 10px;
        }
        
        .print-controls button {
            padding: 10px 20px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-weight: 600;
            display: flex;
            align-items: center;
            gap: 8px;
            transition: all 0.3s;
        }
        
        .print-controls button:hover {
            transform: translateY(-2px);
        }
        
        .btn-print {
            background: linear-gradient(135deg, #2596be, #2596be);
            color: white;
        }
        
        .btn-back {
            background: linear-gradient(135deg, #95a5a6, #7f8c8d);
            color: white;
        }
        
        .btn-close {
            background: linear-gradient(135deg, #e74c3c, #c0392b);
            color: white;
        }
        
        /* Responsive */
        @media (max-width: 768px) {
            .print-container {
                padding: 15px;
            }
            
            .info-grid {
                grid-template-columns: 1fr;
            }
            
            .signature-area {
                grid-template-columns: 1fr;
                gap: 20px;
            }
            
            .print-controls {
                top: 10px;
                left: 10px;
                right: 10px;
                flex-wrap: wrap;
                justify-content: center;
            }
            
            .print-controls button {
                flex: 1;
                min-width: 120px;
            }
        }
        
        /* Watermark (for draft) */
        .watermark {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%) rotate(-45deg);
            font-size: 120px;
            color: rgba(0,0,0,0.1);
            pointer-events: none;
            z-index: -1;
            white-space: nowrap;
            font-weight: 900;
        }
    </style>
</head>
<body>
    <!-- Print Controls -->
    <div class="print-controls no-print">
        <button type="button" class="btn-print" onclick="window.print()">
            <i class="fas fa-print"></i> طباعة التقرير
        </button>
        <button type="button" class="btn-back" onclick="window.history.back()">
            <i class="fas fa-arrow-right"></i> العودة
        </button>
        <button type="button" class="btn-close" onclick="window.close()">
            <i class="fas fa-times"></i> إغلاق
        </button>
    </div>
    
    <!-- Watermark -->
    <div class="watermark">
        <?= e($student['university_name_ar'] ?? 'جامعة') ?>
    </div>
    
    <!-- Main Report Container -->
    <div class="print-container">
        <!-- Report Header -->
        <div class="report-header">
            <h1 class="university-name"><?= e($student['university_name_ar'] ?? 'الجامعة') ?></h1>
            <h2 class="report-title">تقرير القيد والسجل الأكاديمي</h2>
            <h3 class="report-subtitle">شهادة حالة التسجيل والالتحاق</h3>
            <div class="report-code">
                رمز التقرير: <?= strtoupper(substr(md5($student_id . time()), 0, 8)) ?>
            </div>
            <div style="margin-top: 10px; font-size: 14px; color: #666;">
                تاريخ الطباعة: <?= $current_date ?> | تاريخ الانشاء: <?= date('Y-m-d H:i:s') ?>
            </div>
        </div>
        
        <!-- Student Information -->
        <div class="info-section">
            <h3 class="section-title">
                <i class="fas fa-user-graduate"></i>
                معلومات الطالب الأساسية
            </h3>
            
            <div class="info-grid">
                <div class="info-row">
                    <span class="info-label">الرقم الجامعي:</span>
                    <span class="info-value highlight-value"><?= e($student['student_id']) ?></span>
                </div>
                
                <div class="info-row">
                    <span class="info-label">اسم الطالب (عربي):</span>
                    <span class="info-value"><?= e($student['student_name'] ?? 'غير محدد') ?></span>
                </div>
                
                <div class="info-row">
                    <span class="info-label">اسم الطالب (إنجليزي):</span>
                    <span class="info-value"><?= e($student['student_name_eng'] ?? 'غير محدد') ?></span>
                </div>
                
                <div class="info-row">
                    <span class="info-label">الجنس:</span>
                    <span class="info-value"><?= $student['gender'] === 'female' ? 'أنثى' : 'ذكر' ?></span>
                </div>
                
                <div class="info-row">
                    <span class="info-label">تاريخ الميلاد:</span>
                    <span class="info-value"><?= $student_dob ?></span>
                </div>
                
                <div class="info-row">
                    <span class="info-label">الهوية الوطنية:</span>
                    <span class="info-value"><?= e($student['national_id'] ?? 'غير محدد') ?></span>
                </div>
                
                <div class="info-row">
                    <span class="info-label">رقم الهاتف:</span>
                    <span class="info-value"><?= e($student['phone_number'] ?? 'غير محدد') ?></span>
                </div>
                
                <div class="info-row">
                    <span class="info-label">البريد الإلكتروني:</span>
                    <span class="info-value"><?= e($student['email'] ?? 'غير محدد') ?></span>
                </div>
            </div>
        </div>
        
        <!-- Academic Information -->
        <div class="info-section">
            <h3 class="section-title">
                <i class="fas fa-university"></i>
                المعلومات الأكاديمية
            </h3>
            
            <div class="info-grid">
                <div class="info-row">
                    <span class="info-label">الكلية:</span>
                    <span class="info-value highlight-value"><?= e($student['college_name_ar'] ?? $student['college_name'] ?? 'غير محدد') ?></span>
                </div>
                
                <div class="info-row">
                    <span class="info-label">القسم/الشعبة:</span>
                    <span class="info-value highlight-value"><?= e($student['section_name_ar'] ?? $student['section_name'] ?? 'غير محدد') ?></span>
                </div>
                
                <div class="info-row">
                    <span class="info-label">الدفعة:</span>
                    <span class="info-value"><?= e($student['batch_name_ar'] ?? $student['batch_name'] ?? 'غير محدد') ?></span>
                </div>
                
                <?php if (!empty($student['program_name'])): ?>
                <div class="info-row">
                    <span class="info-label">البرنامج الدراسي:</span>
                    <span class="info-value"><?= e($student['program_name_ar'] ?? $student['program_name']) ?></span>
                </div>
                <?php endif; ?>
                
                <div class="info-row">
                    <span class="info-label">حالة القبول:</span>
                    <span class="info-value <?= $student['interview_status'] === 'accepted' ? 'success-value' : 'warning-value' ?>">
                        <?= $student['interview_status'] === 'accepted' ? '✓ مقبول' : 'قيد المراجعة' ?>
                    </span>
                </div>
                
                <div class="info-row">
                    <span class="info-label">اللياقة الطبية:</span>
                    <span class="info-value <?= $student['medically_fit'] ? 'success-value' : 'warning-value' ?>">
                        <?= $student['medically_fit'] ? '✓ لائق طبياً' : 'غير لائق' ?>
                    </span>
                </div>
                
                <div class="info-row">
                    <span class="info-label">اكتمال الملف:</span>
                    <span class="info-value <?= $student['profile_completed'] ? 'success-value' : 'warning-value' ?>">
                        <?= $student['profile_completed'] ? '✓ مكتمل' : 'غير مكتمل' ?>
                    </span>
                </div>
            </div>
        </div>
        
        <!-- Registration Status -->
        <div class="info-section">
            <h3 class="section-title">
                <i class="fas fa-clipboard-check"></i>
                حالة التسجيل والالتحاق
            </h3>
            
            <?php if ($registration_data): ?>
                <div class="status-box status-active">
                    <h4 style="margin-bottom: 10px;">
                        <i class="fas fa-check-circle"></i> الطالب مسجل في النظام
                    </h4>
                    <p style="font-size: 18px; margin: 5px 0;">
                        آخر فصل مسجل: <strong>الفصل <?= e($last_semester) ?></strong>
                    </p>
                    <p style="margin: 5px 0;">تاريخ آخر تسجيل: <?= e($last_registration_date) ?></p>
                    <p style="margin: 5px 0;">الحالة الأكاديمية: <strong><?= e($academic_status) ?></strong></p>
                    
                    <?php if (!empty($registration_data['academic_year'])): ?>
                    <p style="margin: 5px 0;">العام الدراسي: <?= e($registration_data['academic_year']) ?></p>
                    <?php endif; ?>
                    
                    <?php if (!empty($registration_data['semester_type'])): ?>
                    <p style="margin: 5px 0;">نوع الفصل: <?= e($registration_data['semester_type']) ?></p>
                    <?php endif; ?>
                </div>
            <?php else: ?>
                <div class="status-box status-warning">
                    <h4 style="margin-bottom: 10px;">
                        <i class="fas fa-exclamation-triangle"></i> الطالب غير مسجل
                    </h4>
                    <p style="font-size: 18px;">لم يتم تسجيل الطالب في أي فصل دراسي حتى الآن</p>
                </div>
            <?php endif; ?>
        </div>
        
        <!-- Registration History -->
        <?php if (!empty($registration_history)): ?>
        <div class="info-section">
            <h3 class="section-title">
                <i class="fas fa-history"></i>
                سجل التسجيلات
            </h3>
            
            <div class="table-container">
                <table class="data-table">
                    <thead>
                        <tr>
                            <th>رقم الفصل</th>
                            <th>تاريخ التسجيل</th>
                            <th>العام الدراسي</th>
                            <th>نوع الفصل</th>
                            <th>الحالة</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($registration_history as $record): ?>
                        <tr>
                            <td>
                                <span class="semester-badge">الفصل <?= e($record['semester_id']) ?></span>
                            </td>
                            <td><?= date('d/m/Y', strtotime($record['registration_date'])) ?></td>
                            <td><?= e($record['academic_year'] ?? '—') ?></td>
                            <td><?= e($record['semester_type'] ?? '—') ?></td>
                            <td>
                                <?php 
                                $status_badge = match($record['status']) {
                                    'active' => '<span style="background: #28a745; color: white; padding: 3px 8px; border-radius: 12px; font-size: 12px;">نشط</span>',
                                    'completed' => '<span style="background: #17a2b8; color: white; padding: 3px 8px; border-radius: 12px; font-size: 12px;">مكتمل</span>',
                                    'frozen' => '<span style="background: #ffc107; color: #000; padding: 3px 8px; border-radius: 12px; font-size: 12px;">مجمد</span>',
                                    'withdrawn' => '<span style="background: #dc3545; color: white; padding: 3px 8px; border-radius: 12px; font-size: 12px;">منسحب</span>',
                                    default => '<span style="background: #6c757d; color: white; padding: 3px 8px; border-radius: 12px; font-size: 12px;">غير محدد</span>'
                                };
                                echo $status_badge;
                                ?>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
            
            <div style="margin-top: 15px; padding: 10px; background: #e8f4fd; border-radius: 5px;">
                <p style="margin: 0; font-weight: 600; color: #2c3e50;">
                    <i class="fas fa-info-circle me-2"></i>
                    إجمالي عدد الفصول المسجلة: <?= count($registration_history) ?> فصل
                </p>
            </div>
        </div>
        <?php endif; ?>
        
        <!-- Additional Information -->
        <div class="info-section">
            <h3 class="section-title">
                <i class="fas fa-info-circle"></i>
                معلومات إضافية
            </h3>
            
            <div class="info-grid">
                <div class="info-row">
                    <span class="info-label">تاريخ إنشاء السجل:</span>
                    <span class="info-value"><?= date('d/m/Y H:i', strtotime($student['created_at'])) ?></span>
                </div>
                
                <div class="info-row">
                    <span class="info-label">تاريخ آخر تحديث:</span>
                    <span class="info-value"><?= date('d/m/Y H:i', strtotime($student['updated_at'])) ?></span>
                </div>
                
                <?php if (!empty($student['admission_type'])): ?>
                <div class="info-row">
                    <span class="info-label">نوع القبول:</span>
                    <span class="info-value"><?= e($student['admission_type']) ?></span>
                </div>
                <?php endif; ?>
                
                <?php if (!empty($student['nationality'])): ?>
                <div class="info-row">
                    <span class="info-label">الجنسية:</span>
                    <span class="info-value"><?= e($student['nationality']) ?></span>
                </div>
                <?php endif; ?>
                
                <?php if (!empty($student['address'])): ?>
                <div class="info-row">
                    <span class="info-label">العنوان:</span>
                    <span class="info-value"><?= e($student['address']) ?></span>
                </div>
                <?php endif; ?>
            </div>
        </div>
        
        <!-- Footer & Signatures -->
        <div class="report-footer">
            <div class="signature-area">
                <div class="signature-box">
                    <div class="signature-title">عميد الكلية</div>
                    <div style="margin-top: 50px; height: 1px;"></div>
                </div>
                
                <div class="signature-box">
                    <div class="signature-title">رئيس القسم</div>
                    <div style="margin-top: 50px; height: 1px;"></div>
                </div>
                
                <div class="signature-box">
                    <div class="signature-title">مسؤول القبول والتسجيل</div>
                    <div style="margin-top: 50px; height: 1px;"></div>
                </div>
            </div>
            
            <div class="footer-note">
                <p>
                    <i class="fas fa-shield-alt me-2"></i>
                    هذا التقرير معتمد إلكترونياً من نظام القبول والتسجيل - جميع الحقوق محفوظة
                </p>
                <p style="font-size: 12px; margin-top: 10px;">
                    الرجاء التحقق من صحة المعلومات عبر نظام التسجيل الإلكتروني أو الاتصال بدائرة القبول والتسجيل
                </p>
            </div>
        </div>
    </div>
    
    <!-- JavaScript for Print Functionality -->
    <script>
    document.addEventListener('DOMContentLoaded', function() {
        // Auto-print option (can be enabled by adding ?auto_print=1 to URL)
        const urlParams = new URLSearchParams(window.location.search);
        if (urlParams.get('auto_print') === '1') {
            setTimeout(() => {
                window.print();
            }, 1000);
        }
        
        // Add page break for printing if content is long
        function addPageBreaks() {
            const contentHeight = document.querySelector('.print-container').offsetHeight;
            const pageHeight = 1122; // A4 height in pixels at 96 DPI
            
            if (contentHeight > pageHeight) {
                // Find a good place to add page break
                const sections = document.querySelectorAll('.info-section');
                let cumulativeHeight = 0;
                
                for (let i = 0; i < sections.length; i++) {
                    cumulativeHeight += sections[i].offsetHeight;
                    if (cumulativeHeight > pageHeight && i > 0) {
                        sections[i].classList.add('page-break');
                        cumulativeHeight = sections[i].offsetHeight;
                    }
                }
            }
        }
        
        // Check if we're in print preview
        window.addEventListener('beforeprint', function() {
            addPageBreaks();
            document.body.classList.add('printing');
        });
        
        window.addEventListener('afterprint', function() {
            document.body.classList.remove('printing');
        });
        
        // Keyboard shortcuts
        document.addEventListener('keydown', function(e) {
            // Ctrl+P or Cmd+P for print
            if ((e.ctrlKey || e.metaKey) && e.key === 'p') {
                e.preventDefault();
                window.print();
            }
            // Escape to go back
            if (e.key === 'Escape') {
                window.history.back();
            }
        });
        
        // Show print confirmation
        const printBtn = document.querySelector('.btn-print');
        if (printBtn) {
            printBtn.addEventListener('click', function() {
                if (confirm('هل تريد طباعة تقرير القيد والسجل؟')) {
                    window.print();
                }
            });
        }
    });
    
    // Function to download as PDF (if needed)
    function downloadAsPDF() {
        alert('خاصية تحميل PDF ستتوفر قريباً. استخدم خاصية الطباعة وحفظ كـ PDF.');
    }
    </script>
</body>
</html>
