<?php
// card_print_page.php - MODIFIED VERSION WITH MULTIPLE IMAGE FORMATS SUPPORT AND SINGLE IMAGE SELECTION
error_reporting(E_ALL);
ini_set('display_errors', 1);

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

// Initialize variables
$students = [];
$student_count = 0;

// Get student IDs from URL parameter
$student_ids = $_GET['students'] ?? '';
if (empty($student_ids)) {
    die("لم يتم تحديد طلاب للطباعة.");
}

// Convert comma-separated IDs to array
$student_ids_array = explode(',', $student_ids);
$student_ids_array = array_filter($student_ids_array, function($id) {
    return !empty(trim($id));
});

if (empty($student_ids_array)) {
    die("معرفات الطلاب غير صالحة.");
}

// Get students data
try {
    if (!$mysqli1) {
        throw new Exception("فشل الاتصال بقاعدة البيانات.");
    }
    
    // Check if program_id exists in batches or students table
    $hasProgramInStudents = false;
    $hasProgramInBatches = false;
    
    $checkStudents = $mysqli1->query("SHOW COLUMNS FROM students LIKE 'program_id'");
    $hasProgramInStudents = $checkStudents->num_rows > 0;
    
    $checkBatches = $mysqli1->query("SHOW COLUMNS FROM batches LIKE 'program_id'");
    $hasProgramInBatches = $checkBatches->num_rows > 0;
    
    $placeholders = str_repeat('?,', count($student_ids_array) - 1) . '?';
    
    // Build dynamic SQL based on available program field
    if ($hasProgramInBatches) {
        // Program is in batches table
        $sql = "
            SELECT 
                s.student_id, 
                s.student_name, 
                s.student_name_eng,
                s.gender,
                s.national_id,
                s.phone_number,
                s.email,
                s.college_id,
                s.section_id,
                s.batch_id,
                s.created_at,
                sec.name AS section_name,
                b.value AS batch_name,
                c.name AS college_name,
                p.name AS program_name
            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
            LEFT JOIN programs p ON p.id = b.program_id
            WHERE s.student_id IN ($placeholders)
            ORDER BY s.student_id
        ";
    } elseif ($hasProgramInStudents) {
        // Program is in students table
        $sql = "
            SELECT 
                s.student_id, 
                s.student_name, 
                s.student_name_eng,
                s.gender,
                s.national_id,
                s.phone_number,
                s.email,
                s.college_id,
                s.section_id,
                s.batch_id,
                s.created_at,
                sec.name AS section_name,
                b.value AS batch_name,
                c.name AS college_name,
                p.name AS program_name
            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
            LEFT JOIN programs p ON p.id = s.program_id
            WHERE s.student_id IN ($placeholders)
            ORDER BY s.student_id
        ";
    } else {
        // No program available
        $sql = "
            SELECT 
                s.student_id, 
                s.student_name, 
                s.student_name_eng,
                s.gender,
                s.national_id,
                s.phone_number,
                s.email,
                s.college_id,
                s.section_id,
                s.batch_id,
                s.created_at,
                sec.name AS section_name,
                b.value AS batch_name,
                c.name AS college_name,
                '' AS program_name
            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
        ";
    }
    
    $stmt = $mysqli1->prepare($sql);
    if (!$stmt) {
        throw new Exception("خطأ في إعداد الاستعلام: " . $mysqli1->error);
    }
    
    $types = str_repeat('s', count($student_ids_array));
    $stmt->bind_param($types, ...$student_ids_array);
    
    if (!$stmt->execute()) {
        throw new Exception("خطأ في تنفيذ الاستعلام: " . $stmt->error);
    }
    
    $result = $stmt->get_result();
    if (!$result) {
        throw new Exception("خطأ في الحصول على النتائج: " . $stmt->error);
    }
    
    $students = $result->fetch_all(MYSQLI_ASSOC);
    $stmt->close();
    
    // Set student count here
    $student_count = count($students);
    
} catch (Exception $e) {
    die("خطأ في قاعدة البيانات: " . $e->getMessage());
}

if (empty($students)) {
    die("لم يتم العثور على طلاب بالمعلومات المقدمة.");
}

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

// Debug: Ensure student_count is set
if (!isset($student_count)) {
    $student_count = count($students);
}
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>طباعة بطاقات CR80</title>
    <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        /* Reset and base styles */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Cairo', sans-serif;
            background: white;
            padding: 0;
            margin: 0;
        }
        
        /* Print Controls */
        .print-controls {
            background: white;
            padding: 20px;
            border-radius: 12px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
            margin-bottom: 20px;
            text-align: center;
        }
        
        .btn-print {
            background: linear-gradient(135deg, #27ae60, #2ecc71);
            color: white;
            border: none;
            padding: 12px 24px;
            border-radius: 8px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            margin: 0 10px;
        }
        
        .btn-back {
            background: linear-gradient(135deg, #95a5a6, #7f8c8d);
            color: white;
            border: none;
            padding: 12px 24px;
            border-radius: 8px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            margin: 0 10px;
        }
        
        /* CR80 PAGE - ONE CARD PER PAGE */
        .cr80-page {
            width: 54mm;  /* CR80 WIDTH */
            height: 85.6mm; /* CR80 HEIGHT */
            margin: 0;
            padding: 0;
            page-break-after: always;
            display: block;
            position: relative;
        }
        
        /* TABLE THAT FILLS ENTIRE CR80 CARD - WITH BACKGROUND IMAGE */
        .full-card-table {
            width: 100%;
            height: 100%;
            border-collapse: collapse;
            table-layout: fixed;
            border: 0.5px solid #ccc;
            background: url('img/front-background2.png') no-repeat center center;
            background-size: 100% 100%;
            background-position: center;
        }
        
        /* BACK PAGE - SIMPLE DIV WITH BACKGROUND IMAGE */
        .back-page-container {
            width: 100%;
            height: 100%;
        }
        
        .back-image {
            width: 100%;
            height: 100%;
            background: url('img/background.png') no-repeat center center;
            background-size: 100% 100%;
            background-position: center;
        }
        
        /* MODIFIED ROWS: 20%|25%|55% DISTRIBUTION (ADDED SPACE FOR LOGO) */
        .row-logo {
            height: 30%; /* 17.12mm - SPACE FOR LOGO/EMPTY */
            vertical-align: top;
            padding: 0;
        }
        
        .row-image {
            height: 15%; /* 21.4mm */
            vertical-align: middle;
            padding: 0;
            text-align: center;
        }
        
        .row-info {
            height: 90%; /* 47.08mm - INCREASED FOR MORE DATA */
            background: transparent;
            vertical-align: middle;
            padding: 0;
            text-align: center;
        }
        
        /* Logo/University Name */
        .logo-container {
            width: 100%;
            height: 100%;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: flex-start;
            padding-top: 1mm;
        }
        
        .university-name {
            font-family: 'Cairo', sans-serif;
            font-size: 6pt; /* Smaller font for university name */
            font-weight: 800;
            color: #000000;
            text-align: center;
            line-height: 1.2;
            margin-bottom: 0.5mm;
        }
        
        .logo-text {
            font-family: 'Cairo', sans-serif;
            font-size: 5.5pt; /* Even smaller for logo text */
            font-weight: 700;
            color: #000000;
            text-align: center;
            line-height: 1.1;
        }
        
        /* Student photo styling - MODIFIED FOR BETTER SPACING */
        .student-photo-container {
            width: 100%;
            height: 100%;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            padding-top: 1mm; /* Added space from logo */
            
        }
        
        .student-photo {
            width: 22mm;  /* Photo width */
            height:30mm; /* Photo height */
            object-fit: contain;
            border: 1px solid #ddd;
            border-radius: 3mm;
            display: block;
            margin: 0 auto 1mm auto; /* Added bottom margin for spacing */
        }
        
        .photo-placeholder {
            width: 22mm;
            height: 30mm;
            background: linear-gradient(135deg, #f5f5f5, #e0e0e0);
            border: 1px solid #ddd;
            border-radius: 3mm;
            display: flex;
            align-items: center;
            justify-content: center;
            text-align: center;
            margin: 0 auto 1mm auto; /* Added bottom margin for spacing */
        }
        
        .photo-placeholder span {
            font-size: 5pt;
            color: #999;
            line-height: 1.2;
            padding: 0mm;
        }
        
        /* DYNAMIC DATA CONTAINER - FITS IN BOTTOM ROW (55% HEIGHT) */
        .data-container {
            width: 100%;
            height: 100%;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            padding: 2mm 4mm 0.1mm; /* Reduced top padding */
            
        }
        
        /* TEXT STYLES - INCREASED FONT SIZES */
        .data-line {
            font-family: 'Cairo', sans-serif;
            font-weight: 800;
            color: #000000;
            text-align: center;
            width: 100%;
            line-height: 1.3;
            overflow: hidden;
            text-shadow: none;
            direction: rtl;
            white-space: normal;
            word-wrap: break-word;
            word-break: keep-all;
        }
        
        .college-line {
            font-size: 7pt;
            margin-bottom: 0.6mm;
            font-weight: 800;
            color: #000000;
        }
        
        .name-line {
            font-size: 9pt;
            margin-bottom: 0.6mm;
            min-height: 3.5mm;
            display: flex;
            align-items: center;
            justify-content: center;
            text-decoration: underline;
            text-decoration-thickness: 0.7px;
            text-underline-offset: 1.5px;
            padding-bottom: 0.3mm;
        }
        
        .id-line {
            font-size: 7pt;
            margin-bottom: 0.6mm;
            font-weight: 800;
        }
        
        .section-line {
            font-size: 7pt;
            margin-bottom: 0.6mm;
            font-weight: 800;
        }
        
        /* MODIFIED: Program and Batch in same line - BATCH FIRST */
        .program-batch-line {
            font-size: 7pt;
            margin-bottom: 0.6mm;
            font-weight: 800;
            display: flex;
            flex-wrap: wrap;
            justify-content: center;
            align-items: center;
            gap: 3px;
            min-height: 3mm;
        }
        
        .program-text {
            font-weight: 800;
        }
        
        .batch-text {
            font-weight: 800;
            color: #000000;
        }
        
        .separator {
            font-weight: 400;
            color: #666;
            margin: 0 2px;
            font-size: 6pt;
        }
        
        .phone-line {
            font-size: 7pt;
            margin-bottom: 0.6mm;
            font-weight: 800;
        
        }
        
        /* PRINT SETTINGS FOR CR80 PAPER */
        @page {
            size: 54mm 85.6mm; /* CR80 DIMENSIONS */
            margin: 0;
        }
        
        @media print {
            body {
                margin: 0;
                padding: 0;
                width: 54mm;
                height: 85.6mm;
                background: white;
            }
            
            .print-controls {
                display: none !important;
            }
            
            .cr80-page {
                width: 54mm !important;
                height: 85.6mm !important;
                margin: 0 !important;
                padding: 0 !important;
                border: none;
                page-break-after: always;
            }
            
            .full-card-table {
                width: 100% !important;
                height: 100% !important;
                border: none;
                background-size: 100% 100% !important;
                -webkit-print-color-adjust: exact;
                print-color-adjust: exact;
            }
            
            .back-page-container {
                width: 100% !important;
                height: 100% !important;
            }
            
            .data-line {
                color: #000000 !important;
                -webkit-print-color-adjust: exact;
                print-color-adjust: exact;
            }
            
            .name-line {
                text-decoration: underline !important;
                -webkit-print-color-adjust: exact;
                print-color-adjust: exact;
            }
            
            .back-image {
                -webkit-print-color-adjust: exact;
                print-color-adjust: exact;
                background-size: 100% 100% !important;
            }
            
            .student-photo {
                -webkit-print-color-adjust: exact;
                print-color-adjust: exact;
                border: 0.5px solid #ccc !important;
            }
            
            .photo-placeholder {
                -webkit-print-color-adjust: exact;
                print-color-adjust: exact;
                border: 0.5px solid #ccc !important;
            }
            
            .university-name, .logo-text {
                color: #000000 !important;
                -webkit-print-color-adjust: exact;
                print-color-adjust: exact;
            }
        }
        
        /* SCREEN PREVIEW - SCALED UP FOR BETTER VIEWING */
        @media screen {
            body {
                background: #f0f0f0;
                padding: 20px;
                display: flex;
                flex-direction: column;
                align-items: center;
            }
            
            .cr80-page {
                transform: scale(2.5); /* Enlarge for preview */
                transform-origin: top center;
                margin: 40px 0;
                border: 1px dashed #ccc;
            }
            
            .print-controls {
                width: 90%;
                max-width: 800px;
            }
        }
        
        /* Text muted class for print controls */
        .text-muted {
            color: #6c757d;
            font-size: 14px;
            margin: 5px 0;
        }
        
        /* Image format indicator (for debugging) */
        .image-format {
            font-size: 4pt;
            color: #666;
            text-align: center;
            margin-top: 0.5mm;
        }
    </style>
</head>
<body>
    <!-- Print Controls -->
    <div class="print-controls no-print">
        <h2>🖨️ طباعة على ورق CR80</h2>
        <p class="text-muted">عدد البطاقات: <?php 
            $display_count = isset($student_count) && is_numeric($student_count) ? $student_count : (isset($students) ? count($students) : 0);
            echo $display_count;
        ?> بطاقة (<?php 
            echo $display_count * 2;
        ?> صفحة)</p>
        <p class="text-muted">📏 حجم الصفحة: 54mm × 85.6mm (ورق CR80)</p>
        <p class="text-muted">📄 التوزيع: وجه + ظهر لكل بطاقة</p>
        <div style="margin-top: 15px;">
            <button class="btn-print" onclick="window.print()">
                <i class="fas fa-print"></i> طباعة البطاقات
            </button>
            <button class="btn-back" onclick="window.history.back()">
                <i class="fas fa-arrow-right"></i> العودة
            </button>
        </div>
        <div style="margin-top: 10px; font-size: 12px; color: #7f8c8d;">
            💡 كل طالب: صفحة أمامية + صفحة خلفية
        </div>
    </div>

    <!-- CR80 Cards - FRONT AND BACK FOR EACH STUDENT -->
    <?php if (!empty($students)): ?>
        <?php foreach ($students as $student): ?>
        <?php
        // Get the best available photo for this student
        $photo_info = getStudentPhoto($student['student_id']);
        ?>
        <!-- FRONT PAGE -->
        <div class="cr80-page">
            <!-- TABLE WITH ONE COLUMN AND THREE ROWS (20%|25%|55%) -->
            <table class="full-card-table">
                <!-- ROW 1: LOGO/UNIVERSITY NAME SECTION (20%) -->
                <tr>
                    <td class="row-logo">
                        <div class="logo-container">
                       
                        </div>
                    </td>
                </tr>
                
                <!-- ROW 2: STUDENT PHOTO SECTION (25%) -->
                <tr>
                    <td class="row-image">
                        <div class="student-photo-container">
                            <?php if ($photo_info): ?>
                                <img src="<?php echo $photo_info['path']; ?>" 
                                     alt="Student Photo" 
                                     class="student-photo"
                                     onerror="handleImageError(this, '<?php echo $student['student_id']; ?>')">
                                <!-- Debug: Show image format -->
                                <!-- <div class="image-format"><?php echo strtoupper($photo_info['format']); ?> - <?php echo $photo_info['filename']; ?></div> -->
                            <?php else: ?>
                                <div class="photo-placeholder">
                                    <span>لا توجد<br>صورة</span>
                                </div>
                            <?php endif; ?>
                        </div>
                    </td>
                </tr>
                
                <!-- ROW 3: STUDENT INFORMATION SECTION (55%) -->
                <tr>
                    <td class="row-info">
                        <div class="data-container">
                            <!-- Student Name -->
                          
                            <div class="data-line name-line">
                                <?php echo htmlspecialchars($student['student_name'] ?? '—', ENT_QUOTES, 'UTF-8'); ?>
                            </div>
        
                            <!-- College Name -->
                            <div class="data-line college-line">
                                <?php echo htmlspecialchars($student['college_name'] ?? '—', ENT_QUOTES, 'UTF-8'); ?>
                            </div>
                            
                            <!-- Section -->
                            <div class="data-line section-line">
                                القسم: <?php echo htmlspecialchars($student['section_name'] ?? '—', ENT_QUOTES, 'UTF-8'); ?>
                            </div>
                            
                            <!-- MODIFIED: Batch and Program in same line - BATCH FIRST -->
                            <div class="data-line program-batch-line">
                                <?php
                                // Combine batch and program name - BATCH FIRST
                                $program_name = htmlspecialchars($student['program_name'] ?? '', ENT_QUOTES, 'UTF-8');
                                $batch_name = htmlspecialchars($student['batch_name'] ?? '—', ENT_QUOTES, 'UTF-8');
                                
                                if (!empty($batch_name) && !empty($program_name)) {
                                    echo '<span class="batch-text">الدفعة: ' . $batch_name . '</span>';
                                    echo '<span class="program-text">البرنامج: ' . $program_name . '</span>';
                                } elseif (!empty($batch_name)) {
                                    echo '<span class="batch-text">الدفعة: ' . $batch_name . '</span>';
                                } elseif (!empty($program_name)) {
                                    echo '<span class="program-text">البرنامج: ' . $program_name . '</span>';
                                } else {
                                    echo '<span>—</span>';
                                }
                                ?>
                            </div>

                            <!-- Student ID -->
                            <div class="data-line id-line">
                             الرقم:
                                 <strong class="d-block fs-6" dir="RTL"><?= e($student['student_id']) ?></strong>
                            </div>
                            <!-- Phone Number -->
                            <br>
                        </div>
                    </td>
                </tr>
            </table>
        </div>
        
        <!-- BACK PAGE - JUST THE IMAGE -->
        <div class="cr80-page">
            <div class="back-page-container">
                <div class="back-image">
                    <!-- Background image only, no text -->
                </div>
            </div>
        </div>
        <?php endforeach; ?>
    <?php else: ?>
        <div class="print-controls">
            <h3 style="color: red;">⚠️ لم يتم العثور على بيانات الطلاب</h3>
            <p>الرجاء التحقق من معرفات الطلاب المحددة.</p>
        </div>
    <?php endif; ?>

    <script>
        // Function to handle image loading errors
        function handleImageError(img, studentId) {
            console.log('Failed to load image for student:', studentId);
            img.style.display = 'none';
            
            // Create placeholder
            const container = img.parentElement;
            const placeholder = document.createElement('div');
            placeholder.className = 'photo-placeholder';
            placeholder.innerHTML = '<span>لا توجد<br>صورة</span>';
            
            // Replace image with placeholder
            container.appendChild(placeholder);
        }
        
        // Auto-adjust font size for long text
        window.addEventListener('load', function() {
            const adjustTextSize = () => {
                document.querySelectorAll('.data-container').forEach(container => {
                    const lines = container.querySelectorAll('.data-line');
                    const containerHeight = container.offsetHeight;
                    
                    // First pass: check if all lines fit
                    let totalTextHeight = 0;
                    lines.forEach(line => {
                        // Reset font sizes to initial values
                        if (line.classList.contains('name-line')) {
                            line.style.fontSize = '9pt';
                        } else if (line.classList.contains('program-batch-line')) {
                            line.style.fontSize = '7pt';
                            line.style.flexWrap = 'wrap';
                            line.style.gap = '3px';
                        } else {
                            line.style.fontSize = '7pt';
                        }
                        line.style.lineHeight = '1.3';
                        line.style.marginBottom = '0.6mm';
                        totalTextHeight += line.offsetHeight;
                    });
                    
                    // If text is too tall for container, reduce font size gradually
                    if (totalTextHeight > containerHeight * 0.95) {
                        let fontSizeName = 9; // Start with 9pt for name
                        let fontSizeOthers = 7; // Start with 7pt for others
                        let fits = false;
                        
                        // Gradually reduce font size until everything fits
                        while ((fontSizeName >= 6 || fontSizeOthers >= 5) && !fits) {
                            let newTotalHeight = 0;
                            lines.forEach(line => {
                                if (line.classList.contains('name-line')) {
                                    line.style.fontSize = fontSizeName + 'pt';
                                } else {
                                    line.style.fontSize = fontSizeOthers + 'pt';
                                }
                                // Recalculate height
                                newTotalHeight += line.offsetHeight;
                            });
                            
                            if (newTotalHeight <= containerHeight * 0.95) {
                                fits = true;
                            } else {
                                // Reduce both sizes proportionally
                                if (fontSizeName > 6) fontSizeName -= 0.5;
                                if (fontSizeOthers > 5) fontSizeOthers -= 0.5;
                            }
                        }
                    }
                    
                    // Special handling for name line
                    const nameLine = container.querySelector('.name-line');
                    if (nameLine) {
                        const nameText = nameLine.textContent || '';
                        if (nameText.length > 20) {
                            nameLine.style.wordBreak = 'break-word';
                            nameLine.style.lineHeight = '1.2';
                        }
                    }
                    
                    // Special handling for program-batch line
                    const programBatchLine = container.querySelector('.program-batch-line');
                    if (programBatchLine) {
                        const textLength = programBatchLine.textContent?.length || 0;
                        if (textLength > 25) {
                            programBatchLine.style.flexDirection = 'column';
                            programBatchLine.style.gap = '0';
                            programBatchLine.style.lineHeight = '1.1';
                        }
                    }
                });
            };
            
            // Adjust after a short delay to ensure rendering is complete
            setTimeout(adjustTextSize, 100);
            
            // Log image loading status for debugging
            document.querySelectorAll('.student-photo').forEach(img => {
                img.onload = function() {
                    console.log('Image loaded successfully:', this.src);
                };
                img.onerror = function() {
                    console.log('Image failed to load:', this.src);
                };
            });
        });
        
        // Ensure proper print scaling
        window.onbeforeprint = function() {
            document.querySelectorAll('.cr80-page').forEach(page => {
                page.style.transform = 'none';
            });
        };
        
        // Handle browser back button
        document.querySelector('.btn-back').addEventListener('click', function() {
            window.history.back();
        });
    </script>
</body>
</html>
