<?php
include('session_validator.php');
include('includes/db.php');

// Get school details
$school_query = "SELECT * FROM schools LIMIT 1";
$school_result = $conn->query($school_query);
$school = $school_result->fetch_assoc();

// Get current academic year
$current_year = date('Y');
$current_academic_year = $current_year . '-' . ($current_year + 1);
?>
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title><?php echo htmlspecialchars($school['school_name'] ?? 'SRMS'); ?> - Printable Mark Slip</title>
        <link rel="stylesheet" href="css/bootstrap.min.css" media="screen">
        <link rel="stylesheet" href="css/font-awesome.min.css" media="screen">
        <link rel="stylesheet" href="css/select2/select2.min.css">
        <link rel="stylesheet" href="css/main.css" media="screen">
        
        <!-- PDF and Print Libraries -->
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/dom-to-image/2.6.0/dom-to-image.min.js"></script>
        
        <style>
            /* Print Styles */
            @media print {
                body * {
                    visibility: hidden;
                    background: white !important;
                    color: black !important;
                }
                .print-section, .print-section * {
                    visibility: visible !important;
                }
                .print-section {
                    position: absolute !important;
                    left: 0 !important;
                    top: 0 !important;
                    width: 100% !important;
                    background: white !important;
                    padding: 20px !important;
                    margin: 0 !important;
                }
                .no-print, .no-print * {
                    display: none !important;
                }
                .print-header {
                    border-bottom: 2px solid #000 !important;
                    margin-bottom: 15px !important;
                    padding-bottom: 10px !important;
                }
                .markslip-title {
                    font-size: 18px !important;
                    font-weight: bold !important;
                    text-align: center !important;
                    margin: 15px 0 !important;
                    text-decoration: underline !important;
                }
                .markslip-details {
                    border: 1px solid #000 !important;
                    margin-bottom: 15px !important;
                    padding: 12px !important;
                    background: #f9f9f9 !important;
                    border-radius: 5px !important;
                }
                .detail-grid {
                    display: grid !important;
                    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)) !important;
                    gap: 15px !important;
                }
                .detail-item {
                    margin-bottom: 6px !important;
                    font-size: 13px !important;
                    line-height: 1.4 !important;
                }
                .detail-label {
                    font-weight: bold !important;
                    min-width: 100px !important;
                    display: inline-block !important;
                }
                .table {
                    width: 100% !important;
                    border-collapse: collapse !important;
                    margin: 15px 0 !important;
                    font-size: 12px !important;
                }
                .table th, .table td {
                    border: 1px solid #000 !important;
                    padding: 5px !important;
                    text-align: center !important;
                    vertical-align: middle !important;
                }
                .table th {
                    background-color: #f0f0f0 !important;
                    font-weight: bold !important;
                }
                .empty-column {
                    min-height: 30px !important;
                    background: #f9f9f9 !important;
                }
                .signature-area {
                    margin-top: 40px !important;
                    border-top: 1px solid #000 !important;
                    padding-top: 15px !important;
                    font-size: 11px !important;
                }
                .page-break {
                    page-break-after: always !important;
                    clear: both !important;
                }
                .school-logo {
                    max-height: 60px !important;
                    max-width: 150px !important;
                }
                .total-students {
                    font-weight: bold !important;
                    margin-top: 10px !important;
                    padding: 5px !important;
                    background: #e9ecef !important;
                    border-radius: 3px !important;
                    text-align: center !important;
                }
            }
            
            /* Screen Styles */
            body {
                background-color: #f5f5f5;
                font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            }
            
            .main-wrapper {
                background: #f8f9fa;
            }
            
            .print-header {
                background: white;
                padding: 25px;
                border-radius: 8px;
                box-shadow: 0 4px 6px rgba(0,0,0,0.1);
                margin-bottom: 25px;
                border-left: 5px solid #3498db;
                transition: all 0.3s ease;
            }
            
            .print-header:hover {
                box-shadow: 0 6px 12px rgba(0,0,0,0.15);
                transform: translateY(-2px);
            }
            
            .school-logo {
                max-height: 90px;
                max-width: 100%;
                object-fit: contain;
                border-radius: 4px;
                box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            }
            
            .school-info {
                text-align: center;
                padding: 10px;
            }
            
            .school-name {
                font-size: 24px;
                font-weight: 700;
                color: #2c3e50;
                margin-bottom: 8px;
                text-transform: uppercase;
                letter-spacing: 0.5px;
            }
            
            .school-address {
                font-size: 14px;
                color: #5d6d7e;
                margin-bottom: 5px;
                line-height: 1.4;
            }
            
            .school-contact {
                font-size: 13px;
                color: #7f8c8d;
                margin-bottom: 5px;
            }
            
            .markslip-title {
                font-size: 20px;
                font-weight: 700;
                color: #2c3e50;
                text-align: center;
                margin: 25px 0;
                padding: 15px;
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                color: white;
                border-radius: 8px;
                text-transform: uppercase;
                letter-spacing: 1px;
                box-shadow: 0 4px 6px rgba(0,0,0,0.1);
            }
            
            .markslip-details {
                background: white;
                padding: 20px;
                border-radius: 8px;
                margin-bottom: 25px;
                box-shadow: 0 4px 6px rgba(0,0,0,0.1);
                border: 1px solid #e3e6f0;
            }
            
            .detail-grid {
                display: grid;
                grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
                gap: 20px;
            }
            
            .detail-group {
                background: #f8f9fa;
                padding: 15px;
                border-radius: 6px;
                border-left: 4px solid #3498db;
            }
            
            .detail-item {
                margin-bottom: 10px;
                font-size: 14px;
                display: flex;
                align-items: center;
            }
            
            .detail-label {
                font-weight: 600;
                color: #2c3e50;
                min-width: 120px;
                display: inline-block;
                margin-right: 10px;
            }
            
            .detail-value {
                color: #34495e;
                font-weight: 500;
            }
            
            .detail-value.highlight {
                color: #e74c3c;
                font-weight: 700;
            }
            
            .detail-value.special {
                color: #27ae60;
                font-weight: 600;
            }
            
            .table-container {
                background: white;
                border-radius: 8px;
                overflow: hidden;
                box-shadow: 0 4px 6px rgba(0,0,0,0.1);
                margin-bottom: 25px;
                border: 1px solid #e3e6f0;
            }
            
            .table {
                margin: 0;
            }
            
            .table thead th {
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                color: white;
                border: none;
                font-weight: 600;
                text-align: center;
                vertical-align: middle;
                padding: 12px 8px;
                text-transform: uppercase;
                font-size: 13px;
            }
            
            .table tbody tr {
                transition: all 0.2s ease;
            }
            
            .table tbody tr:hover {
                background-color: #f8f9fa;
                transform: translateX(2px);
            }
            
            .empty-column {
                min-height: 40px;
                border: 2px dashed #bdc3c7;
                background-color: #f9f9f9;
                transition: all 0.3s ease;
            }
            
            .empty-column:hover {
                background-color: #e8f4fc;
                border-color: #3498db;
            }
            
            .action-buttons {
                margin: 25px 0;
                padding: 20px;
                background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
                border-radius: 8px;
                border-left: 5px solid #28a745;
                display: flex;
                justify-content: center;
                gap: 15px;
                flex-wrap: wrap;
                box-shadow: 0 4px 6px rgba(0,0,0,0.1);
            }
            
            .btn-print {
                background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
                color: white;
                border: none;
                padding: 12px 30px;
                font-weight: 600;
                border-radius: 6px;
                transition: all 0.3s ease;
                display: flex;
                align-items: center;
                gap: 8px;
                box-shadow: 0 4px 6px rgba(40, 167, 69, 0.3);
            }
            
            .btn-print:hover {
                transform: translateY(-3px);
                box-shadow: 0 6px 12px rgba(40, 167, 69, 0.4);
                background: linear-gradient(135deg, #218838 0%, #1aa179 100%);
            }
            
            .btn-pdf {
                background: linear-gradient(135deg, #dc3545 0%, #fd7e14 100%);
                color: white;
                border: none;
                padding: 12px 30px;
                font-weight: 600;
                border-radius: 6px;
                transition: all 0.3s ease;
                display: flex;
                align-items: center;
                gap: 8px;
                box-shadow: 0 4px 6px rgba(220, 53, 69, 0.3);
            }
            
            .btn-pdf:hover {
                transform: translateY(-3px);
                box-shadow: 0 6px 12px rgba(220, 53, 69, 0.4);
                background: linear-gradient(135deg, #c82333 0%, #e46008 100%);
            }
            
            .btn-generate {
                background: linear-gradient(135deg, #3498db 0%, #2ecc71 100%);
                color: white;
                border: none;
                padding: 12px 30px;
                font-weight: 600;
                border-radius: 6px;
                transition: all 0.3s ease;
                display: flex;
                align-items: center;
                gap: 8px;
                box-shadow: 0 4px 6px rgba(52, 152, 219, 0.3);
            }
            
            .btn-generate:hover {
                transform: translateY(-3px);
                box-shadow: 0 6px 12px rgba(52, 152, 219, 0.4);
                background: linear-gradient(135deg, #2980b9 0%, #27ae60 100%);
            }
            
            .footer-section {
                margin-top: 30px;
                padding: 20px;
                background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
                border-radius: 8px;
                border: 1px solid #dee2e6;
            }
            
            .instructions {
                font-size: 13px;
                color: #495057;
                line-height: 1.6;
            }
            
            .instructions h6 {
                color: #2c3e50;
                font-weight: 700;
                margin-bottom: 12px;
                border-bottom: 2px solid #3498db;
                padding-bottom: 5px;
                display: inline-block;
            }
            
            .teacher-signature {
                margin-top: 40px;
                padding-top: 20px;
                border-top: 2px solid #dee2e6;
                text-align: right;
                font-style: italic;
                color: #495057;
            }
            
            .signature-line {
                border-top: 2px solid #2c3e50;
                width: 250px;
                margin-top: 25px;
                margin-left: auto;
            }
            
            .loading-spinner {
                text-align: center;
                padding: 40px;
                background: white;
                border-radius: 8px;
                box-shadow: 0 4px 6px rgba(0,0,0,0.1);
            }
            
            .spinner-border {
                width: 3rem;
                height: 3rem;
                color: #3498db;
            }
            
            .stats-badge {
                background: linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%);
                border: 2px solid #90caf9;
                color: #1976d2;
                padding: 8px 20px;
                border-radius: 25px;
                font-size: 14px;
                font-weight: 600;
                display: inline-flex;
                align-items: center;
                gap: 8px;
                box-shadow: 0 2px 4px rgba(25, 118, 210, 0.2);
            }
            
            .required-field::after {
                content: " *";
                color: #dc3545;
                font-weight: bold;
            }
            
            .panel {
                border-radius: 8px;
                overflow: hidden;
                box-shadow: 0 4px 6px rgba(0,0,0,0.1);
            }
            
            .panel-heading {
                background: linear-gradient(135deg, #2c3e50 0%, #4a6491 100%);
                color: white;
                padding: 15px 20px;
                border-bottom: none;
            }
            
            .panel-title {
                font-size: 18px;
                font-weight: 600;
            }
            
            .form-group {
                margin-bottom: 20px;
            }
            
            .form-group label {
                font-weight: 600;
                color: #2c3e50;
                margin-bottom: 8px;
                display: flex;
                align-items: center;
                gap: 8px;
            }
            
            .select2-container .select2-selection--single {
                height: 40px !important;
                border: 1px solid #ced4da !important;
                border-radius: 6px !important;
            }
            
            .select2-container--default .select2-selection--single .select2-selection__rendered {
                line-height: 38px !important;
            }
            
            .select2-container--default .select2-selection--single .select2-selection__arrow {
                height: 38px !important;
            }
            
            .form-control {
                border-radius: 6px;
                border: 1px solid #ced4da;
                padding: 8px 12px;
                transition: all 0.3s ease;
            }
            
            .form-control:focus {
                border-color: #3498db;
                box-shadow: 0 0 0 0.2rem rgba(52, 152, 219, 0.25);
            }
            
            .page-title-div {
                background: white;
                padding: 20px;
                border-radius: 8px;
                margin-bottom: 20px;
                box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            }
            
            .title {
                color: #2c3e50;
                font-weight: 700;
                display: flex;
                align-items: center;
                gap: 10px;
            }
            
            .breadcrumb {
                background: #f8f9fa;
                border-radius: 6px;
                padding: 10px 15px;
                margin-bottom: 20px;
            }
            
            .breadcrumb li a {
                color: #3498db;
                font-weight: 500;
            }
            
            .breadcrumb li.active {
                color: #6c757d;
            }
            
            .total-students-badge {
                position: absolute;
                top: 10px;
                right: 10px;
                background: #28a745;
                color: white;
                padding: 5px 15px;
                border-radius: 20px;
                font-size: 12px;
                font-weight: 600;
                z-index: 1;
            }
            
            .alert-info {
                background: linear-gradient(135deg, #d1ecf1 0%, #bee5eb 100%);
                border: 1px solid #bee5eb;
                color: #0c5460;
                border-radius: 6px;
                padding: 15px;
                margin-bottom: 20px;
            }
            
            @media (max-width: 768px) {
                .detail-grid {
                    grid-template-columns: 1fr;
                }
                
                .action-buttons {
                    flex-direction: column;
                    align-items: stretch;
                }
                
                .btn-print, .btn-pdf, .btn-generate {
                    width: 100%;
                    justify-content: center;
                }
                
                .school-info {
                    text-align: center;
                }
            }
        </style>
    </head>
    <body>
        <div class="main-wrapper">
            <?php include('includes/topbar.php'); ?> 
            <div class="content-wrapper">
                <div class="content-container">
                    <?php include('includes/leftbar.php'); ?>  
                    <div class="main-page">
                        <div class="container-fluid">
                            <!-- Page Header -->
                            <div class="row page-title-div no-print">
                                <div class="col-md-6">
                                    <h2 class="title"><i class="fa fa-print mr-2"></i>Printable Mark Slip</h2>
                                </div>
                                <div class="col-md-6 text-right">
                                    <div class="stats-badge">
                                        <i class="fa fa-info-circle mr-1"></i>Generate printable mark slips for manual entry
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Breadcrumb -->
                            <div class="row breadcrumb-div no-print">
                                <div class="col-md-12">
                                    <ul class="breadcrumb">
                                        <li><a href="dashboard.php"><i class="fa fa-home"></i> Home</a></li>
                                        <li><a href="#"><i class="fa fa-bar-chart"></i> Examination</a></li>
                                        <li class="active"><i class="fa fa-print"></i> Printable Mark Slip</li>
                                    </ul>
                                </div>
                            </div>
                            
                            <!-- Info Alert -->
                            <div class="row no-print">
                                <div class="col-md-12">
                                    <div class="alert-info">
                                        <i class="fa fa-info-circle mr-2"></i>
                                        <strong>Note:</strong> Generate printable mark slips for manual entry. These slips can be printed and used by teachers to write marks manually.
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Main Content -->
                        <div class="container-fluid">
                            <div class="row">
                                <div class="col-md-12">
                                    <div class="panel">
                                        <div class="panel-heading no-print">
                                            <div class="panel-title">
                                                <h5><i class="fa fa-cogs mr-2"></i>Generate Printable Mark Slip</h5>
                                            </div>
                                        </div>
                                        <div class="panel-body">
                                            <!-- Selection Form -->
                                            <form id="generate-form" class="no-print">
                                                <div class="row">
                                                    <div class="form-group col-md-3">
                                                        <label for="class_id" class="required-field">
                                                            <i class="fa fa-graduation-cap mr-1"></i>Class:
                                                        </label>
                                                        <select id="class_id" name="class_id" class="form-control select2" required>
                                                            <option value="">-- Select Class --</option>
                                                            <?php
                                                            $queryclass = "SELECT class_id, class, class_numeric 
                                                                         FROM classes 
                                                                         WHERE status = '1' 
                                                                         ORDER BY class_numeric ASC";
                                                            $resultclass = $conn->query($queryclass);
                                                            while ($row = $resultclass->fetch_assoc()) {
                                                                echo "<option value='" . $row['class_id'] . "'>" . 
                                                                    htmlspecialchars($row['class']) . "</option>";
                                                            }
                                                            ?>
                                                        </select>
                                                    </div>

                                                    <div class="form-group col-md-3">
                                                        <label for="section_id" class="required-field">
                                                            <i class="fa fa-columns mr-1"></i>Section:
                                                        </label>
                                                        <select id="section_id" name="section_id" class="form-control select2" disabled required>
                                                            <option value="">-- Select Section --</option>
                                                        </select>
                                                    </div>

                                                    <div class="form-group col-md-3">
                                                        <label for="exam_id" class="required-field">
                                                            <i class="fa fa-calendar-check-o mr-1"></i>Exam:
                                                        </label>
                                                        <select id="exam_id" name="exam_id" class="form-control select2" disabled required>
                                                            <option value="">-- Select Exam --</option>
                                                        </select>
                                                    </div>

                                                    <div class="form-group col-md-3">
                                                        <label for="subject_id" class="required-field">
                                                            <i class="fa fa-book mr-1"></i>Subject:
                                                        </label>
                                                        <select id="subject_id" name="subject_id" class="form-control select2" disabled required>
                                                            <option value="">-- Select Subject --</option>
                                                        </select>
                                                    </div>
                                                </div>
                                                
                                                <div class="row">
                                                    <div class="form-group col-md-4">
                                                        <label for="academic_year">
                                                            <i class="fa fa-calendar mr-1"></i>Academic Year:
                                                        </label>
                                                        <select id="academic_year" name="academic_year" class="form-control">
                                                            <option value="<?php echo $current_academic_year; ?>"><?php echo $current_academic_year; ?> (Current)</option>
                                                            <?php
                                                            for($i = $current_year - 5; $i <= $current_year + 1; $i++) {
                                                                $next_year = $i + 1;
                                                                $academic_year = $i . '-' . $next_year;
                                                                if($academic_year != $current_academic_year) {
                                                                    echo "<option value='$academic_year'>$academic_year</option>";
                                                                }
                                                            }
                                                            ?>
                                                        </select>
                                                    </div>
                                                    
                                                    <div class="form-group col-md-4">
                                                        <label for="subject_teacher">
                                                            <i class="fa fa-user mr-1"></i>Subject Teacher:
                                                        </label>
                                                        <input type="text" id="subject_teacher" name="subject_teacher" class="form-control" placeholder="Enter subject teacher's name">
                                                    </div>
                                                    
                                                    <div class="form-group col-md-4">
                                                        <label for="students_per_page">
                                                            <i class="fa fa-users mr-1"></i>Students per Page:
                                                        </label>
                                                        <select id="students_per_page" name="students_per_page" class="form-control">
                                                            <option value="25">25 Students</option>
                                                            <option value="30">30 Students</option>
                                                            <option value="40">40 Students</option>
                                                            <option value="50" selected>50 Students</option>
                                                            <option value="0">All Students (No pagination)</option>
                                                        </select>
                                                    </div>
                                                </div>
                                                
                                                <div class="form-actions text-center mt-4">
                                                    <button class="btn btn-generate" type="submit" id="generateBtn" disabled>
                                                        <i class="fa fa-file-text-o mr-1"></i> Generate Mark Slip
                                                    </button>
                                                    <button type="button" class="btn btn-secondary" id="resetBtn">
                                                        <i class="fa fa-refresh mr-1"></i> Reset Form
                                                    </button>
                                                </div>
                                            </form>
                                            
                                            <!-- Loading Indicator -->
                                            <div class="loading-spinner text-center mt-4" id="loadingSpinner" style="display: none;">
                                                <div class="spinner-border" role="status">
                                                    <span class="sr-only">Loading...</span>
                                                </div>
                                                <p class="mt-3">Generating mark slip, please wait...</p>
                                            </div>
                                            
                                            <!-- Printable Mark Slip Area -->
                                            <div id="mark-slip-area" class="mt-4"></div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>  
                    </div>  
                </div>
            </div>
        </div>

        <!-- Scripts -->
               <script src="js/jquery/jquery-2.2.4.min.js"></script>
        <script src="js/bootstrap/bootstrap.min.js"></script>
        <script src="js/pace/pace.min.js"></script>
        <script src="js/lobipanel/lobipanel.min.js"></script>
        <script src="js/iscroll/iscroll.js"></script>
        <script src="js/prism/prism.js"></script>
        <script src="js/select2/select2.min.js"></script>
        <script src="js/main.js"></script>
        
        <!-- DataTables JS -->
        <script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
        <script src="https://cdn.datatables.net/buttons/2.4.1/js/dataTables.buttons.min.js"></script>
        <script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.print.min.js"></script>
        <script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.html5.min.js"></script>
        <script src="https://cdn.datatables.net/responsive/2.5.0/js/dataTables.responsive.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/pdfmake.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/vfs_fonts.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
        
        <script>
            $(document).ready(function () {
                // Initialize Select2
                $('.select2').select2({
                    width: '100%',
                    placeholder: "Select option",
                    allowClear: true
                });
                
                // When class is selected
                $('#class_id').change(function () {
                    var classId = $(this).val();
                    
                    if (classId) {
                        // Enable section select
                        $('#section_id').prop('disabled', false);
                        $('#exam_id').prop('disabled', false);
                        
                        // Clear and load sections
                        $('#section_id').html('<option value="">Loading sections...</option>').trigger('change');
                        loadSections(classId);
                        
                        // Clear and load exams
                        $('#exam_id').html('<option value="">Loading exams...</option>').trigger('change');
                        loadExams(classId);
                        
                        // Disable subject until section is selected
                        $('#subject_id').prop('disabled', true).html('<option value="">-- Select Subject --</option>');
                        
                        // Disable generate button
                        $('#generateBtn').prop('disabled', true);
                    } else {
                        resetForm();
                    }
                });
                
                // When section is selected
                $('#section_id').change(function () {
                    var classId = $('#class_id').val();
                    var sectionId = $(this).val();
                    
                    if (classId && sectionId) {
                        // Enable subject select and load subjects
                        $('#subject_id').prop('disabled', false);
                        loadSubjects(classId, sectionId);
                    } else {
                        $('#subject_id').prop('disabled', true).html('<option value="">-- Select Subject --</option>');
                    }
                });
                
                // When subject is selected
                $('#subject_id').change(function () {
                    if ($(this).val()) {
                        $('#generateBtn').prop('disabled', false);
                    } else {
                        $('#generateBtn').prop('disabled', true);
                    }
                });
                
                // Form submission
                $("#generate-form").submit(function (e) {
                    e.preventDefault();
                    
                    // Validate all required fields
                    var classId = $('#class_id').val();
                    var sectionId = $('#section_id').val();
                    var examId = $('#exam_id').val();
                    var subjectId = $('#subject_id').val();
                    
                    if (!classId || !sectionId || !examId || !subjectId) {
                        Swal.fire({ 
                            icon: 'warning', 
                            title: 'Incomplete Form', 
                            text: 'Please select Class, Section, Exam, and Subject.' 
                        });
                        return false;
                    }
                    
                    // Show loading
                    $("#loadingSpinner").show();
                    $("#generateBtn").prop('disabled', true).html('<i class="fa fa-spinner fa-spin mr-1"></i> Generating...');
                    $("#mark-slip-area").empty();
                    
                    // Get form data
                    var formData = $(this).serialize();
                    
                    $.ajax({
                        type: "POST",
                        url: "ajax/generate_printable_markslip.php",
                        data: formData,
                        dataType: 'json',
                        success: function (result) {
                            $("#loadingSpinner").hide();
                            $("#generateBtn").prop('disabled', false).html('<i class="fa fa-file-text-o mr-1"></i> Generate Mark Slip');
                            
                            if (result.status === 'success') {
                                displayPrintableMarkSlip(result.data);
                            } else {
                                Swal.fire({ 
                                    icon: "error", 
                                    title: "Error", 
                                    text: result.message 
                                });
                            }
                        },
                        error: function (xhr, status, error) {
                            $("#loadingSpinner").hide();
                            $("#generateBtn").prop('disabled', false).html('<i class="fa fa-file-text-o mr-1"></i> Generate Mark Slip');
                            Swal.fire({ 
                                icon: "error", 
                                title: "Error", 
                                text: "Failed to generate mark slip. Please try again." 
                            });
                            console.error("AJAX Error:", status, error, xhr.responseText);
                        }
                    });
                });
                
                // Reset form
                $("#resetBtn").click(function () {
                    resetForm();
                });
                
                // Function to load sections
                function loadSections(classId) {
                    $.ajax({
                        url: 'ajax/get_sections_by_class.php',
                        type: 'GET',
                        dataType: 'json',
                        data: { class_id: classId },
                        success: function (sections) {
                            var options = '<option value="">-- Select Section --</option>';
                            
                            if (sections && sections.length > 0) {
                                sections.forEach(function (section) {
                                    options += '<option value="' + section.section_id + '">' + 
                                              section.section_name + '</option>';
                                });
                            } else {
                                options = '<option value="">No sections available</option>';
                            }
                            
                            $('#section_id').html(options).trigger('change');
                        },
                        error: function () {
                            $('#section_id').html('<option value="">Error loading sections</option>').trigger('change');
                        }
                    });
                }
                
                // Function to load exams
                function loadExams(classId) {
                    $.ajax({
                        url: 'ajax/get_exams_by_class.php',
                        type: 'GET',
                        dataType: 'json',
                        data: { class_id: classId },
                        success: function (exams) {
                            var options = '<option value="">-- Select Exam --</option>';
                            
                            if (exams && exams.length > 0) {
                                exams.forEach(function (exam) {
                                    options += '<option value="' + exam.id + '">' + 
                                              exam.exam_type + ' - ' + exam.exm_year + '</option>';
                                });
                            } else {
                                options = '<option value="">No exams available</option>';
                            }
                            
                            $('#exam_id').html(options).trigger('change');
                        },
                        error: function () {
                            $('#exam_id').html('<option value="">Error loading exams</option>').trigger('change');
                        }
                    });
                }
                
                // Function to load subjects
                function loadSubjects(classId, sectionId) {
                    $.ajax({
                        url: 'ajax/get_subjects_by_class_section.php',
                        type: 'GET',
                        dataType: 'json',
                        data: { 
                            class_id: classId,
                            section_id: sectionId
                        },
                        success: function (data) {
                            var options = '<option value="">-- Select Subject --</option>';
                            
                            if (data.success && data.subjects && data.subjects.length > 0) {
                                data.subjects.forEach(function (subject) {
                                    options += '<option value="' + subject.subject_id + '" ' +
                                              'data-theory="' + (subject.theory_full_marks || 0) + '" ' +
                                              'data-internal="' + (subject.internal_full_marks || 0) + '">' + 
                                              subject.subject_name + ' (' + subject.subject_code + ')' + '</option>';
                                });
                            } else {
                                options = '<option value="">No subjects available</option>';
                            }
                            
                            $('#subject_id').html(options).trigger('change');
                        },
                        error: function () {
                            $('#subject_id').html('<option value="">Error loading subjects</option>').trigger('change');
                        }
                    });
                }
                
                // Reset form function
                function resetForm() {
                    $('#generate-form')[0].reset();
                    $('#class_id').val('').trigger('change');
                    $('#section_id').html('<option value="">-- Select Section --</option>').prop('disabled', true).trigger('change');
                    $('#exam_id').html('<option value="">-- Select Exam --</option>').prop('disabled', true).trigger('change');
                    $('#subject_id').html('<option value="">-- Select Subject --</option>').prop('disabled', true).trigger('change');
                    $('#academic_year').val('<?php echo $current_academic_year; ?>');
                    $('#generateBtn').prop('disabled', true);
                    $('#mark-slip-area').empty();
                    $('.select2').trigger('change');
                    
                    // Show success message
                    Swal.fire({
                        icon: 'success',
                        title: 'Form Reset',
                        text: 'All fields have been reset to default values.',
                        timer: 2000,
                        showConfirmButton: false
                    });
                }
            });
            
            // Function to display printable mark slip
            function displayPrintableMarkSlip(data) {
                var html = '';
                
                // Calculate how many pages needed
                var studentsPerPage = parseInt($('#students_per_page').val()) || 50;
                var totalPages = studentsPerPage > 0 ? Math.ceil(data.students.length / studentsPerPage) : 1;
                
                for (var page = 0; page < totalPages; page++) {
                    var startIndex = page * studentsPerPage;
                    var endIndex = studentsPerPage > 0 ? Math.min(startIndex + studentsPerPage, data.students.length) : data.students.length;
                    var pageStudents = data.students.slice(startIndex, endIndex);
                    var totalMarks = parseInt(data.full_marks_theory) + parseInt(data.full_marks_internal);
                    
                    html += '<div class="print-section" style="position: relative;">';
                    
                    // Add total students badge
                    html += '<div class="total-students-badge no-print" style="position: absolute; top: 10px; right: 10px; background: #28a745; color: white; padding: 5px 15px; border-radius: 20px; font-size: 12px; font-weight: 600;">';
                    html += '<i class="fa fa-users mr-1"></i>' + data.total_students + ' Students';
                    html += '</div>';
                    
                    // School Header
                    html += '<div class="print-header">';
                    html += '<div class="row">';
                    if (data.school.logo) {
                        html += '<div class="col-md-2 text-center">';
                        html += '<img src="uploads/school_logos/' + data.school.logo + '" class="school-logo" alt="School Logo">';
                        html += '</div>';
                        html += '<div class="col-md-8 school-info">';
                    } else {
                        html += '<div class="col-md-12 school-info">';
                    }
                    html += '<div class="school-name">' + (data.school.school_name || 'SCHOOL NAME') + '</div>';
                    html += '<div class="school-address">' + (data.school.address || 'School Address') + '</div>';
                    html += '<div class="school-contact">';
                    if (data.school.phone) html += '<i class="fa fa-phone mr-1"></i>' + data.school.phone + ' | ';
                    if (data.school.email) html += '<i class="fa fa-envelope mr-1"></i>' + data.school.email + ' | ';
                    if (data.school.website) html += '<i class="fa fa-globe mr-1"></i>' + data.school.website;
                    html += '</div>';
                    if (data.school.school_code) {
                        html += '<div class="school-contact mt-2">';
                        html += '<i class="fa fa-id-card mr-1"></i> School Code: ' + data.school.school_code;
                        if (data.school.neb_code) html += ' | NEB Code: ' + data.school.neb_code;
                        if (data.school.ctevt_code) html += ' | CTEVT Code: ' + data.school.ctevt_code;
                        html += '</div>';
                    }
                    html += '<div class="school-contact"><span class="detail-label">Academic Year:</span> <span class="detail-value highlight">' + data.academic_year + '</span></div>';
                    html += '</div>';
                    if (data.school.logo) {
                        html += '<div class="col-md-2 text-right">';
                        html += '<div style="font-size: 12px; color: #666;">';
                        html += '<i class="fa fa-calendar mr-1"></i> Generated: ' + new Date().toLocaleDateString();
                        html += '</div>';
                        html += '</div>';
                    }
                    html += '</div>';
                    html += '</div>';
                    
                    // Mark Slip Title
                    html += '<div class="markslip-title">MARK INPUT SLIP FOR MANUAL ENTRY</div>';
                    
                    // Enhanced Exam Details - 3 columns in 2 rows
                    html += '<div class="markslip-details">';
                    html += '<div class="detail-grid">';
                    
                    // First Column - Exam Information
                    // html += '<div class="detail-group">';
                    // html += '<div style="font-weight: bold; color: #2c3e50; margin-bottom: 10px; border-bottom: 2px solid #3498db; padding-bottom: 5px;">EXAM DETAILS</div>';
                    // html += '<div class="detail-item"><span class="detail-label">Exam:</span> <span class="detail-value">' + data.exam_name + '</span></div>';
                    // html += '<div class="detail-item"><span class="detail-label">Academic Year:</span> <span class="detail-value highlight">' + data.academic_year + '</span></div>';
                    // html += '<div class="detail-item"><span class="detail-label">Generated Date:</span> <span class="detail-value">' + new Date().toLocaleDateString() + '</span></div>';
                    //html += '</div>';
                    
                    // Second Column - Class/Section Information
                    html += '<div class="detail-group">';
                    html += '<div style="font-weight: bold; color: #2c3e50; margin-bottom: 10px; border-bottom: 2px solid #3498db; padding-bottom: 5px;">CLASS DETAILS</div>';
                    html += '<div class="detail-item"><span class="detail-label">Class:</span> <span class="detail-value">' + data.class_name + '</span></div>';
                    html += '<div class="detail-item"><span class="detail-label">Section:</span> <span class="detail-value">' + data.section_name + '</span></div>';
                    html += '<div class="detail-item"><span class="detail-label">Total Students:</span> <span class="detail-value highlight">' + data.total_students + '</span></div>';
                    html += '</div>';
                    
                    // Third Column - Subject Information
                    html += '<div class="detail-group">';
                    html += '<div style="font-weight: bold; color: #2c3e50; margin-bottom: 10px; border-bottom: 2px solid #3498db; padding-bottom: 5px;">SUBJECT DETAILS</div>';
                    html += '<div class="detail-item"><span class="detail-label">Subject:</span> <span class="detail-value">' + data.subject_name + '</span></div>';
                    html += '<div class="detail-item"><span class="detail-label">Subject Code:</span> <span class="detail-value highlight">' + data.subject_code + '</span></div>';
                    html += '<div class="detail-item"><span class="detail-label">Subject Teacher:</span> <span class="detail-value">' + (data.subject_teacher || '_________________') + '</span></div>';
                    html += '</div>';
                    
                    // Fourth Column - Marks Information
                    // html += '<div class="detail-group">';
                    // html += '<div style="font-weight: bold; color: #2c3e50; margin-bottom: 10px; border-bottom: 2px solid #3498db; padding-bottom: 5px;">MARKS INFORMATION</div>';
                    // html += '<div class="detail-item"><span class="detail-label">Theory Marks:</span> <span class="detail-value">' + data.full_marks_theory + '</span></div>';
                    // html += '<div class="detail-item"><span class="detail-label">Internal Marks:</span> <span class="detail-value">' + data.full_marks_internal + '</span></div>';
                    // html += '<div class="detail-item"><span class="detail-label">Total Marks:</span> <span class="detail-value special">' + totalMarks + '</span></div>';
                    // html += '</div>';
                    
                    html += '</div>'; // End detail-grid
                    html += '</div>'; // End markslip-details
                    
                    // Marks Table
                    html += '<div class="table-container">';
                    html += '<table class="table table-bordered">';
                    html += '<thead>';
                    html += '<tr>';
                    html += '<th width="5%">S.N.</th>';
                    html += '<th width="10%">Roll No.</th>';
                    html += '<th width="25%">Student Name</th>';
                    html += '<th width="15%">Exam 1<br><small> ................................ </small></th>';
                    html += '<th width="15%">Exam 2<br><small>................................</small></th>';
                    html += '<th width="15%">Exam 3<br><small>................................</small></th>';
                    html += '<th width="15%">Remarks</th>';
                    html += '</tr>';
                    html += '</thead>';
                    html += '<tbody>';
                    
                    // Student rows
                    if (pageStudents.length > 0) {
                        pageStudents.forEach(function(student, index) {
                            var sn = startIndex + index + 1;
                            var rowClass = index % 2 === 0 ? 'even' : 'odd';
                            html += '<tr class="' + rowClass + '">';
                            html += '<td style="text-align: center; font-weight: 600;">' + sn + '</td>';
                            html += '<td style="text-align: center; font-weight: 600;">' + (student.roll_no || student.symbol_no || '-') + '</td>';
                            html += '<td style="text-align: left; padding-left: 15px;">' + student.student_name + '</td>';
                            html += '<td class="empty-column" contenteditable="true" onfocus="this.style.backgroundColor=\'#e8f4fc\'" onblur="this.style.backgroundColor=\'#f9f9f9\'"></td>';
                            html += '<td class="empty-column" contenteditable="true" onfocus="this.style.backgroundColor=\'#e8f4fc\'" onblur="this.style.backgroundColor=\'#f9f9f9\'"></td>';
                            html += '<td class="empty-column" contenteditable="true" onfocus="this.style.backgroundColor=\'#e8f4fc\'" onblur="this.style.backgroundColor=\'#f9f9f9\'"></td>';
                            html += '<td class="empty-column" contenteditable="true" onfocus="this.style.backgroundColor=\'#e8f4fc\'" onblur="this.style.backgroundColor=\'#f9f9f9\'"></td>';
                            html += '</tr>';
                        });
                    } else {
                        html += '<tr>';
                        html += '<td colspan="7" class="text-center py-4" style="color: #dc3545; font-weight: 600;">No students found in this class-section</td>';
                        html += '</tr>';
                    }
                    
                    html += '</tbody>';
                    html += '</table>';
                    html += '</div>';
                    
                    // Footer Section
                    html += '<div class="row mt-4">';
                    html += '<div class="col-md-6">';
                    html += '<div class="footer-section">';
                    html += '<div class="instructions">';
                    html += '<h6><i class="fa fa-info-circle mr-2"></i>INSTRUCTIONS FOR USE:</h6>';
                    html += '<ul style="margin: 0; padding-left: 20px;">';
                    html += '<li>Write marks clearly in blue/black ink in the empty columns</li>';
                    html += '<li>Total Marks = Theory Marks + Internal Marks</li>';
                    html += '<li>Do not overwrite or use correction fluid</li>';
                    html += '<li>Verify marks before submitting</li>';
                    html += '<li>Sign the slip after entering all marks</li>';
                    html += '<li>Submit completed slip to examination department</li>';
                    html += '</ul>';
                    html += '</div>';
                    html += '</div>';
                    html += '</div>';
                    html += '<div class="col-md-6">';
                    html += '<div class="teacher-signature">';
                    html += '<div style="text-align: center; margin-bottom: 20px; font-size: 12px; color: #666; background: #f8f9fa; padding: 8px; border-radius: 5px;">';
                    html += 'Page ' + (page + 1) + ' of ' + totalPages + ' | Students ' + (startIndex + 1) + ' to ' + endIndex + ' of ' + data.total_students;
                    html += '</div>';
                    html += '<div style="text-align: center;">';
                    html += '<div>_________________________</div>';
                    html += '<div style="font-size: 13px; font-weight: 600; margin-top: 5px;">Signature of Subject Teacher</div>';
                    html += '<div style="font-size: 11px; color: #666; margin-top: 5px;">' + (data.subject_teacher || 'Name of Teacher') + '</div>';
                    html += '</div>';
                    html += '</div>';
                    html += '</div>';
                    html += '</div>';
                    
                    html += '</div>'; // End print-section
                    
                    // Add page break for all but last page
                    if (page < totalPages - 1) {
                        html += '<div class="page-break"></div>';
                    }
                }
                
                // Add action buttons
                html += '<div class="action-buttons no-print">';
                html += '<button onclick="printMarkSlip()" class="btn btn-print"><i class="fa fa-print mr-1"></i> Print Mark Slip</button>';
                html += '<button onclick="downloadPDF()" class="btn btn-pdf"><i class="fa fa-file-pdf-o mr-1"></i> Download as PDF</button>';
                html += '<button onclick="resetForm()" class="btn btn-secondary"><i class="fa fa-refresh mr-1"></i> Generate Another</button>';
                html += '</div>';
                
                // Add success message
                html += '<div class="alert alert-success no-print mt-3" style="background: #d4edda; color: #155724; border: 1px solid #c3e6cb; padding: 15px; border-radius: 5px;">';
                html += '<i class="fa fa-check-circle mr-2"></i> <strong>Mark slip generated successfully!</strong> You can now print or download the mark slip.';
                html += '</div>';
                
                $('#mark-slip-area').html(html);
                
                // Scroll to result
                $('html, body').animate({
                    scrollTop: $("#mark-slip-area").offset().top - 100
                }, 500);
            }
            
            // Enhanced Print function
            function printMarkSlip() {
                const printableSections = document.querySelectorAll('.print-section');
                
                if (printableSections.length === 0) {
                    Swal.fire({
                        icon: 'warning',
                        title: 'No Content',
                        text: 'Please generate a mark slip first before printing.'
                    });
                    return;
                }
                
                // Create a new window for printing
                const printWindow = window.open('', '_blank', 'width=800,height=600');
                
                // Build print content
                let printContent = `
                    <html>
                    <head>
                        <title>Mark Slip - ${$('#class_id option:selected').text()} - ${$('#exam_id option:selected').text()}</title>
                        <style>
                            @media print {
                                body {
                                    background: white !important;
                                    color: black !important;
                                    font-size: 12px !important;
                                    margin: 0 !important;
                                    padding: 20px !important;
                                }
                                .print-section {
                                    page-break-after: always;
                                    margin: 0 !important;
                                    padding: 0 !important;
                                }
                                .print-header {
                                    border-bottom: 2px solid #000 !important;
                                    margin-bottom: 15px !important;
                                    padding-bottom: 10px !important;
                                }
                                .markslip-title {
                                    font-size: 16px !important;
                                    font-weight: bold !important;
                                    text-align: center !important;
                                    margin: 15px 0 !important;
                                    text-decoration: underline !important;
                                }
                                .markslip-details {
                                    border: 1px solid #000 !important;
                                    margin-bottom: 15px !important;
                                    padding: 12px !important;
                                    background: #f9f9f9 !important;
                                }
                                .detail-grid {
                                    display: grid !important;
                                    grid-template-columns: 1fr 1fr !important;
                                    gap: 15px !important;
                                }
                                .detail-item {
                                    margin-bottom: 6px !important;
                                    font-size: 12px !important;
                                    line-height: 1.3 !important;
                                }
                                .detail-label {
                                    font-weight: bold !important;
                                    min-width: 100px !important;
                                    display: inline-block !important;
                                }
                                .table {
                                    width: 100% !important;
                                    border-collapse: collapse !important;
                                    margin: 15px 0 !important;
                                    font-size: 11px !important;
                                }
                                .table th, .table td {
                                    border: 1px solid #000 !important;
                                    padding: 4px !important;
                                    text-align: center !important;
                                }
                                .table th {
                                    background-color: #f0f0f0 !important;
                                    font-weight: bold !important;
                                }
                                .empty-column {
                                    min-height: 25px !important;
                                    background: #f9f9f9 !important;
                                }
                                .signature-area {
                                    margin-top: 40px !important;
                                    border-top: 1px solid #000 !important;
                                    padding-top: 10px !important;
                                    font-size: 10px !important;
                                }
                                .page-break {
                                    page-break-after: always !important;
                                }
                                .school-logo {
                                    max-height: 60px !important;
                                }
                                .no-print {
                                    display: none !important;
                                }
                            }
                            @page {
                                size: A4;
                                margin: 15mm;
                            }
                        </style>
                    </head>
                    <body>
                `;
                
                // Add each section
                printableSections.forEach((section, index) => {
                    const sectionClone = section.cloneNode(true);
                    
                    // Remove no-print elements
                    const noPrintElements = sectionClone.querySelectorAll('.no-print');
                    noPrintElements.forEach(el => el.remove());
                    
                    // Add page number
                    const pageNumber = document.createElement('div');
                    pageNumber.style.textAlign = 'right';
                    pageNumber.style.fontSize = '10px';
                    pageNumber.style.marginBottom = '10px';
                    pageNumber.textContent = `Page ${index + 1} of ${printableSections.length}`;
                    sectionClone.insertBefore(pageNumber, sectionClone.firstChild);
                    
                    printContent += sectionClone.outerHTML;
                    
                    // Add page break except for last section
                    if (index < printableSections.length - 1) {
                        printContent += '<div style="page-break-after: always;"></div>';
                    }
                });
                
                printContent += `
                    </body>
                    </html>
                `;
                
                printWindow.document.open();
                printWindow.document.write(printContent);
                printWindow.document.close();
                
                // Wait a bit for content to load, then print
                setTimeout(() => {
                    printWindow.print();
                    
                    // Close window after printing
                    printWindow.onafterprint = function() {
                        printWindow.close();
                    };
                }, 500);
            }
            
            // Enhanced PDF Download function
            async function downloadPDF() {
                const { jsPDF } = window.jspdf;
                
                if (typeof jsPDF === 'undefined') {
                    Swal.fire({
                        icon: 'warning',
                        title: 'PDF Library Error',
                        text: 'PDF library not loaded. Please check your internet connection.',
                        footer: 'You can still use the Print function and save as PDF from print dialog.'
                    });
                    return;
                }
                
                const printableSections = document.querySelectorAll('.print-section');
                
                if (printableSections.length === 0) {
                    Swal.fire({
                        icon: 'warning',
                        title: 'No Content',
                        text: 'Please generate a mark slip first before downloading.'
                    });
                    return;
                }
                
                // Show loading
                Swal.fire({
                    title: 'Generating PDF...',
                    text: 'This may take a few moments.',
                    allowOutsideClick: false,
                    didOpen: () => {
                        Swal.showLoading();
                    }
                });
                
                try {
                    const pdf = new jsPDF('p', 'mm', 'a4');
                    
                    for (let i = 0; i < printableSections.length; i++) {
                        const section = printableSections[i];
                        
                        // Clone the section
                        const sectionClone = section.cloneNode(true);
                        
                        // Remove no-print elements
                        const noPrintElements = sectionClone.querySelectorAll('.no-print');
                        noPrintElements.forEach(el => el.remove());
                        
                        // Set styles for PDF
                        sectionClone.style.width = '210mm';
                        sectionClone.style.padding = '20mm';
                        sectionClone.style.boxSizing = 'border-box';
                        sectionClone.style.background = 'white';
                        
                        // Add to temporary container
                        const tempContainer = document.createElement('div');
                        tempContainer.style.position = 'fixed';
                        tempContainer.style.left = '-9999px';
                        tempContainer.style.top = '0';
                        tempContainer.style.width = '210mm';
                        tempContainer.style.background = 'white';
                        tempContainer.appendChild(sectionClone);
                        document.body.appendChild(tempContainer);
                        
                        // Convert to canvas
                        const canvas = await html2canvas(sectionClone, {
                            scale: 2,
                            useCORS: true,
                            backgroundColor: '#ffffff',
                            logging: false,
                            width: sectionClone.offsetWidth,
                            height: sectionClone.offsetHeight
                        });
                        
                        // Remove temporary container
                        document.body.removeChild(tempContainer);
                        
                        // Convert canvas to image
                        const imgData = canvas.toDataURL('image/jpeg', 0.9);
                        const imgWidth = 210;
                        const imgHeight = (canvas.height * imgWidth) / canvas.width;
                        
                        // Add page if not first page
                        if (i > 0) {
                            pdf.addPage();
                        }
                        
                        // Add image to PDF
                        pdf.addImage(imgData, 'JPEG', 0, 0, imgWidth, imgHeight);
                        
                        // Add page number
                        pdf.setFontSize(10);
                        pdf.text(`Page ${i + 1} of ${printableSections.length}`, 180, 290);
                    }
                    
                    // Generate filename
                    const className = $('#class_id option:selected').text().replace(/\s+/g, '_');
                    const examName = $('#exam_id option:selected').text().replace(/\s+/g, '_').substring(0, 20);
                    const subjectName = $('#subject_id option:selected').text().split('(')[0].trim().replace(/\s+/g, '_').substring(0, 20);
                    const fileName = `Mark_Slip_${className}_${examName}_${subjectName}_${new Date().toISOString().slice(0,10)}.pdf`;
                    
                    // Save PDF
                    pdf.save(fileName);
                    
                    Swal.fire({
                        icon: 'success',
                        title: 'PDF Downloaded!',
                        text: 'Mark slip has been saved as PDF successfully.',
                        timer: 3000,
                        showConfirmButton: false
                    });
                    
                } catch (error) {
                    console.error('PDF generation error:', error);
                    Swal.fire({
                        icon: 'error',
                        title: 'PDF Generation Failed',
                        text: 'An error occurred while generating the PDF. Please try again.',
                        footer: 'Error: ' + error.message
                    });
                }
            }
        </script>
    </body>
</html>