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

$alert = "";
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Terminal Ledger Generator</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/animate-css/animate.min.css" media="screen" >
<link rel="stylesheet" href="css/lobipanel/lobipanel.min.css" media="screen" >
<link rel="stylesheet" href="css/prism/prism.css" media="screen" >
<link rel="stylesheet" href="css/select2/select2.min.css" >
<link rel="stylesheet" href="css/main.css" media="screen" >
<!-- Additional CSS for ledger -->
<style>
/* ---------- LEDGER SPECIFIC STYLES ---------- */
.table-container{overflow-x:auto;}
.ledger-table{
    width:100%;
    border-collapse:collapse;
    font-size:12px;
}
.ledger-table th{
    background:#343a40;
    color:#fff;
    padding:6px;
    border:1px solid #444;
    text-align:center;
    white-space:nowrap;
    position:sticky;
    top:0;
    z-index:10;
}
.ledger-table td{
    padding:5px;
    border:1px solid #ddd;
    text-align:center;
}
.ledger-table tbody tr:nth-child(even){
    background:#f8f9fa;
}
.ledger-table tbody tr:hover{
    background:#eef2f7;
}
.highlight{background-color:#ffcccc!important;}
.header-info{background:#f8f9fa;padding:15px;border-radius:5px;margin-bottom:15px;}
.subject-code{font-size:11px;color:#666;}
.full-marks{font-size:11px;color:#28a745;font-weight:bold;}
.total-column{background:#e8f5e8!important;font-weight:bold;}
.attendance-column{background:#e3f2fd!important;font-weight:bold;}
.gpa-column{background:#fff3cd!important;font-weight:bold;color:#856404;}
.gp-cell,.grade-cell{font-weight:bold;}
.gp-ng,.grade-ng{color:red!important;}
.gp-abs,.grade-abs{color:#0011ff!important;}

/* ---------- EXPORT CONTROLS ---------- */
.export-controls{
    background:#e9ecef;
    padding:12px;
    border-radius:5px;
    margin-bottom:15px;
    border:1px solid #dee2e6;
}
.export-option{
    display:inline-block;
    margin-right:15px;
    margin-bottom:5px;
}
.export-option label{
    font-size:12px;
    font-weight:normal;
    margin-right:5px;
}

/* ---------- PRINT STYLES ---------- */
@media print{
    body{font-size:11px!important;}
    .no-print{display:none!important;}
    .table-container{margin:0;}
    @page{size:landscape;margin:5mm;}
    .ledger-table{font-size:10px!important;}
    .ledger-table th{padding:4px!important;}
    .ledger-table td{padding:3px!important;}
    .header-info{padding:10px!important;margin-bottom:10px!important;}
}

/* ---------- FILTER BOX ---------- */
.filter-box{
    background:#fff;
    padding:15px;
    border:1px solid #ddd;
    margin-bottom:15px;
    border-radius:5px;
}
.filter-box label{
    font-size:13px;
    font-weight:600;
    margin-bottom:2px;
}
</style>
<script src="js/modernizr/modernizr.min.js"></script>

</head>


<body class="top-navbar-fixed">
    <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">
                        <div class="row page-title-div">
                            <div class="col-md-6">
                                <h2 class="title">Terminal Ledger Generator</h2>
                            </div>
                            <div class="col-md-6 text-right">
                                <small><i class="fa fa-info-circle"></i> Generate marks/grade ledgers for terminal exams</small>
                            </div>
                        </div>
                        <div class="row breadcrumb-div">
                            <div class="col-md-6">
                                <ul class="breadcrumb">
                                    <li><a href="dashboard.php"><i class="fa fa-home"></i> Home</a></li>
                                    <li> Reports</li>
                                    <li class="active">Terminal Ledger</li>
                                </ul>
                            </div>
                        </div>
                    </div>

                    <div class="container-fluid">
                        <div class="row">
                            <div class="col-md-12">
                                <div class="panel">
                                    <div class="panel-heading">
                                        <div class="panel-title">
                                            <h5>Generate Terminal Ledger</h5>
                                        </div>
                                    </div>
                                    <div class="panel-body">

                                        <!-- Filter Form -->
                                        <form id="ledgerForm">
                                        <div class="filter-box">
                                        <div class="row">

                                            <div class="col-lg-2 col-md-4 mb-3">
                                                <label>Exam Type</label>
                                                <select id="exam_type" name="exam_id" class="form-control" required>
                                                    <option value="">Select</option>
                                                    <?php
                                                    $q="SELECT id,exam_type,exm_year FROM examination_type ORDER BY exm_year DESC";
                                                    $r=$conn->query($q);
                                                    while($row=$r->fetch_assoc()){
                                                        echo "<option value='{$row['id']}'>{$row['exam_type']} - {$row['exm_year']}</option>";
                                                    }
                                                    ?>
                                                </select>
                                            </div>

                                            <div class="col-lg-2 col-md-4 mb-3">
                                                <label>Academic Year</label>
                                                <select id="academic_year" name="academic_year" class="form-control" required>
                                                    <option value="">Select</option>
                                                    <?php
                                                    $q="SELECT DISTINCT academic_year FROM studentsub ORDER BY academic_year DESC";
                                                    $r=$conn->query($q);
                                                    while($row=$r->fetch_assoc()){
                                                        echo "<option value='{$row['academic_year']}'>{$row['academic_year']}</option>";
                                                    }
                                                    ?>
                                                </select>
                                            </div>

                                            <div class="col-lg-2 col-md-4 mb-3">
                                                <label>Class</label>
                                                <select id="class_id" name="class_id" class="form-control" required>
                                                    <option value="">Select</option>
                                                    <?php
                                                    $q="SELECT class_id,class FROM classes WHERE status=1 ORDER BY class_numeric";
                                                    $r=$conn->query($q);
                                                    while($row=$r->fetch_assoc()){
                                                        echo "<option value='{$row['class_id']}'>{$row['class']}</option>";
                                                    }
                                                    ?>
                                                </select>
                                            </div>

                                            <div class="col-lg-2 col-md-4 mb-3">
                                                <label>Section(s)</label>
                                                <select id="section_id" name="section_ids[]" class="form-control" multiple></select>
                                            </div>

                                            <div class="col-lg-2 col-md-4 mb-3">
                                                <label>Ledger Type</label>
                                                <select id="ledger_type" name="ledger_type" class="form-control" required>
                                                    <option value="">Select</option>
                                                    <option value="Marks">Marks Ledger</option>
                                                    <option value="Grade">Grade Ledger</option>
                                                    <option value="Both">Marks + Grade Ledger</option>
                                                </select>
                                            </div>

                                            <div class="col-lg-2 col-md-4 mb-3">
                                                <label>&nbsp;</label>
                                                <button class="btn btn-primary btn-block">
                                                    <i class="fa fa-cogs"></i> Generate
                                                </button>
                                            </div>

                                        </div>
                                        </div>
                                        </form>

                                        <!-- Export Controls (hidden by default) -->
                                        <div id="exportControls" class="export-controls no-print" style="display:none;">
                                            <div class="row">
                                                <div class="col-md-12">
                                                    <h6><i class="fa fa-download"></i> Export Options</h6>
                                                    <div class="d-flex flex-wrap align-items-center">
                                                        <div class="export-option">
                                                            <label>Page Size:</label>
                                                            <select id="pageSize" class="form-control form-control-sm" style="width:100px;display:inline-block;">
                                                                <option value="a4">A4</option>
                                                                <option value="letter">Letter</option>
                                                                <option value="legal">Legal</option>
                                                            </select>
                                                        </div>
                                                        
                                                        <div class="export-option">
                                                            <label>Orientation:</label>
                                                            <select id="pageOrientation" class="form-control form-control-sm" style="width:120px;display:inline-block;">
                                                                <option value="landscape" selected>Landscape</option>
                                                                <option value="portrait">Portrait</option>
                                                            </select>
                                                        </div>
                                                        
                                                        <div class="export-option">
                                                            <label>Font Scale:</label>
                                                            <select id="fontScale" class="form-control form-control-sm" style="width:100px;display:inline-block;">
                                                                <option value="0.8">Small</option>
                                                                <option value="1.0" selected>Normal</option>
                                                                <option value="1.2">Large</option>
                                                                <option value="1.4">Extra Large</option>
                                                            </select>
                                                        </div>
                                                        
                                                        <div class="export-option">
                                                            <label>Margin:</label>
                                                            <select id="pageMargin" class="form-control form-control-sm" style="width:90px;display:inline-block;">
                                                                <option value="5">5 mm</option>
                                                                <option value="8" selected>8 mm</option>
                                                                <option value="10">10 mm</option>
                                                            </select>
                                                        </div>
                                                        
                                                        <div style="flex-grow:1;"></div>
                                                        
                                                        <div>
                                                            <button id="exportPdf" class="btn btn-success btn-sm">
                                                                <i class="fa fa-file-pdf-o"></i> PDF
                                                            </button>
                                                            
                                                            <button id="exportExcel" class="btn btn-primary btn-sm">
                                                                <i class="fa fa-file-excel-o"></i> Excel
                                                            </button>
                                                            
                                                            <button id="printPage" class="btn btn-info btn-sm">
                                                                <i class="fa fa-print"></i> Print
                                                            </button>
                                                            
                                                            <button onclick="window.location.reload()" class="btn btn-secondary btn-sm">
                                                                <i class="fa fa-refresh"></i> Refresh
                                                            </button>
                                                        </div>
                                                    </div>
                                                    <small class="text-muted mt-2 d-block">
                                                        <i class="fa fa-lightbulb-o"></i> Tip: Use "Large" font scale and Landscape orientation for best readability
                                                    </small>
                                                </div>
                                            </div>
                                        </div>

                                        <!-- Ledger Results Area -->
                                        <div id="ledger_result" style="min-height:200px;"></div>

                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>


<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>
<!-- Include export libraries -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.17.5/xlsx.full.min.js"></script>
<!-- Include sortable tables -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/tablesort/5.2.1/tablesort.min.js"></script>

<script>
$(document).ready(function(){

    // Initialize select2
    $('select').select2({placeholder:'Select',allowClear:true});

    // Load sections when class is selected
    $('#class_id').change(function(){
        let cid=$(this).val();
        $('#section_id').empty();
        if(!cid) return;

        $.getJSON('ajax/get_sections_by_class_for_ledger.php',{class_id:cid},function(res){
            $.each(res,function(i,r){
                $('#section_id').append(new Option(r.section_name,r.section_id,false,false));
            });
            $('#section_id').trigger('change');
        });
    });

    // Form submission
    $('#ledgerForm').submit(function(e){
        e.preventDefault();
        let t=$('#ledger_type').val();
        let url=(t==='Marks')?'terminal_marksledger.php':(t==='Grade')?'terminal_grade_ledger.php':'terminal_MGledger.php';

        // Show loading state
        $('#ledger_result').html(`
            <div class="text-center p-5">
                <div class="spinner-border text-primary" role="status">
                    <span class="sr-only">Loading...</span>
                </div>
                <p class="mt-3">Generating ledger report...</p>
            </div>
        `);
        $('#exportControls').hide();
        
        $.post(url,$(this).serialize(),function(html){
            $('#ledger_result').html(html);
            $('#exportControls').show();
            
            // Make tables sortable
            $('.ledger-table').each(function() {
                new Tablesort(this);
            });
            
            // Initialize export functions
            initializeExportFunctions();
        });
    });

    // Initialize export functions
    function initializeExportFunctions() {
        // PDF Export
        $('#exportPdf').off('click').on('click', function() {
            exportToPDF();
        });
        
        // Excel Export
        $('#exportExcel').off('click').on('click', function() {
            exportToExcel();
        });
        
        // Print
        $('#printPage').off('click').on('click', function() {
            printLedger();
        });
    }

    // PDF Export Function
    function exportToPDF() {
        const pageSize = $('#pageSize').val();
        const orientation = $('#pageOrientation').val();
        const margin = parseInt($('#pageMargin').val());
        const fontScale = parseFloat($('#fontScale').val());
        
        // Configure page format
        let format;
        switch(pageSize) {
            case 'a4': format = [595.28, 841.89]; break;
            case 'letter': format = [612, 792]; break;
            case 'legal': format = [612, 1008]; break;
            default: format = 'a4';
        }
        
        // Get content for export (clone to avoid affecting original)
        const contentToExport = $('#ledger_result').clone();
        
        // Remove any existing sort indicators
        contentToExport.find('.tablesort-sortable').removeClass('tablesort-sortable');
        contentToExport.find('[data-sort]').removeAttr('data-sort');
        
        // Apply font scaling for better readability
        const baseFontSize = 10;
        const scaledFontSize = baseFontSize * fontScale;
        
        // Configure PDF options with optimized settings
        const options = {
            margin: margin,
            filename: 'Terminal_Ledger_' + new Date().toISOString().slice(0,10) + '.pdf',
            image: { 
                type: 'jpeg', 
                quality: 1.0 
            },
            html2canvas: { 
                scale: 2,
                useCORS: true,
                letterRendering: true,
                windowWidth: contentToExport[0].scrollWidth,
                onclone: function(clonedDoc) {
                    // Apply optimized styles for PDF
                    const styleTag = clonedDoc.createElement('style');
                    styleTag.innerHTML = `
                        /* Base styles */
                        body { 
                            font-family: Arial, sans-serif;
                            font-size: ${11 * fontScale}px !important;
                            margin: 0;
                            padding: 0;
                        }
                        
                        /* Table styles */
                        .table-container { 
                            width: 100% !important;
                            overflow: visible !important;
                        }
                        
                        .ledger-table {
                            width: 100% !important;
                            border-collapse: collapse !important;
                            font-size: ${scaledFontSize}px !important;
                            page-break-inside: auto !important;
                        }
                        
                        .ledger-table th {
                            background: #343a40 !important;
                            color: white !important;
                            padding: ${6 * fontScale}px !important;
                            border: 1px solid #444 !important;
                            text-align: center !important;
                            font-weight: bold !important;
                            font-size: ${scaledFontSize * 0.9}px !important;
                        }
                        
                        .ledger-table td {
                            padding: ${5 * fontScale}px !important;
                            border: 1px solid #ddd !important;
                            text-align: center !important;
                        }
                        
                        .ledger-table tbody tr:nth-child(even) {
                            background: #f8f9fa !important;
                        }
                        
                        /* Special columns */
                        .total-column { 
                            background: #e8f5e8 !important; 
                            font-weight: bold !important; 
                        }
                        .attendance-column { 
                            background: #e3f2fd !important; 
                            font-weight: bold !important; 
                        }
                        .gpa-column { 
                            background: #fff3cd !important; 
                            font-weight: bold !important; 
                            color: #856404 !important; 
                        }
                        
                        /* Header info */
                        .header-info {
                            background: #f8f9fa !important;
                            padding: ${15 * fontScale}px !important;
                            border-radius: 5px !important;
                            margin-bottom: ${15 * fontScale}px !important;
                            font-size: ${14 * fontScale}px !important;
                        }
                        
                        /* Subject reference table */
                        .subject-reference table {
                            font-size: ${scaledFontSize * 0.8}px !important;
                        }
                        
                        /* Page breaks */
                        .page-break {
                            page-break-before: always !important;
                        }
                    `;
                    clonedDoc.head.appendChild(styleTag);
                    
                    // Ensure tables fit on page
                    const tables = clonedDoc.querySelectorAll('.ledger-table');
                    tables.forEach(table => {
                        table.style.width = '100%';
                        table.style.maxWidth = '100%';
                        // Remove any inline styles that might cause overflow
                        table.style.overflow = 'visible';
                    });
                }
            },
            jsPDF: { 
                unit: 'mm', 
                format: format,
                orientation: orientation,
                compress: true
            },
            pagebreak: { 
                mode: ['avoid-all', 'css', 'legacy'],
                before: '.page-break'
            }
        };
        
        // Show loading state
        const exportBtn = $('#exportPdf');
        const originalText = exportBtn.html();
        exportBtn.html('<i class="fa fa-spinner fa-spin"></i> Generating...');
        exportBtn.prop('disabled', true);
        
        // Generate PDF
        html2pdf().set(options).from(contentToExport[0]).save()
            .then(() => {
                // Restore button
                exportBtn.html(originalText);
                exportBtn.prop('disabled', false);
            })
            .catch((error) => {
                console.error('PDF Error:', error);
                alert('Error generating PDF. Please try again.');
                exportBtn.html(originalText);
                exportBtn.prop('disabled', false);
            });
    }

    // Excel Export Function
    function exportToExcel() {
        const tables = $('#ledger_result table');
        if(!tables.length) {
            alert('No table found to export');
            return;
        }
        
        // Create workbook
        const wb = XLSX.utils.book_new();
        
        // Process each table
        tables.each(function(index) {
            const table = this;
            
            // Clone table and remove sort indicators
            const tableClone = $(table).clone();
            tableClone.find('.tablesort-sortable').removeClass('tablesort-sortable');
            tableClone.find('[data-sort]').removeAttr('data-sort');
            
            // Convert to worksheet
            const ws = XLSX.utils.table_to_sheet(tableClone[0], {raw: true});
            
            // Set column widths
            const wscols = [];
            const range = XLSX.utils.decode_range(ws['!ref']);
            for(let C = range.s.c; C <= range.e.c; ++C) {
                let maxWidth = 15; // Minimum width
                for(let R = range.s.r; R <= range.e.r; ++R) {
                    const cell = XLSX.utils.encode_cell({c:C, r:R});
                    if(ws[cell] && ws[cell].v) {
                        const cellText = ws[cell].v.toString();
                        const cellWidth = cellText.length;
                        if(cellWidth > maxWidth) maxWidth = Math.min(cellWidth, 50);
                    }
                }
                wscols.push({wch: maxWidth});
            }
            ws['!cols'] = wscols;
            
            // Add worksheet to workbook
            const sheetName = index === 0 ? 'Ledger' : ('Reference_' + (index + 1));
            XLSX.utils.book_append_sheet(wb, ws, sheetName);
        });
        
        // Save file
        XLSX.writeFile(wb, 'Terminal_Ledger_' + new Date().toISOString().slice(0,10) + '.xlsx');
    }

    // Print Function
    function printLedger() {
        const fontScale = parseFloat($('#fontScale').val());
        
        // Get content for printing
        const contentToPrint = $('#ledger_result').clone();
        
        // Remove sort indicators
        contentToPrint.find('.tablesort-sortable').removeClass('tablesort-sortable');
        contentToPrint.find('[data-sort]').removeAttr('data-sort');
        
        // Create print-optimized document
        const printWindow = window.open('', '_blank', 'width=1200,height=800,toolbar=no,scrollbars=yes');
        
        const printHTML = `
            <!DOCTYPE html>
            <html>
            <head>
                <title>Terminal Ledger - Print</title>
                <meta charset="UTF-8">
                <meta name="viewport" content="width=device-width, initial-scale=1">
                <style>
                    /* Reset and base styles */
                    * { margin: 0; padding: 0; box-sizing: border-box; }
                    body { 
                        font-family: Arial, sans-serif;
                        font-size: ${11 * fontScale}px !important;
                        line-height: 1.4;
                        color: #000;
                        padding: 10px;
                        background: white;
                    }
                    
                    /* Container */
                    .container-fluid { 
                        width: 100%;
                        max-width: 100%;
                        margin: 0 auto;
                        padding: 0;
                    }
                    
                    /* Header info */
                    .header-info {
                        background: #f8f9fa;
                        padding: 15px;
                        border: 1px solid #ddd;
                        border-radius: 5px;
                        margin-bottom: 15px;
                        text-align: center;
                        font-size: ${14 * fontScale}px !important;
                    }
                    
                    .header-info h4 {
                        font-size: ${18 * fontScale}px !important;
                        margin-bottom: 5px;
                        color: #333;
                    }
                    
                    .header-info h5 {
                        font-size: ${16 * fontScale}px !important;
                        margin: 10px 0;
                        color: #555;
                    }
                    
                    .header-info p {
                        margin: 3px 0;
                        color: #666;
                    }
                    
                    /* Table container */
                    .table-container {
                        width: 100%;
                        overflow: visible;
                        margin-bottom: 20px;
                    }
                    
                    /* Ledger table */
                    .ledger-table {
                        width: 100% !important;
                        max-width: 100% !important;
                        border-collapse: collapse !important;
                        border-spacing: 0;
                        font-size: ${10 * fontScale}px !important;
                        table-layout: fixed;
                        page-break-inside: auto;
                    }
                    
                    .ledger-table th {
                        background: #343a40 !important;
                        color: white !important;
                        padding: 6px !important;
                        border: 1px solid #444 !important;
                        text-align: center !important;
                        font-weight: bold !important;
                        font-size: ${10 * fontScale}px !important;
                        white-space: nowrap;
                        position: relative;
                    }
                    
                    .ledger-table td {
                        padding: 5px !important;
                        border: 1px solid #ddd !important;
                        text-align: center !important;
                        vertical-align: middle;
                    }
                    
                    .ledger-table tbody tr:nth-child(even) {
                        background: #f8f9fa !important;
                    }
                    
                    /* Special columns */
                    .total-column { 
                        background: #e8f5e8 !important; 
                        font-weight: bold !important; 
                    }
                    .attendance-column { 
                        background: #e3f2fd !important; 
                        font-weight: bold !important; 
                    }
                    .gpa-column { 
                        background: #fff3cd !important; 
                        font-weight: bold !important; 
                        color: #856404 !important; 
                    }
                    
                    /* Subject reference */
                    .subject-reference {
                        font-size: ${9 * fontScale}px !important;
                        margin-top: 20px;
                    }
                    
                    .subject-reference table {
                        font-size: ${8 * fontScale}px !important;
                        width: 100%;
                    }
                    
                    /* Grade legend */
                    .alert-info {
                        font-size: ${10 * fontScale}px !important;
                        padding: 10px !important;
                        margin-top: 15px;
                    }
                    
                    /* Print-specific styles */
                    @media print {
                        body { 
                            font-size: ${11 * fontScale}px !important;
                            padding: 5px !important;
                        }
                        
                        .header-info {
                            padding: 10px !important;
                            margin-bottom: 10px !important;
                        }
                        
                        .ledger-table {
                            font-size: ${9 * fontScale}px !important;
                        }
                        
                        .ledger-table th {
                            padding: 4px !important;
                            font-size: ${9 * fontScale}px !important;
                        }
                        
                        .ledger-table td {
                            padding: 3px !important;
                        }
                        
                        .no-print { display: none !important; }
                        
                        @page {
                            size: landscape;
                            margin: 5mm;
                        }
                        
                        /* Avoid breaking inside rows */
                        tr { page-break-inside: avoid; }
                        
                        /* Force table headers on each page */
                        thead { display: table-header-group; }
                        
                        /* Remove URLs */
                        a[href]:after { content: none !important; }
                    }
                    
                    /* Page break helper */
                    .page-break {
                        page-break-before: always;
                        margin-top: 20px;
                    }
                </style>
            </head>
            <body>
                <div class="container-fluid">
                    ${contentToPrint.html()}
                </div>
                <script>
                    // Auto print and close
                    window.onload = function() {
                        // Small delay to ensure styles are applied
                        setTimeout(function() {
                            window.print();
                            // Close window after print dialog is closed
                            window.onafterprint = function() {
                                setTimeout(function() {
                                    window.close();
                                }, 100);
                            };
                        }, 300);
                    };
                <\/script>
            </body>
            </html>
        `;
        
        printWindow.document.open();
        printWindow.document.write(printHTML);
        printWindow.document.close();
    }

    // Direct browser printing support
    window.addEventListener('beforeprint', function() {
        const fontScale = parseFloat($('#fontScale').val()) || 1.0;
        
        // Scale fonts for printing
        $('#ledger_result .ledger-table').css('font-size', (10 * fontScale) + 'px');
        $('#ledger_result .header-info').css('font-size', (14 * fontScale) + 'px');
        $('#ledger_result .alert').css('font-size', (11 * fontScale) + 'px');
        
        // Remove sort indicators
        $('#ledger_result .tablesort-sortable').removeClass('tablesort-sortable');
        $('#ledger_result [data-sort]').removeAttr('data-sort');
    });

    window.addEventListener('afterprint', function() {
        // Restore original styles
        $('#ledger_result .ledger-table').css('font-size', '');
        $('#ledger_result .header-info').css('font-size', '');
        $('#ledger_result .alert').css('font-size', '');
    });

});
</script>

</body>
</html>