<!DOCTYPE html>
<html>
<head>
    <!-- TABLES CSS CODE -->
    <?php include"comman/code_css.php"; ?>
    <style>
        @media print {
            .no-print { display: none !important; }
            .print-break { page-break-before: always; }
            body { 
                font-size: 12px; 
                margin: 0; 
                padding: 0; 
                background: white !important;
            }
            .report-container { 
                margin: 0; 
                padding: 20px; 
                box-shadow: none;
                border: none;
            }
            .company-header {
                margin-bottom: 20px;
                padding-bottom: 15px;
                border-bottom: 2px solid #000;
            }
            .company-name {
                font-size: 20px;
                margin: 10px 0;
            }
            .company-details {
                font-size: 12px;
            }
            .report-title {
                font-size: 18px;
                margin: 15px 0;
            }
            .report-period {
                font-size: 14px;
                margin-bottom: 20px;
            }
            .summary-cards {
                display: none !important;
            }
            .pl-table {
                font-size: 11px;
                border-collapse: collapse;
            }
            .pl-table th,
            .pl-table td {
                padding: 6px 8px;
                border: 1px solid #000;
            }
            .pl-table .amount {
                text-align: right;
            }
            .section-title {
                background: #f0f0f0 !important;
                color: #000 !important;
                padding: 8px 12px;
                font-size: 14px;
            }
        }
        
        .report-container {
            background: white;
            padding: 20px;
            margin: 10px;
            border-radius: 5px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        .company-header {
            text-align: center;
            margin-bottom: 30px;
            padding-bottom: 20px;
            border-bottom: 2px solid #3c8dbc;
        }
        
        .company-logo {
            max-height: 80px;
            margin-bottom: 10px;
        }
        
        .company-name {
            font-size: 24px;
            font-weight: bold;
            color: #2c3e50;
            margin: 10px 0;
        }
        
        .company-details {
            font-size: 14px;
            color: #7f8c8d;
            line-height: 1.4;
        }
        
        .report-title {
            text-align: center;
            font-size: 20px;
            font-weight: bold;
            color: #e74c3c;
            margin: 20px 0;
            text-transform: uppercase;
            letter-spacing: 1px;
        }
        
        .report-period {
            text-align: center;
            font-size: 16px;
            color: #7f8c8d;
            margin-bottom: 30px;
        }
        
        .pl-section {
            margin-bottom: 30px;
        }
        
        .section-title {
            background: #3c8dbc;
            color: white;
            padding: 10px 15px;
            font-weight: bold;
            font-size: 16px;
            margin: 0;
            border-radius: 3px 3px 0 0;
        }
        
        .pl-table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 20px;
            background: white;
        }
        
        .pl-table th {
            background: #f8f9fa;
            padding: 12px 15px;
            text-align: left;
            font-weight: bold;
            color: #495057;
            border: 1px solid #dee2e6;
        }
        
        .pl-table td {
            padding: 10px 15px;
            border: 1px solid #dee2e6;
            vertical-align: top;
        }
        
        .pl-table .amount {
            text-align: right;
            font-weight: bold;
        }
        
        .pl-table .subtotal {
            background: #f8f9fa;
            font-weight: bold;
        }
        
        .pl-table .total {
            background: #e9ecef;
            font-weight: bold;
            font-size: 16px;
        }
        
        .pl-table .profit {
            color: #28a745;
            font-weight: bold;
        }
        
        .pl-table .loss {
            color: #dc3545;
            font-weight: bold;
        }
        
        .pl-table .text-success {
            color: #28a745 !important;
            font-weight: bold;
        }
        
        .pl-table .text-danger {
            color: #dc3545 !important;
            font-weight: bold;
        }
        
        .pl-table .subtotal {
            background: #f8f9fa;
            font-weight: bold;
            border-top: 2px solid #dee2e6;
        }
        
        .pl-table .subtotal td {
            border-top: 2px solid #dee2e6;
        }
        
        .summary-cards {
            display: flex;
            justify-content: space-around;
            margin: 30px 0;
            flex-wrap: wrap;
        }
        
        .summary-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
            border-radius: 10px;
            text-align: center;
            min-width: 200px;
            margin: 10px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
        }
        
        .summary-card h3 {
            margin: 0 0 10px 0;
            font-size: 14px;
            opacity: 0.9;
        }
        
        .summary-card .amount {
            font-size: 24px;
            font-weight: bold;
            margin: 0;
        }
        
        .export-buttons {
            text-align: center;
            margin: 30px 0;
        }
        
        .export-btn {
            margin: 5px;
            padding: 10px 20px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-weight: bold;
            text-decoration: none;
            display: inline-block;
        }
        
        .export-btn.primary {
            background: #007bff;
            color: white;
        }
        
        .export-btn.success {
            background: #28a745;
            color: white;
        }
        
        .export-btn.warning {
            background: #ffc107;
            color: #212529;
        }
        
        .export-btn.info {
            background: #17a2b8;
            color: white;
        }
        
        .export-btn.danger {
            background: #dc3545;
            color: white;
        }
        
        .loading {
            text-align: center;
            padding: 50px;
            color: #7f8c8d;
        }
        
        .error {
            text-align: center;
            padding: 50px;
            color: #dc3545;
        }
        
        /* Date Range Picker Alignment */
        .daterangepicker {
            z-index: 9999 !important;
        }
        
        .daterangepicker .ranges {
            width: 200px;
        }
        
        .daterangepicker .ranges ul {
            list-style: none;
            margin: 0;
            padding: 0;
        }
        
        .daterangepicker .ranges li {
            padding: 8px 12px;
            cursor: pointer;
            border-bottom: 1px solid #eee;
        }
        
        .daterangepicker .ranges li:hover {
            background-color: #f5f5f5;
        }
        
        .daterangepicker .ranges li.active {
            background-color: #3c8dbc;
            color: white;
        }
        
        /* Form alignment improvements */
        .form-group label {
            font-weight: 600;
            margin-bottom: 5px;
        }
        
        .btn-block {
            width: 100%;
        }
        
        /* Additional print optimizations */
        .printing .report-container {
            max-width: none;
            margin: 0;
            padding: 20px;
        }
        
        .printing .company-header {
            page-break-inside: avoid;
        }
        
        .printing .pl-section {
            page-break-inside: avoid;
            margin-bottom: 20px;
        }
        
        .printing .pl-table {
            page-break-inside: avoid;
        }
        
        /* Loading states for export buttons */
        .export-btn.loading {
            opacity: 0.6;
            cursor: not-allowed;
        }
        
        .export-btn.loading::after {
            content: " ⏳";
        }
        
        /* Preview Modal Styles */
        .modal-lg {
            max-width: 90%;
        }
        
        .modal-body {
            max-height: 70vh;
            overflow-y: auto;
        }
        
        .modal-footer .export-buttons {
            text-align: center;
            width: 100%;
        }
        
        .modal-footer .export-btn {
            margin: 5px 10px;
            min-width: 120px;
        }
        
        .preview-container {
            font-family: 'Arial', sans-serif;
        }
        
        .preview-container .receipt-table {
            width: 100%;
            border-collapse: collapse;
            margin: 10px 0;
            font-size: 11px;
        }
        
        .preview-container .receipt-table th {
            background: #2c3e50;
            color: white;
            padding: 8px 10px;
            text-align: left;
            font-weight: bold;
            font-size: 10px;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }
        
        .preview-container .receipt-table td {
            padding: 6px 10px;
            border-bottom: 1px solid #ddd;
            vertical-align: top;
        }
        
        .preview-container .receipt-table .amount {
            text-align: right;
            font-weight: bold;
        }
        
        .preview-container .receipt-table .section-header {
            background: #34495e !important;
            color: white !important;
            font-weight: bold;
            font-size: 11px;
            padding: 8px 10px;
        }
        
        .preview-container .receipt-table .subtotal {
            background: #f8f9fa;
            font-weight: bold;
            border-top: 2px solid #ddd;
        }
        
        .preview-container .receipt-table .total {
            background: #2c3e50 !important;
            color: white !important;
            font-weight: bold;
            font-size: 12px;
        }
        
        .preview-container .receipt-table .positive {
            color: #27ae60;
        }
        
        .preview-container .receipt-table .negative {
            color: #e74c3c;
        }
        
        @media (max-width: 768px) {
            .summary-cards {
                flex-direction: column;
                align-items: center;
            }
            
            .pl-table {
                font-size: 12px;
            }
            
            .pl-table th,
            .pl-table td {
                padding: 8px;
            }
            
            .col-md-3 {
                margin-bottom: 15px;
            }
        }
    </style>
</head>
<body class="hold-transition skin-blue sidebar-mini">
    <div class="wrapper">
        <?php include"sidebar.php"; ?>
        
        <!-- Content Wrapper. Contains page content -->
        <div class="content-wrapper">
            <!-- Content Header (Page header) -->
            <section class="content-header">
                <h1>
                    <?=$page_title;?>
                    <small>Professional Report</small>
                </h1>
                <ol class="breadcrumb">
                    <li><a href="<?php echo $base_url; ?>dashboard"><i class="fa fa-dashboard"></i>Home</a></li>
                    <li class="active"><?=$page_title;?></li>
                </ol>
            </section>
            
            <section class="content">
                <div class="row">
                    <div class="col-md-12">
                        <!-- Date Range Selection -->
                        <div class="box box-primary no-print">
                            <div class="box-header with-border">
                                <h3 class="box-title">Report Filters</h3>
                            </div>
                            <div class="box-body">
                                <div class="row">
                                    <div class="col-md-3">
                                        <div class="form-group">
                                            <label for="pl-daterange-btn">Select Date Range</label>
                                            <div class="input-group">
                                                <button type="button" class="btn btn-default" id="pl-daterange-btn" name="pl-daterange-btn" style="width: 100%; text-align: left;">
                                                    <span><i class="fa fa-calendar"></i> Select Date Range</span>
                                                    <i class="fa fa-caret-down pull-right"></i>
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-3">
                                        <div class="form-group">
                                            <label>Store</label>
                                            <?php if(store_module() && is_admin()) { 
                                                $this->load->view('store/store_code',array('show_store_select_box'=>true,'store_id'=>get_current_store_id(),'div_length'=>'','label_length'=>'','show_all'=>'true')); 
                                            } else {
                                                echo "<select class='form-control' id='store_id' name='store_id'>";
                                                echo "<option value='".get_current_store_id()."'>".get_store_name(get_current_store_id())."</option>";
                                                echo "</select>";
                                            } ?>
                                        </div>
                                    </div>
                                    <div class="col-md-3">
                                        <div class="form-group">
                                            <label>&nbsp;</label>
                                            <div>
                                                <button type="button" class="btn btn-primary btn-block" id="generate-report">
                                                    <i class="fa fa-refresh"></i> Generate Report
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-3">
                                        <div class="form-group">
                                            <label>&nbsp;</label>
                                            <div>
                                                <button type="button" class="btn btn-success btn-block" onclick="showPreview()">
                                                    <i class="fa fa-eye"></i> Preview & Export
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Report Container -->
                        <div class="report-container" id="report-container" style="display: none;">
                            <!-- Company Header -->
                            <div class="company-header">
                                <?php 
                                $store_info = get_store_details();
                                $logo_path = base_url('uploads/store_logo/'.$store_info->store_logo);
                                ?>
                                <?php if(!empty($store_info->store_logo) && file_exists(FCPATH.'uploads/store_logo/'.$store_info->store_logo)): ?>
                                    <img src="<?php echo $logo_path; ?>" alt="Company Logo" class="company-logo">
                                <?php endif; ?>
                                
                                <div class="company-name"><?php echo $store_info->store_name; ?></div>
                                <div class="company-details">
                                    <?php if(!empty($store_info->address)): ?>
                                        <?php echo $store_info->address; ?><br>
                                    <?php endif; ?>
                                    <?php if(!empty($store_info->mobile)): ?>
                                        Phone: <?php echo $store_info->mobile; ?><br>
                                    <?php endif; ?>
                                    <?php if(!empty($store_info->email)): ?>
                                        Email: <?php echo $store_info->email; ?><br>
                                    <?php endif; ?>
                                    <?php if(!empty($store_info->store_website)): ?>
                                        Website: <?php echo $store_info->store_website; ?>
                                    <?php endif; ?>
                                </div>
                            </div>
                            
                            <!-- Report Title -->
                            <div class="report-title">Profit & Loss Statement</div>
                            <div class="report-period" id="report-period">Period: Loading...</div>
                            
                            
                            <!-- Summary Cards -->
                            <div class="summary-cards" id="summary-cards">
                                <!-- Will be populated by JavaScript -->
                            </div>
                            
                            <!-- Report Content -->
                            <div id="report-content">
                                <!-- Will be populated by JavaScript -->
                            </div>
                        </div>
                        
                        <!-- Loading State -->
                        <div class="loading" id="loading-state" style="display: none;">
                            <i class="fa fa-spinner fa-spin fa-2x"></i>
                            <p>Generating report...</p>
                        </div>
                        
                        <!-- Error State -->
                        <div class="error" id="error-state" style="display: none;">
                            <i class="fa fa-exclamation-triangle fa-2x"></i>
                            <p>Error loading report. Please try again.</p>
                        </div>
                        
                        <!-- Preview Modal -->
                        <div class="modal fade" id="previewModal" tabindex="-1" role="dialog" aria-labelledby="previewModalLabel">
                            <div class="modal-dialog modal-lg" role="document">
                                <div class="modal-content">
                                    <div class="modal-header">
                                        <h4 class="modal-title" id="previewModalLabel">
                                            <i class="fa fa-eye"></i> Report Preview & Export
                                        </h4>
                                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                            <span aria-hidden="true">&times;</span>
                                        </button>
                                    </div>
                                    <div class="modal-body">
                                        <div id="preview-content">
                                            <!-- Preview content will be loaded here -->
                                        </div>
                                    </div>
                                    <div class="modal-footer">
                                        <div class="export-buttons">
                                            <button class="export-btn primary" onclick="printFromPreview()">
                                                <i class="fa fa-print"></i> Print
                                            </button>
                                            <button class="export-btn info" onclick="exportA4FromPreview()">
                                                <i class="fa fa-file-text"></i> A4
                                            </button>
                                            <button class="export-btn danger" onclick="export80MMFromPreview()">
                                                <i class="fa fa-print"></i> 80MM
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </section>
        </div>
        
        <!-- Footer -->
        <?php include"footer.php"; ?>
    </div>

    <!-- Include JavaScript -->
    <?php include"comman/code_js.php"; ?>
    
    <script>
        $(document).ready(function() {
            // Initialize date range picker
            $('#pl-daterange-btn').daterangepicker({
                ranges: {
                    'Today': [moment(), moment()],
                    'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
                    'Last 7 Days': [moment().subtract(6, 'days'), moment()],
                    'Last 30 Days': [moment().subtract(29, 'days'), moment()],
                    'This Month': [moment().startOf('month'), moment().endOf('month')],
                    'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
                },
                startDate: moment().subtract(29, 'days'),
                endDate: moment()
            });
            
            // Generate report on button click
            $('#generate-report').click(function() {
                generateReport();
            });
            
            // Auto-generate report on page load
            generateReport();
        });
        
        function generateReport() {
            var dateRange = $('#pl-daterange-btn').data('daterangepicker');
            var fromDate = dateRange.startDate.format('YYYY-MM-DD');
            var toDate = dateRange.endDate.format('YYYY-MM-DD');
            var storeId = $('#store_id').val();
            
            // Show loading state
            $('#loading-state').show();
            $('#report-container').hide();
            $('#error-state').hide();
            
            // Update report period
            $('#report-period').text('Period: ' + dateRange.startDate.format('MMM DD, YYYY') + ' - ' + dateRange.endDate.format('MMM DD, YYYY'));
            
            // Make AJAX request
            $.ajax({
                url: base_url + 'reports/get_professional_pl_report',
                type: 'POST',
                data: {
                    from_date: fromDate,
                    to_date: toDate,
                    store_id: storeId
                },
                dataType: 'json',
                success: function(response) {
                    $('#loading-state').hide();
                    if (response.error) {
                        $('#error-state').show();
                        console.error('Report Error:', response.message);
                    } else {
                        displayReport(response);
                        $('#report-container').show();
                    }
                },
                error: function(xhr, status, error) {
                    $('#loading-state').hide();
                    $('#error-state').show();
                    console.error('AJAX Error:', error);
                }
            });
        }
        
        function displayReport(data) {
            // Store the report data globally for export functions
            storeReportData(data);
            
            // Get currency settings from response or fallback to session
            var currencyInfo = data.currency_info || {};
            var currencyCode = currencyInfo.currency_code || '<?php echo $this->session->userdata("currency_code") ?: "USD"; ?>';
            var currencySymbol = currencyInfo.symbol || '<?php echo $this->session->userdata("currency_symbol") ?: "$"; ?>';
            var currencyPosition = currencyInfo.position || '<?php echo $this->session->userdata("currency_placement") ?: "Left"; ?>';
            
            // Format currency function
            function formatCurrency(amount) {
                var num = parseFloat(amount);
                
                // Check if it's a whole number
                if (num % 1 === 0) {
                    var formatted = num.toLocaleString('en-US', {
                        minimumFractionDigits: 0,
                        maximumFractionDigits: 0
                    });
                } else {
                    var formatted = num.toLocaleString('en-US', {
                        minimumFractionDigits: 2,
                        maximumFractionDigits: 2
                    });
                }
                
                if (currencyPosition === 'before' || currencyPosition === 'Left') {
                    return currencySymbol + ' ' + formatted;
                } else {
                    return formatted + ' ' + currencySymbol;
                }
            }
            
            // Calculate totals
            var grossProfit = parseFloat(data.gross_profit || 0);
            var netProfit = parseFloat(data.net_profit || 0);
            var totalRevenue = parseFloat(data.sal_total || 0);
            var totalExpenses = parseFloat(data.pur_total || 0) + parseFloat(data.expense_total || 0);
            
            // Format compressed numbers for summary cards
            function formatCompressedNumber(amount) {
                var num = parseFloat(amount);
                if (num === 0) return '0';
                
                var absNum = Math.abs(num);
                var sign = num < 0 ? '-' : '';
                
                if (absNum >= 1e12) {
                    return sign + (absNum / 1e12).toFixed(1) + 'T';
                } else if (absNum >= 1e9) {
                    return sign + (absNum / 1e9).toFixed(1) + 'B';
                } else if (absNum >= 1e6) {
                    return sign + (absNum / 1e6).toFixed(1) + 'M';
                } else if (absNum >= 1e3) {
                    return sign + (absNum / 1e3).toFixed(1) + 'K';
                } else {
                    return sign + absNum.toFixed(0);
                }
            }
            
            // Hide summary cards
            $('#summary-cards').hide();
            
            // Add base currency information
            var currencyInfoHtml = '';
            if (currencyInfo.currency_name) {
                currencyInfoHtml = `
                    <div class="currency-info" style="background: #f8f9fa; padding: 15px; margin: 20px 0; border-radius: 5px; border-left: 4px solid #28a745;">
                        <h4 style="margin: 0 0 10px 0; color: #28a745;">
                            <i class="fa fa-money"></i> Report Currency
                        </h4>
                        <p style="margin: 5px 0; color: #666;">
                            <strong>Base Currency:</strong> ${currencyInfo.currency_name} (${currencyInfo.currency_code})
                        </p>
                        <p style="margin: 5px 0; color: #666; font-size: 12px;">
                            <em>All amounts are displayed in the system's base currency. Multi-currency transactions have been automatically converted using current exchange rates.</em>
                        </p>
                    </div>
                `;
            }
            
            // Generate comprehensive detailed report content
            var reportContent = `
                <div class="company-header" style="text-align: center; margin-bottom: 15px; padding-bottom: 10px; border-bottom: 1px solid #3c8dbc;">
                    <div class="company-name" style="font-size: 18px; font-weight: bold; color: #2c3e50; margin: 5px 0;">
                        ${$('.company-name').first().text() || '<?php echo get_store_name() ? get_store_name() : "Company Name"; ?>'}
                    </div>
                    <div class="company-details" style="font-size: 12px; color: #7f8c8d; line-height: 1.2;">
                        ${$('.company-details').first().html() || '<?php $store = get_store_details(); echo isset($store->address) ? $store->address : "Company Address"; ?><br><?php echo isset($store->mobile) ? "Phone: " . $store->mobile : "Phone: Company Phone"; ?><br><?php echo isset($store->email) ? "Email: " . $store->email : "Email: Company Email"; ?>'}
                    </div>
                </div>
                
                <div class="pl-section">
                    <h3 class="section-title">Opening Stock</h3>
                    <table class="pl-table">
                        <tr>
                            <td>Opening Stock Value</td>
                            <td class="amount">${formatCurrency(data.opening_stock_price || 0)}</td>
                        </tr>
                    </table>
                </div>
                
                <div class="pl-section">
                    <h3 class="section-title">Purchases</h3>
                    <table class="pl-table">
                        <tr>
                            <td>Total Purchase</td>
                            <td class="amount">${formatCurrency(data.pur_total || 0)}</td>
                        </tr>
                        <tr>
                            <td>Total Purchase Tax</td>
                            <td class="amount">${formatCurrency(data.purchase_tax_amt || 0)}</td>
                        </tr>
                        <tr>
                            <td>Total Other Charges of Purchase</td>
                            <td class="amount">${formatCurrency(data.pur_other_charges_amt || 0)}</td>
                        </tr>
                        <tr>
                            <td>Total Discount on Purchase</td>
                            <td class="amount">${formatCurrency(data.purchase_discount_amt || 0)}</td>
                        </tr>
                        <tr>
                            <td>Paid Amount</td>
                            <td class="amount text-success">${formatCurrency(data.purchase_paid_amount || 0)}</td>
                        </tr>
                        <tr>
                            <td>Purchase Due</td>
                            <td class="amount text-danger">${formatCurrency(data.purchase_due_total || 0)}</td>
                        </tr>
                    </table>
                </div>
                
                <div class="pl-section">
                    <h3 class="section-title">Purchase Returns</h3>
                    <table class="pl-table">
                        <tr>
                            <td>Total Purchase Return</td>
                            <td class="amount">${formatCurrency(data.pur_return_total || 0)}</td>
                        </tr>
                        <tr>
                            <td>Total Purchase Return Tax</td>
                            <td class="amount">${formatCurrency(data.purchase_return_tax_amt || 0)}</td>
                        </tr>
                        <tr>
                            <td>Total Other Charges of Purchase Return</td>
                            <td class="amount">${formatCurrency(data.pur_return_other_charges_amt || 0)}</td>
                        </tr>
                        <tr>
                            <td>Total Discount on Purchase Return</td>
                            <td class="amount">${formatCurrency(data.purchase_return_discount_amt || 0)}</td>
                        </tr>
                        <tr>
                            <td>Paid Amount</td>
                            <td class="amount text-success">${formatCurrency(data.purchase_return_paid_amount || 0)}</td>
                        </tr>
                        <tr>
                            <td>Purchase Return Due</td>
                            <td class="amount text-danger">${formatCurrency(data.purchase_return_due_total || 0)}</td>
                        </tr>
                    </table>
                </div>
                
                <div class="pl-section">
                    <h3 class="section-title">Sales</h3>
                    <table class="pl-table">
                        <tr>
                            <td>Sales (Before Tax)</td>
                            <td class="amount">${formatCurrency(data.sal_total || 0)}</td>
                        </tr>
                        <tr>
                            <td>Total Sales Tax</td>
                            <td class="amount">${formatCurrency(data.sales_tax_amt || 0)}</td>
                        </tr>
                        <tr>
                            <td>Total Other Charges of Sales</td>
                            <td class="amount">${formatCurrency(data.sal_other_charges_amt || 0)}</td>
                        </tr>
                        <tr>
                            <td>Total Discount on Sales</td>
                            <td class="amount">${formatCurrency(data.sales_discount_amt || 0)}</td>
                        </tr>
                        <tr>
                            <td>Coupon Discount</td>
                            <td class="amount">${formatCurrency(data.coupon_discount_amt || 0)}</td>
                        </tr>
                        <tr class="subtotal">
                            <td><strong>Total Sales</strong></td>
                            <td class="amount"><strong>${formatCurrency(totalRevenue)}</strong></td>
                        </tr>
                        <tr>
                            <td>Paid Amount</td>
                            <td class="amount text-success">${formatCurrency(data.sales_paid_amount || 0)}</td>
                        </tr>
                        <tr>
                            <td>Sales Due</td>
                            <td class="amount text-danger">${formatCurrency(data.sales_due_total || 0)}</td>
                        </tr>
                    </table>
                </div>
                
                <div class="pl-section">
                    <h3 class="section-title">Sales Returns</h3>
                    <table class="pl-table">
                        <tr>
                            <td>Total Sales Return</td>
                            <td class="amount">${formatCurrency(data.sal_return_total || 0)}</td>
                        </tr>
                        <tr>
                            <td>Total Sales Return Tax</td>
                            <td class="amount">${formatCurrency(data.sales_return_tax_amt || 0)}</td>
                        </tr>
                        <tr>
                            <td>Total Other Charges of Sales Return</td>
                            <td class="amount">${formatCurrency(data.sal_return_other_charges_amt || 0)}</td>
                        </tr>
                        <tr>
                            <td>Coupon Discount</td>
                            <td class="amount">${formatCurrency(data.sales_return_coupon_amt || 0)}</td>
                        </tr>
                        <tr>
                            <td>Total Discount on Sales Return</td>
                            <td class="amount">${formatCurrency(data.sales_return_discount_amt || 0)}</td>
                        </tr>
                        <tr class="subtotal">
                            <td><strong>Return Total</strong></td>
                            <td class="amount"><strong>${formatCurrency(data.sal_return_total || 0)}</strong></td>
                        </tr>
                        <tr>
                            <td>Paid Amount</td>
                            <td class="amount text-success">${formatCurrency(data.sales_return_paid_amount || 0)}</td>
                        </tr>
                        <tr>
                            <td>Sales Return Due</td>
                            <td class="amount text-danger">${formatCurrency(data.sales_return_due_total || 0)}</td>
                        </tr>
                    </table>
                </div>
                
                <div class="pl-section">
                    <h3 class="section-title">Expenses</h3>
                    <table class="pl-table">
                        <tr>
                            <td>Total Expense</td>
                            <td class="amount">${formatCurrency(data.expense_total || 0)}</td>
                        </tr>
                    </table>
                </div>
                
                <div class="pl-section">
                    <h3 class="section-title">Summary</h3>
                    <table class="pl-table">
                        <tr>
                            <td><strong>Gross Profit</strong></td>
                            <td class="amount ${grossProfit >= 0 ? 'profit' : 'loss'}"><strong>${formatCurrency(grossProfit)}</strong></td>
                        </tr>
                        <tr>
                            <td><strong>Total Expenses</strong></td>
                            <td class="amount"><strong>${formatCurrency(data.expense_total || 0)}</strong></td>
                        </tr>
                        <tr class="total">
                            <td><strong>Net Profit/Loss</strong></td>
                            <td class="amount ${netProfit >= 0 ? 'profit' : 'loss'}"><strong>${formatCurrency(netProfit)}</strong></td>
                        </tr>
                    </table>
                </div>
            `;
            
            // Hide the static company header and show the dynamic one
            $('.company-header').hide();
            $('#report-content').html(currencyInfoHtml + reportContent);
            
            // Also hide the static header in the main container
            $('.report-container .company-header').hide();
        }
        
        // Preview and Export functions
        function showPreview() {
            // Get currency settings from stored report data
            var data = currentReportData;
            var currencyInfo = data.currency_info || {};
            var currencyCode = currencyInfo.currency_code || '<?php echo $this->session->userdata("currency_code") ?: "USD"; ?>';
            var currencySymbol = currencyInfo.symbol || '<?php echo $this->session->userdata("currency_symbol") ?: "$"; ?>';
            var currencyPosition = currencyInfo.position || '<?php echo $this->session->userdata("currency_placement") ?: "Left"; ?>';
            
            // Format currency function
            function formatCurrency(amount) {
                var num = parseFloat(amount);
                
                // Check if it's a whole number
                if (num % 1 === 0) {
                    var formatted = num.toLocaleString('en-US', {
                        minimumFractionDigits: 0,
                        maximumFractionDigits: 0
                    });
                } else {
                    var formatted = num.toLocaleString('en-US', {
                        minimumFractionDigits: 2,
                        maximumFractionDigits: 2
                    });
                }
                
                if (currencyPosition === 'before' || currencyPosition === 'Left') {
                    return currencySymbol + ' ' + formatted;
                } else {
                    return formatted + ' ' + currencySymbol;
                }
            }
            
            // Get actual report data
            var reportData = getReportData();
            
            // Generate preview content - use print optimized content
            var previewContent = `
                <div class="preview-container" style="background: white; padding: 20px; border-radius: 5px;">
                    ${generatePrintOptimizedContent(reportData, formatCurrency)}
                    
                    <div class="footer" style="margin-top: 30px; text-align: center; font-size: 10px; color: #666; border-top: 1px solid #ddd; padding-top: 10px;">
                        <div>Generated on: ${new Date().toLocaleString()}</div>
                        <div>This is a computer generated report</div>
                    </div>
                </div>
            `;
            
            // Show preview in modal
            $('#preview-content').html(previewContent);
            $('#previewModal').modal('show');
            
            // Hide any duplicate headers in preview
            setTimeout(function() {
                $('#preview-content .company-header').not(':first').hide();
            }, 100);
        }
        
        function printFromPreview() {
            var previewContent = document.getElementById('preview-content').innerHTML;
            var newWindow = window.open('', '_blank');
            newWindow.document.write(`
                <!DOCTYPE html>
                <html>
                <head>
                    <title>Profit & Loss Report - Print</title>
                    <style>
                        * { margin: 0; padding: 0; box-sizing: border-box; }
                        body { 
                            font-family: 'Arial', sans-serif; 
                            font-size: 12px; 
                            line-height: 1.4;
                            color: #333;
                            background: white;
                        }
                        .receipt-table {
                            width: 100%;
                            border-collapse: collapse;
                            margin: 10px 0;
                            font-size: 11px;
                        }
                        .receipt-table th {
                            background: #2c3e50;
                            color: white;
                            padding: 8px 10px;
                            text-align: left;
                            font-weight: bold;
                            font-size: 10px;
                            text-transform: uppercase;
                            letter-spacing: 0.5px;
                        }
                        .receipt-table td {
                            padding: 6px 10px;
                            border-bottom: 1px solid #ddd;
                            vertical-align: top;
                        }
                        .receipt-table .amount {
                            text-align: right;
                            font-weight: bold;
                        }
                        .receipt-table .section-header {
                            background: #34495e !important;
                            color: white !important;
                            font-weight: bold;
                            font-size: 11px;
                            padding: 8px 10px;
                        }
                        .receipt-table .subtotal {
                            background: #f8f9fa;
                            font-weight: bold;
                            border-top: 2px solid #ddd;
                        }
                        .receipt-table .total {
                            background: #2c3e50 !important;
                            color: white !important;
                            font-weight: bold;
                            font-size: 12px;
                        }
                        .receipt-table .positive {
                            color: #27ae60;
                        }
                        .receipt-table .negative {
                            color: #e74c3c;
                        }
                        @media print {
                            body { margin: 0; padding: 0; }
                            @page { size: A4; margin: 0; }
                        }
                    </style>
                </head>
                <body>
                    ${previewContent}
                </body>
                </html>
            `);
            newWindow.document.close();
            newWindow.print();
        }
        
        function exportA4FromPreview() {
            exportToA4();
        }
        
        function export80MMFromPreview() {
            exportTo80MM();
        }
        
        // Export functions
        function printReport() {
            // Add print-specific class for better formatting
            document.body.classList.add('printing');
            window.print();
            document.body.classList.remove('printing');
        }
        
        function exportToPDF() {
            var btn = event.target;
            btn.classList.add('loading');
            btn.disabled = true;
            
            // Use html2pdf library for PDF generation
            if (typeof html2pdf === 'undefined') {
                // Load html2pdf library if not already loaded
                var script = document.createElement('script');
                script.src = 'https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js';
                script.onload = function() {
                    generatePDF();
                    btn.classList.remove('loading');
                    btn.disabled = false;
                };
                document.head.appendChild(script);
            } else {
                generatePDF();
                btn.classList.remove('loading');
                btn.disabled = false;
            }
        }
        
        function generatePDF() {
            var btn = event.target;
            btn.classList.add('loading');
            btn.disabled = true;
            
            // Get currency settings
            var currencyCode = '<?php echo $this->session->userdata("currency_code") ?: "USD"; ?>';
            var currencyPlacement = '<?php echo $this->session->userdata("currency_placement") ?: "Left"; ?>';
            
            // Format currency function
            function formatCurrency(amount) {
                var num = parseFloat(amount);
                
                // Check if it's a whole number
                if (num % 1 === 0) {
                    var formatted = num.toLocaleString('en-US', {
                        minimumFractionDigits: 0,
                        maximumFractionDigits: 0
                    });
                } else {
                    var formatted = num.toLocaleString('en-US', {
                        minimumFractionDigits: 2,
                        maximumFractionDigits: 2
                    });
                }
                
                if (currencyPlacement === 'Left') {
                    return currencyCode + ' ' + formatted;
                } else {
                    return formatted + ' ' + currencyCode;
                }
            }
            
            // Get actual report data
            var reportData = getReportData();
            
            var newWindow = window.open('', '_blank');
            newWindow.document.write(`
                <!DOCTYPE html>
                <html>
                <head>
                    <title>Profit & Loss Report - PDF</title>
                    <style>
                        * { margin: 0; padding: 0; box-sizing: border-box; }
                        body { 
                            font-family: 'Arial', sans-serif; 
                            font-size: 12px; 
                            line-height: 1.4;
                            color: #333;
                            background: white;
                        }
                        .receipt-container {
                            width: 210mm;
                            min-height: 297mm;
                            margin: 0 auto;
                            padding: 15mm;
                            background: white;
                        }
                        .receipt-header {
                            text-align: center;
                            margin-bottom: 20px;
                            padding-bottom: 15px;
                            border-bottom: 2px solid #000;
                        }
                        .company-name {
                            font-size: 24px;
                            font-weight: bold;
                            margin-bottom: 8px;
                            text-transform: uppercase;
                            letter-spacing: 1px;
                            color: #2c3e50;
                        }
                        .company-details {
                            font-size: 11px;
                            color: #666;
                            line-height: 1.3;
                        }
                        .report-title {
                            font-size: 20px;
                            font-weight: bold;
                            margin: 15px 0 8px 0;
                            text-transform: uppercase;
                            letter-spacing: 1px;
                            color: #e74c3c;
                            text-align: center;
                        }
                        .report-period {
                            font-size: 12px;
                            color: #666;
                            margin-bottom: 20px;
                            font-weight: bold;
                            text-align: center;
                        }
                        .receipt-table {
                            width: 100%;
                            border-collapse: collapse;
                            margin: 10px 0;
                            font-size: 11px;
                        }
                        .receipt-table th {
                            background: #2c3e50;
                            color: white;
                            padding: 8px 10px;
                            text-align: left;
                            font-weight: bold;
                            font-size: 10px;
                            text-transform: uppercase;
                            letter-spacing: 0.5px;
                        }
                        .receipt-table td {
                            padding: 6px 10px;
                            border-bottom: 1px solid #ddd;
                            vertical-align: top;
                        }
                        .receipt-table .amount {
                            text-align: right;
                            font-weight: bold;
                        }
                        .receipt-table .section-header {
                            background: #34495e !important;
                            color: white !important;
                            font-weight: bold;
                            font-size: 11px;
                            padding: 8px 10px;
                        }
                        .receipt-table .subtotal {
                            background: #f8f9fa;
                            font-weight: bold;
                            border-top: 2px solid #ddd;
                        }
                        .receipt-table .total {
                            background: #2c3e50 !important;
                            color: white !important;
                            font-weight: bold;
                            font-size: 12px;
                        }
                        .receipt-table .positive {
                            color: #27ae60;
                        }
                        .receipt-table .negative {
                            color: #e74c3c;
                        }
                        .separator {
                            border-top: 1px solid #000;
                            margin: 15px 0;
                        }
                        .footer {
                            margin-top: 30px;
                            text-align: center;
                            font-size: 10px;
                            color: #666;
                            border-top: 1px solid #ddd;
                            padding-top: 10px;
                        }
                        @media print {
                            body { margin: 0; padding: 0; }
                            .receipt-container { margin: 0; padding: 15mm; }
                            @page { size: A4; margin: 0; }
                        }
                    </style>
                </head>
                <body>
                    <div class="receipt-container">
                        
                        ${generatePrintOptimizedContent(reportData, formatCurrency)}
                        
                        <div class="footer">
                            <div>Generated on: ${new Date().toLocaleString()}</div>
                            <div>This is a computer generated report</div>
                        </div>
                    </div>
                </body>
                </html>
            `);
            newWindow.document.close();
            
            // Show preview first, then download
            setTimeout(function() {
                // Show the preview window first
                newWindow.focus();
                
                // Wait a moment for user to see preview, then download
                setTimeout(function() {
                    if (typeof html2pdf !== 'undefined') {
                        var element = newWindow.document.body;
                        var opt = {
                            margin: 0.5,
                            filename: 'Profit_Loss_Report_' + new Date().toISOString().split('T')[0] + '.pdf',
                            image: { type: 'jpeg', quality: 0.98 },
                            html2canvas: { scale: 2, useCORS: true },
                            jsPDF: { unit: 'in', format: 'a4', orientation: 'portrait' }
                        };
                        html2pdf().set(opt).from(element).save();
                    } else {
                        newWindow.print();
                    }
                }, 2000); // 2 second delay to show preview
                
                btn.classList.remove('loading');
                btn.disabled = false;
            }, 1000);
        }
        
        function exportToImage() {
            var btn = event.target;
            btn.classList.add('loading');
            btn.disabled = true;
            
            // Get currency settings
            var currencyCode = '<?php echo $this->session->userdata("currency_code") ?: "USD"; ?>';
            var currencyPlacement = '<?php echo $this->session->userdata("currency_placement") ?: "Left"; ?>';
            
            // Format currency function
            function formatCurrency(amount) {
                var num = parseFloat(amount);
                
                // Check if it's a whole number
                if (num % 1 === 0) {
                    var formatted = num.toLocaleString('en-US', {
                        minimumFractionDigits: 0,
                        maximumFractionDigits: 0
                    });
                } else {
                    var formatted = num.toLocaleString('en-US', {
                        minimumFractionDigits: 2,
                        maximumFractionDigits: 2
                    });
                }
                
                if (currencyPlacement === 'Left') {
                    return currencyCode + ' ' + formatted;
                } else {
                    return formatted + ' ' + currencyCode;
                }
            }
            
            // Get actual report data
            var reportData = getReportData();
            
            // Use html2canvas for image generation
            if (typeof html2canvas === 'undefined') {
                // Load html2canvas library if not already loaded
                var script = document.createElement('script');
                script.src = 'https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js';
                script.onload = function() {
                    generateImage();
                    btn.classList.remove('loading');
                    btn.disabled = false;
                };
                document.head.appendChild(script);
            } else {
                generateImage();
                btn.classList.remove('loading');
                btn.disabled = false;
            }
        }
        
        function generateImage() {
            // Get currency settings
            var currencyCode = '<?php echo $this->session->userdata("currency_code") ?: "USD"; ?>';
            var currencyPlacement = '<?php echo $this->session->userdata("currency_placement") ?: "Left"; ?>';
            
            // Format currency function
            function formatCurrency(amount) {
                var num = parseFloat(amount);
                
                // Check if it's a whole number
                if (num % 1 === 0) {
                    var formatted = num.toLocaleString('en-US', {
                        minimumFractionDigits: 0,
                        maximumFractionDigits: 0
                    });
                } else {
                    var formatted = num.toLocaleString('en-US', {
                        minimumFractionDigits: 2,
                        maximumFractionDigits: 2
                    });
                }
                
                if (currencyPlacement === 'Left') {
                    return currencyCode + ' ' + formatted;
                } else {
                    return formatted + ' ' + currencyCode;
                }
            }
            
            // Get actual report data
            var reportData = getReportData();
            
            var newWindow = window.open('', '_blank');
            newWindow.document.write(`
                <!DOCTYPE html>
                <html>
                <head>
                    <title>Profit & Loss Report - Image</title>
                    <style>
                        * { margin: 0; padding: 0; box-sizing: border-box; }
                        body { 
                            font-family: 'Arial', sans-serif; 
                            font-size: 12px; 
                            line-height: 1.4;
                            color: #333;
                            background: white;
                        }
                        .receipt-container {
                            width: 210mm;
                            min-height: 297mm;
                            margin: 0 auto;
                            padding: 15mm;
                            background: white;
                        }
                        .receipt-header {
                            text-align: center;
                            margin-bottom: 20px;
                            padding-bottom: 15px;
                            border-bottom: 2px solid #000;
                        }
                        .company-name {
                            font-size: 24px;
                            font-weight: bold;
                            margin-bottom: 8px;
                            text-transform: uppercase;
                            letter-spacing: 1px;
                            color: #2c3e50;
                        }
                        .company-details {
                            font-size: 11px;
                            color: #666;
                            line-height: 1.3;
                        }
                        .report-title {
                            font-size: 20px;
                            font-weight: bold;
                            margin: 15px 0 8px 0;
                            text-transform: uppercase;
                            letter-spacing: 1px;
                            color: #e74c3c;
                            text-align: center;
                        }
                        .report-period {
                            font-size: 12px;
                            color: #666;
                            margin-bottom: 20px;
                            font-weight: bold;
                            text-align: center;
                        }
                        .receipt-table {
                            width: 100%;
                            border-collapse: collapse;
                            margin: 10px 0;
                            font-size: 11px;
                        }
                        .receipt-table th {
                            background: #2c3e50;
                            color: white;
                            padding: 8px 10px;
                            text-align: left;
                            font-weight: bold;
                            font-size: 10px;
                            text-transform: uppercase;
                            letter-spacing: 0.5px;
                        }
                        .receipt-table td {
                            padding: 6px 10px;
                            border-bottom: 1px solid #ddd;
                            vertical-align: top;
                        }
                        .receipt-table .amount {
                            text-align: right;
                            font-weight: bold;
                        }
                        .receipt-table .section-header {
                            background: #34495e !important;
                            color: white !important;
                            font-weight: bold;
                            font-size: 11px;
                            padding: 8px 10px;
                        }
                        .receipt-table .subtotal {
                            background: #f8f9fa;
                            font-weight: bold;
                            border-top: 2px solid #ddd;
                        }
                        .receipt-table .total {
                            background: #2c3e50 !important;
                            color: white !important;
                            font-weight: bold;
                            font-size: 12px;
                        }
                        .receipt-table .positive {
                            color: #27ae60;
                        }
                        .receipt-table .negative {
                            color: #e74c3c;
                        }
                        .separator {
                            border-top: 1px solid #000;
                            margin: 15px 0;
                        }
                        .footer {
                            margin-top: 30px;
                            text-align: center;
                            font-size: 10px;
                            color: #666;
                            border-top: 1px solid #ddd;
                            padding-top: 10px;
                        }
                    </style>
                </head>
                <body>
                    <div class="receipt-container">
                        
                        ${generatePrintOptimizedContent(reportData, formatCurrency)}
                        
                        <div class="footer">
                            <div>Generated on: ${new Date().toLocaleString()}</div>
                            <div>This is a computer generated report</div>
                        </div>
                    </div>
                </body>
                </html>
            `);
            newWindow.document.close();
            
            // Generate image from the new window
            setTimeout(function() {
                if (typeof html2canvas !== 'undefined') {
                    var element = newWindow.document.body;
                    html2canvas(element, {
                        scale: 2,
                        useCORS: true,
                        backgroundColor: '#ffffff'
                    }).then(function(canvas) {
                        var link = document.createElement('a');
                        link.download = 'Profit_Loss_Report_' + new Date().toISOString().split('T')[0] + '.png';
                        link.href = canvas.toDataURL();
                        link.click();
                        newWindow.close();
                    });
                } else {
                    newWindow.print();
                }
            }, 1000);
        }
        
        function exportToA4() {
            var btn = event.target;
            btn.classList.add('loading');
            btn.disabled = true;
            
            // Get currency settings
            var currencyCode = '<?php echo $this->session->userdata("currency_code") ?: "USD"; ?>';
            var currencyPlacement = '<?php echo $this->session->userdata("currency_placement") ?: "Left"; ?>';
            
            // Format currency function
            function formatCurrency(amount) {
                var num = parseFloat(amount);
                
                // Check if it's a whole number
                if (num % 1 === 0) {
                    var formatted = num.toLocaleString('en-US', {
                        minimumFractionDigits: 0,
                        maximumFractionDigits: 0
                    });
                } else {
                    var formatted = num.toLocaleString('en-US', {
                        minimumFractionDigits: 2,
                        maximumFractionDigits: 2
                    });
                }
                
                if (currencyPlacement === 'Left') {
                    return currencyCode + ' ' + formatted;
                } else {
                    return formatted + ' ' + currencyCode;
                }
            }
            
            // Get actual report data
            var reportData = getReportData();
            
            var newWindow = window.open('', '_blank');
            newWindow.document.write(`
                <!DOCTYPE html>
                <html>
                <head>
                    <title>Profit & Loss Report - A4 Format</title>
                    <style>
                        * { margin: 0; padding: 0; box-sizing: border-box; }
                        body { 
                            font-family: 'Arial', sans-serif; 
                            font-size: 12px; 
                            line-height: 1.4;
                            color: #333;
                            background: white;
                        }
                        .receipt-container {
                            width: 210mm;
                            min-height: 297mm;
                            margin: 0 auto;
                            padding: 15mm;
                            background: white;
                        }
                        .receipt-header {
                            text-align: center;
                            margin-bottom: 20px;
                            padding-bottom: 15px;
                            border-bottom: 2px solid #000;
                        }
                        .company-name {
                            font-size: 24px;
                            font-weight: bold;
                            margin-bottom: 8px;
                            text-transform: uppercase;
                            letter-spacing: 1px;
                            color: #2c3e50;
                        }
                        .company-details {
                            font-size: 11px;
                            color: #666;
                            line-height: 1.3;
                        }
                        .report-title {
                            font-size: 20px;
                            font-weight: bold;
                            margin: 15px 0 8px 0;
                            text-transform: uppercase;
                            letter-spacing: 1px;
                            color: #e74c3c;
                            text-align: center;
                        }
                        .report-period {
                            font-size: 12px;
                            color: #666;
                            margin-bottom: 20px;
                            font-weight: bold;
                            text-align: center;
                        }
                        .receipt-table {
                            width: 100%;
                            border-collapse: collapse;
                            margin: 10px 0;
                            font-size: 11px;
                        }
                        .receipt-table th {
                            background: #2c3e50;
                            color: white;
                            padding: 8px 10px;
                            text-align: left;
                            font-weight: bold;
                            font-size: 10px;
                            text-transform: uppercase;
                            letter-spacing: 0.5px;
                        }
                        .receipt-table td {
                            padding: 6px 10px;
                            border-bottom: 1px solid #ddd;
                            vertical-align: top;
                        }
                        .receipt-table .amount {
                            text-align: right;
                            font-weight: bold;
                        }
                        .receipt-table .section-header {
                            background: #34495e !important;
                            color: white !important;
                            font-weight: bold;
                            font-size: 11px;
                            padding: 8px 10px;
                        }
                        .receipt-table .subtotal {
                            background: #f8f9fa;
                            font-weight: bold;
                            border-top: 2px solid #ddd;
                        }
                        .receipt-table .total {
                            background: #2c3e50 !important;
                            color: white !important;
                            font-weight: bold;
                            font-size: 12px;
                        }
                        .receipt-table .positive {
                            color: #27ae60;
                        }
                        .receipt-table .negative {
                            color: #e74c3c;
                        }
                        .separator {
                            border-top: 1px solid #000;
                            margin: 15px 0;
                        }
                        .footer {
                            margin-top: 30px;
                            text-align: center;
                            font-size: 10px;
                            color: #666;
                            border-top: 1px solid #ddd;
                            padding-top: 10px;
                        }
                        @media print {
                            body { margin: 0; padding: 0; }
                            .receipt-container { margin: 0; padding: 15mm; }
                            @page { size: A4; margin: 0; }
                        }
                    </style>
                </head>
                <body>
                    <div class="receipt-container">
                        
                        ${generatePrintOptimizedContent(reportData, formatCurrency)}
                        
                        <div class="footer">
                            <div>Generated on: ${new Date().toLocaleString()}</div>
                            <div>This is a computer generated report</div>
                        </div>
                    </div>
                </body>
                </html>
            `);
            newWindow.document.close();
            
            setTimeout(function() {
                newWindow.print();
                btn.classList.remove('loading');
                btn.disabled = false;
            }, 500);
        }
        
        function exportTo80MM() {
            var btn = event.target;
            btn.classList.add('loading');
            btn.disabled = true;
            
            // Get currency settings
            var currencyCode = '<?php echo $this->session->userdata("currency_code") ?: "USD"; ?>';
            var currencyPlacement = '<?php echo $this->session->userdata("currency_placement") ?: "Left"; ?>';
            
            // Format currency function
            function formatCurrency(amount) {
                var num = parseFloat(amount);
                
                // Check if it's a whole number
                if (num % 1 === 0) {
                    var formatted = num.toLocaleString('en-US', {
                        minimumFractionDigits: 0,
                        maximumFractionDigits: 0
                    });
                } else {
                    var formatted = num.toLocaleString('en-US', {
                        minimumFractionDigits: 2,
                        maximumFractionDigits: 2
                    });
                }
                
                if (currencyPlacement === 'Left') {
                    return currencyCode + ' ' + formatted;
                } else {
                    return formatted + ' ' + currencyCode;
                }
            }
            
            // Get actual report data
            var reportData = getReportData();
            
            var newWindow = window.open('', '_blank');
            newWindow.document.write(`
                <!DOCTYPE html>
                <html>
                <head>
                    <title>Profit & Loss Report - 80MM Receipt</title>
                    <style>
                        * { margin: 0; padding: 0; box-sizing: border-box; }
                        body { 
                            font-family: 'Courier New', monospace; 
                            font-size: 9px; 
                            line-height: 1.2;
                            color: #000;
                            background: white;
                            width: 80mm;
                        }
                        .receipt-container {
                            width: 80mm;
                            margin: 0 auto;
                            padding: 5mm;
                            background: white;
                        }
                        .receipt-header {
                            text-align: center;
                            margin-bottom: 8px;
                            padding-bottom: 8px;
                            border-bottom: 1px solid #000;
                        }
                        .company-name {
                            font-size: 12px;
                            font-weight: bold;
                            margin-bottom: 4px;
                            text-transform: uppercase;
                        }
                        .company-details {
                            font-size: 8px;
                            color: #000;
                            line-height: 1.1;
                        }
                        .report-title {
                            font-size: 10px;
                            font-weight: bold;
                            margin: 8px 0 4px 0;
                            text-align: center;
                            text-transform: uppercase;
                        }
                        .report-period {
                            font-size: 8px;
                            color: #000;
                            margin-bottom: 8px;
                            text-align: center;
                            font-weight: bold;
                        }
                        .receipt-table {
                            width: 100%;
                            border-collapse: collapse;
                            margin: 4px 0;
                            font-size: 8px;
                        }
                        .receipt-table th {
                            background: #000;
                            color: white;
                            padding: 3px 4px;
                            text-align: left;
                            font-weight: bold;
                            font-size: 7px;
                            text-transform: uppercase;
                        }
                        .receipt-table td {
                            padding: 2px 4px;
                            border-bottom: 1px solid #000;
                            vertical-align: top;
                        }
                        .receipt-table .amount {
                            text-align: right;
                            font-weight: bold;
                        }
                        .receipt-table .section-header {
                            background: #333 !important;
                            color: white !important;
                            font-weight: bold;
                            font-size: 8px;
                            padding: 3px 4px;
                        }
                        .receipt-table .subtotal {
                            background: #f0f0f0;
                            font-weight: bold;
                            border-top: 1px solid #000;
                        }
                        .receipt-table .total {
                            background: #000 !important;
                            color: white !important;
                            font-weight: bold;
                            font-size: 9px;
                        }
                        .receipt-table .positive {
                            color: #000;
                        }
                        .receipt-table .negative {
                            color: #000;
                        }
                        .separator {
                            border-top: 1px solid #000;
                            margin: 6px 0;
                        }
                        .footer {
                            margin-top: 15px;
                            text-align: center;
                            font-size: 7px;
                            color: #000;
                            border-top: 1px solid #000;
                            padding-top: 4px;
                        }
                        @media print {
                            body { margin: 0; padding: 0; }
                            .receipt-container { margin: 0; padding: 5mm; }
                            @page { size: 80mm auto; margin: 0; }
                        }
                    </style>
                </head>
                <body>
                    <div class="receipt-container">
                        
                        
                        ${generatePrintOptimizedContent(reportData, formatCurrency)}
                        
                        <div class="footer">
                            <div>Generated: ${new Date().toLocaleString()}</div>
                        </div>
                    </div>
                </body>
                </html>
            `);
            newWindow.document.close();
            
            setTimeout(function() {
                newWindow.print();
                btn.classList.remove('loading');
                btn.disabled = false;
            }, 500);
        }
        
        // Store the current report data globally
        var currentReportData = {};
        
        // Helper function to get report data from the current report
        function getReportData() {
            return currentReportData;
        }
        
        // Function to store report data when report is generated
        function storeReportData(data) {
            currentReportData = data;
        }
        
        function generateProfessionalReceiptContent(data, formatCurrency) {
            // Calculate totals
            var grossProfit = parseFloat(data.gross_profit || 0);
            var netProfit = parseFloat(data.net_profit || 0);
            var totalRevenue = parseFloat(data.sal_total || 0);
            var totalExpenses = parseFloat(data.pur_total || 0) + parseFloat(data.expense_total || 0);
            
            return `
                <table class="receipt-table">
                    <tr class="section-header">
                        <th colspan="2">OPENING STOCK</th>
                    </tr>
                    <tr>
                        <td>Opening Stock Value</td>
                        <td class="amount">${formatCurrency(data.opening_stock_price || 0)}</td>
                    </tr>
                </table>
                
                <table class="receipt-table">
                    <tr class="section-header">
                        <th colspan="2">PURCHASES</th>
                    </tr>
                    <tr>
                        <td>Total Purchase</td>
                        <td class="amount">${formatCurrency(data.pur_total || 0)}</td>
                    </tr>
                    <tr>
                        <td>Total Purchase Tax</td>
                        <td class="amount">${formatCurrency(data.purchase_tax_amt || 0)}</td>
                    </tr>
                    <tr>
                        <td>Total Other Charges</td>
                        <td class="amount">${formatCurrency(data.pur_other_charges_amt || 0)}</td>
                    </tr>
                    <tr>
                        <td>Total Discount</td>
                        <td class="amount">${formatCurrency(data.purchase_discount_amt || 0)}</td>
                    </tr>
                    <tr class="subtotal">
                        <td><strong>Total Purchases</strong></td>
                        <td class="amount"><strong>${formatCurrency(data.pur_total || 0)}</strong></td>
                    </tr>
                </table>
                
                <table class="receipt-table">
                    <tr class="section-header">
                        <th colspan="2">SALES</th>
                    </tr>
                    <tr>
                        <td>Sales (Before Tax)</td>
                        <td class="amount">${formatCurrency(data.sal_total || 0)}</td>
                    </tr>
                    <tr>
                        <td>Total Sales Tax</td>
                        <td class="amount">${formatCurrency(data.sales_tax_amt || 0)}</td>
                    </tr>
                    <tr>
                        <td>Total Other Charges</td>
                        <td class="amount">${formatCurrency(data.sal_other_charges_amt || 0)}</td>
                    </tr>
                    <tr>
                        <td>Total Discount</td>
                        <td class="amount">${formatCurrency(data.sales_discount_amt || 0)}</td>
                    </tr>
                    <tr>
                        <td>Coupon Discount</td>
                        <td class="amount">${formatCurrency(data.coupon_discount_amt || 0)}</td>
                    </tr>
                    <tr class="subtotal">
                        <td><strong>Total Sales</strong></td>
                        <td class="amount"><strong>${formatCurrency(totalRevenue)}</strong></td>
                    </tr>
                </table>
                
                <table class="receipt-table">
                    <tr class="section-header">
                        <th colspan="2">EXPENSES</th>
                    </tr>
                    <tr>
                        <td>Total Expense</td>
                        <td class="amount">${formatCurrency(data.expense_total || 0)}</td>
                    </tr>
                </table>
                
                <table class="receipt-table">
                    <tr class="section-header">
                        <th colspan="2">SUMMARY</th>
                    </tr>
                    <tr>
                        <td><strong>Gross Profit</strong></td>
                        <td class="amount ${grossProfit >= 0 ? 'positive' : 'negative'}"><strong>${formatCurrency(grossProfit)}</strong></td>
                    </tr>
                    <tr>
                        <td><strong>Total Expenses</strong></td>
                        <td class="amount"><strong>${formatCurrency(data.expense_total || 0)}</strong></td>
                    </tr>
                    <tr class="total">
                        <td><strong>Net Profit/Loss</strong></td>
                        <td class="amount ${netProfit >= 0 ? 'positive' : 'negative'}"><strong>${formatCurrency(netProfit)}</strong></td>
                    </tr>
                </table>
            `;
        }
        
        function formatCompressedNumber(amount) {
            var num = parseFloat(amount);
            if (num === 0) return '0';
            
            var absNum = Math.abs(num);
            var sign = num < 0 ? '-' : '';
            
            if (absNum >= 1e12) {
                return sign + (absNum / 1e12).toFixed(1) + 'T';
            } else if (absNum >= 1e9) {
                return sign + (absNum / 1e9).toFixed(1) + 'B';
            } else if (absNum >= 1e6) {
                return sign + (absNum / 1e6).toFixed(1) + 'M';
            } else if (absNum >= 1e3) {
                return sign + (absNum / 1e3).toFixed(1) + 'K';
            } else {
                return sign + absNum.toFixed(0);
            }
        }

        function generatePrintOptimizedContent(data, formatCurrency) {
            // Calculate totals
            var grossProfit = parseFloat(data.gross_profit || 0);
            var netProfit = parseFloat(data.net_profit || 0);
            
            // Helper function to check if value is significant (not zero or very small)
            function isSignificant(value) {
                return Math.abs(parseFloat(value || 0)) > 0.01;
            }
            
            // Helper function to create table rows with consistent styling
            function createTableRow(label, value, showIfSignificant = true) {
                if (showIfSignificant && !isSignificant(value)) return '';
                return `
                    <tr>
                        <td style="padding: 12px 15px; border: 1px solid #ddd; background: #f8f9fa; font-weight: 500; width: 70%;">${label}</td>
                        <td class="amount" style="padding: 12px 15px; border: 1px solid #ddd; text-align: right; font-weight: bold; background: #fff; width: 30%;">${formatCurrency(value || 0)}</td>
                    </tr>
                `;
            }
            
            return `
                <div class="company-header" style="text-align: center; margin-bottom: 15px; padding-bottom: 10px; border-bottom: 1px solid #000;">
                    <div class="company-name" style="font-size: 18px; font-weight: bold; color: #2c3e50; margin: 5px 0;">
                        ${$('.company-name').first().text() || '<?php echo get_store_name() ? get_store_name() : "Company Name"; ?>'}
                    </div>
                    <div class="company-details" style="font-size: 12px; color: #7f8c8d; line-height: 1.2;">
                        ${$('.company-details').first().html() || '<?php $store = get_store_details(); echo isset($store->address) ? $store->address : "Company Address"; ?><br><?php echo isset($store->mobile) ? "Phone: " . $store->mobile : "Phone: Company Phone"; ?><br><?php echo isset($store->email) ? "Email: " . $store->email : "Email: Company Email"; ?>'}
                    </div>
                </div>
                
                <div class="report-title" style="text-align: center; font-size: 16px; font-weight: bold; color: #e74c3c; margin: 10px 0; text-transform: uppercase; letter-spacing: 1px;">
                    Profit & Loss Statement
                </div>
                
                <div class="report-period" style="text-align: center; font-size: 12px; color: #666; margin-bottom: 15px;">
                    ${data.from_date} to ${data.to_date}
                </div>
                
                <table style="width: 100%; border-collapse: collapse; margin: 0 auto; max-width: 800px; background: white; font-size: 12px;">
                    <thead>
                        <tr style="background: #2c3e50; color: white;">
                            <th style="padding: 8px 12px; text-align: left; font-weight: bold; font-size: 14px; width: 60%; border-right: 2px solid #34495e;">Description</th>
                            <th style="padding: 8px 12px; text-align: right; font-weight: bold; font-size: 14px; width: 40%;">Amount</th>
                        </tr>
                    </thead>
                    <tbody>
                        ${isSignificant(data.opening_stock_price) ? `
                        <tr style="border-bottom: 1px solid #eee;">
                            <td style="padding: 6px 12px; font-weight: 500; border-right: 2px solid #ddd;">Opening Stock Value</td>
                            <td style="padding: 6px 12px; text-align: right; font-weight: bold;">${formatCurrency(data.opening_stock_price || 0)}</td>
                        </tr>
                        ` : ''}
                        
                        ${(isSignificant(data.pur_total) || isSignificant(data.purchase_tax_amt) || isSignificant(data.pur_other_charges_amt) || isSignificant(data.purchase_discount_amt) || isSignificant(data.pur_paid_amount)) ? `
                        <tr style="background: #f8f9fa; border-top: 2px solid #2c3e50;">
                            <td colspan="2" style="padding: 8px 12px; font-weight: bold; font-size: 14px; color: #2c3e50; text-transform: uppercase; letter-spacing: 1px;">PURCHASES</td>
                        </tr>
                        ` : ''}
                
                        ${isSignificant(data.pur_total) ? `
                        <tr style="border-bottom: 1px solid #eee;">
                            <td style="padding: 6px 12px; font-weight: 500; border-right: 2px solid #ddd;">Total Purchase</td>
                            <td style="padding: 6px 12px; text-align: right; font-weight: bold;">${formatCurrency(data.pur_total || 0)}</td>
                        </tr>
                        ` : ''}
                        ${isSignificant(data.purchase_tax_amt) ? `
                        <tr style="border-bottom: 1px solid #eee;">
                            <td style="padding: 6px 12px; font-weight: 500; border-right: 2px solid #ddd;">Total Purchase Tax</td>
                            <td style="padding: 6px 12px; text-align: right; font-weight: bold;">${formatCurrency(data.purchase_tax_amt || 0)}</td>
                        </tr>
                        ` : ''}
                        ${isSignificant(data.pur_other_charges_amt) ? `
                        <tr style="border-bottom: 1px solid #eee;">
                            <td style="padding: 6px 12px; font-weight: 500; border-right: 2px solid #ddd;">Total Other Charges of Purchase</td>
                            <td style="padding: 6px 12px; text-align: right; font-weight: bold;">${formatCurrency(data.pur_other_charges_amt || 0)}</td>
                        </tr>
                        ` : ''}
                        ${isSignificant(data.purchase_discount_amt) ? `
                        <tr style="border-bottom: 1px solid #eee;">
                            <td style="padding: 6px 12px; font-weight: 500; border-right: 2px solid #ddd;">Total Discount on Purchase</td>
                            <td style="padding: 6px 12px; text-align: right; font-weight: bold;">${formatCurrency(data.purchase_discount_amt || 0)}</td>
                        </tr>
                        ` : ''}
                        ${isSignificant(data.pur_paid_amount) ? `
                        <tr style="border-bottom: 1px solid #eee;">
                            <td style="padding: 6px 12px; font-weight: 500; border-right: 2px solid #ddd;">Paid Amount</td>
                            <td style="padding: 6px 12px; text-align: right; font-weight: bold;">${formatCurrency(data.pur_paid_amount || 0)}</td>
                        </tr>
                        ` : ''}
                        ${isSignificant((data.pur_total || 0) - (data.pur_paid_amount || 0)) ? `
                        <tr style="border-bottom: 1px solid #eee;">
                            <td style="padding: 6px 12px; font-weight: 500; border-right: 2px solid #ddd;">Purchase Due</td>
                            <td style="padding: 6px 12px; text-align: right; font-weight: bold;">${formatCurrency((data.pur_total || 0) - (data.pur_paid_amount || 0))}</td>
                        </tr>
                        ` : ''}
                        
                        ${(isSignificant(data.purchase_return_total) || isSignificant(data.purchase_return_tax_amt) || isSignificant(data.purchase_return_other_charges_amt) || isSignificant(data.purchase_return_discount_amt) || isSignificant(data.purchase_return_paid_amount)) ? `
                        <tr style="background: #f8f9fa; border-top: 2px solid #2c3e50;">
                            <td colspan="2" style="padding: 8px 12px; font-weight: bold; font-size: 16px; color: #2c3e50; text-transform: uppercase; letter-spacing: 1px;">PURCHASE RETURNS</td>
                        </tr>
                        ` : ''}
                
                        ${isSignificant(data.purchase_return_total) ? `
                        <tr style="border-bottom: 1px solid #eee;">
                            <td style="padding: 6px 12px; font-weight: 500; border-right: 2px solid #ddd;">Total Purchase Return</td>
                            <td style="padding: 6px 12px; text-align: right; font-weight: bold;">${formatCurrency(data.purchase_return_total || 0)}</td>
                        </tr>
                        ` : ''}
                        ${isSignificant(data.purchase_return_tax_amt) ? `
                        <tr style="border-bottom: 1px solid #eee;">
                            <td style="padding: 6px 12px; font-weight: 500; border-right: 2px solid #ddd;">Total Purchase Return Tax</td>
                            <td style="padding: 6px 12px; text-align: right; font-weight: bold;">${formatCurrency(data.purchase_return_tax_amt || 0)}</td>
                        </tr>
                        ` : ''}
                        ${isSignificant(data.purchase_return_other_charges_amt) ? `
                        <tr style="border-bottom: 1px solid #eee;">
                            <td style="padding: 6px 12px; font-weight: 500; border-right: 2px solid #ddd;">Total Other Charges of Purchase Return</td>
                            <td style="padding: 6px 12px; text-align: right; font-weight: bold;">${formatCurrency(data.purchase_return_other_charges_amt || 0)}</td>
                        </tr>
                        ` : ''}
                        ${isSignificant(data.purchase_return_discount_amt) ? `
                        <tr style="border-bottom: 1px solid #eee;">
                            <td style="padding: 6px 12px; font-weight: 500; border-right: 2px solid #ddd;">Total Discount on Purchase Return</td>
                            <td style="padding: 6px 12px; text-align: right; font-weight: bold;">${formatCurrency(data.purchase_return_discount_amt || 0)}</td>
                        </tr>
                        ` : ''}
                        ${isSignificant(data.purchase_return_paid_amount) ? `
                        <tr style="border-bottom: 1px solid #eee;">
                            <td style="padding: 6px 12px; font-weight: 500; border-right: 2px solid #ddd;">Paid Amount</td>
                            <td style="padding: 6px 12px; text-align: right; font-weight: bold;">${formatCurrency(data.purchase_return_paid_amount || 0)}</td>
                        </tr>
                        ` : ''}
                        ${isSignificant((data.purchase_return_total || 0) - (data.purchase_return_paid_amount || 0)) ? `
                        <tr style="border-bottom: 1px solid #eee;">
                            <td style="padding: 6px 12px; font-weight: 500; border-right: 2px solid #ddd;">Purchase Return Due</td>
                            <td style="padding: 6px 12px; text-align: right; font-weight: bold;">${formatCurrency((data.purchase_return_total || 0) - (data.purchase_return_paid_amount || 0))}</td>
                        </tr>
                        ` : ''}
                        
                        ${(isSignificant(data.sal_total) || isSignificant(data.sales_tax_amt) || isSignificant(data.sal_other_charges_amt) || isSignificant(data.sales_discount_amt) || isSignificant(data.sal_coupon_amt) || isSignificant(data.sal_paid_amount)) ? `
                        <tr style="background: #e8f5e8; border-top: 2px solid #27ae60;">
                            <td colspan="2" style="padding: 8px 12px; font-weight: bold; font-size: 16px; color: #27ae60; text-transform: uppercase; letter-spacing: 1px;">SALES & REVENUE</td>
                        </tr>
                        ` : ''}
                        
                        ${isSignificant(data.sal_total) ? `
                        <tr style="border-bottom: 1px solid #eee;">
                            <td style="padding: 6px 12px; font-weight: 500; border-right: 2px solid #ddd;">Sales (Before Tax)</td>
                            <td style="padding: 6px 12px; text-align: right; font-weight: bold;">${formatCurrency(data.sal_total || 0)}</td>
                        </tr>
                        ` : ''}
                        ${isSignificant(data.sales_tax_amt) ? `
                        <tr style="border-bottom: 1px solid #eee;">
                            <td style="padding: 6px 12px; font-weight: 500; border-right: 2px solid #ddd;">Total Sales Tax</td>
                            <td style="padding: 6px 12px; text-align: right; font-weight: bold;">${formatCurrency(data.sales_tax_amt || 0)}</td>
                        </tr>
                        ` : ''}
                        ${isSignificant(data.sal_other_charges_amt) ? `
                        <tr style="border-bottom: 1px solid #eee;">
                            <td style="padding: 6px 12px; font-weight: 500; border-right: 2px solid #ddd;">Total Other Charges of Sales</td>
                            <td style="padding: 6px 12px; text-align: right; font-weight: bold;">${formatCurrency(data.sal_other_charges_amt || 0)}</td>
                        </tr>
                        ` : ''}
                        ${isSignificant(data.sales_discount_amt) ? `
                        <tr style="border-bottom: 1px solid #eee;">
                            <td style="padding: 6px 12px; font-weight: 500; border-right: 2px solid #ddd;">Total Discount on Sales</td>
                            <td style="padding: 6px 12px; text-align: right; font-weight: bold;">${formatCurrency(data.sales_discount_amt || 0)}</td>
                        </tr>
                        ` : ''}
                        ${isSignificant(data.sal_coupon_amt) ? `
                        <tr style="border-bottom: 1px solid #eee;">
                            <td style="padding: 6px 12px; font-weight: 500; border-right: 2px solid #ddd;">Coupon Discount</td>
                            <td style="padding: 6px 12px; text-align: right; font-weight: bold;">${formatCurrency(data.sal_coupon_amt || 0)}</td>
                        </tr>
                        ` : ''}
                        ${isSignificant(data.sal_paid_amount) ? `
                        <tr style="border-bottom: 1px solid #eee;">
                            <td style="padding: 6px 12px; font-weight: 500; border-right: 2px solid #ddd;">Paid Amount</td>
                            <td style="padding: 6px 12px; text-align: right; font-weight: bold;">${formatCurrency(data.sal_paid_amount || 0)}</td>
                        </tr>
                        ` : ''}
                        ${isSignificant((data.sal_total || 0) - (data.sal_paid_amount || 0)) ? `
                        <tr style="border-bottom: 1px solid #eee;">
                            <td style="padding: 6px 12px; font-weight: 500; border-right: 2px solid #ddd;">Sales Due</td>
                            <td style="padding: 6px 12px; text-align: right; font-weight: bold;">${formatCurrency((data.sal_total || 0) - (data.sal_paid_amount || 0))}</td>
                        </tr>
                        ` : ''}
                        
                        ${(isSignificant(data.sales_return_total) || isSignificant(data.sales_return_tax_amt) || isSignificant(data.sales_return_other_charges_amt) || isSignificant(data.sales_return_coupon_amt) || isSignificant(data.sales_return_discount_amt) || isSignificant(data.sales_return_paid_amount)) ? `
                        <tr style="background: #ffe8e8; border-top: 2px solid #e74c3c;">
                            <td colspan="2" style="padding: 8px 12px; font-weight: bold; font-size: 16px; color: #e74c3c; text-transform: uppercase; letter-spacing: 1px;">SALES RETURNS</td>
                        </tr>
                        ` : ''}
                        
                        ${isSignificant(data.sales_return_total) ? `
                        <tr style="border-bottom: 1px solid #eee;">
                            <td style="padding: 6px 12px; font-weight: 500; border-right: 2px solid #ddd;">Total Sales Return</td>
                            <td style="padding: 6px 12px; text-align: right; font-weight: bold;">${formatCurrency(data.sales_return_total || 0)}</td>
                        </tr>
                        ` : ''}
                        ${isSignificant(data.sales_return_tax_amt) ? `
                        <tr style="border-bottom: 1px solid #eee;">
                            <td style="padding: 6px 12px; font-weight: 500; border-right: 2px solid #ddd;">Total Sales Return Tax</td>
                            <td style="padding: 6px 12px; text-align: right; font-weight: bold;">${formatCurrency(data.sales_return_tax_amt || 0)}</td>
                        </tr>
                        ` : ''}
                        ${isSignificant(data.sales_return_other_charges_amt) ? `
                        <tr style="border-bottom: 1px solid #eee;">
                            <td style="padding: 6px 12px; font-weight: 500; border-right: 2px solid #ddd;">Total Other Charges of Sales Return</td>
                            <td style="padding: 6px 12px; text-align: right; font-weight: bold;">${formatCurrency(data.sales_return_other_charges_amt || 0)}</td>
                        </tr>
                        ` : ''}
                        ${isSignificant(data.sales_return_coupon_amt) ? `
                        <tr style="border-bottom: 1px solid #eee;">
                            <td style="padding: 6px 12px; font-weight: 500; border-right: 2px solid #ddd;">Coupon Discount</td>
                            <td style="padding: 6px 12px; text-align: right; font-weight: bold;">${formatCurrency(data.sales_return_coupon_amt || 0)}</td>
                        </tr>
                        ` : ''}
                        ${isSignificant(data.sales_return_discount_amt) ? `
                        <tr style="border-bottom: 1px solid #eee;">
                            <td style="padding: 6px 12px; font-weight: 500; border-right: 2px solid #ddd;">Total Discount on Sales Return</td>
                            <td style="padding: 6px 12px; text-align: right; font-weight: bold;">${formatCurrency(data.sales_return_discount_amt || 0)}</td>
                        </tr>
                        ` : ''}
                        ${isSignificant(data.sales_return_paid_amount) ? `
                        <tr style="border-bottom: 1px solid #eee;">
                            <td style="padding: 6px 12px; font-weight: 500; border-right: 2px solid #ddd;">Paid Amount</td>
                            <td style="padding: 6px 12px; text-align: right; font-weight: bold;">${formatCurrency(data.sales_return_paid_amount || 0)}</td>
                        </tr>
                        ` : ''}
                        ${isSignificant((data.sales_return_total || 0) - (data.sales_return_paid_amount || 0)) ? `
                        <tr style="border-bottom: 1px solid #eee;">
                            <td style="padding: 6px 12px; font-weight: 500; border-right: 2px solid #ddd;">Sales Return Due</td>
                            <td style="padding: 6px 12px; text-align: right; font-weight: bold;">${formatCurrency((data.sales_return_total || 0) - (data.sales_return_paid_amount || 0))}</td>
                        </tr>
                        ` : ''}
                        
                        ${isSignificant(data.expense_total) ? `
                        <tr style="background: #fff3cd; border-top: 2px solid #f39c12;">
                            <td colspan="2" style="padding: 8px 12px; font-weight: bold; font-size: 16px; color: #f39c12; text-transform: uppercase; letter-spacing: 1px;">EXPENSES</td>
                        </tr>
                        ` : ''}
                        
                        ${isSignificant(data.expense_total) ? `
                        <tr style="border-bottom: 1px solid #eee;">
                            <td style="padding: 6px 12px; font-weight: 500; border-right: 2px solid #ddd;">Total Expense</td>
                            <td style="padding: 6px 12px; text-align: right; font-weight: bold;">${formatCurrency(data.expense_total || 0)}</td>
                        </tr>
                        ` : ''}
                        
                        <tr style="background: #2c3e50; border-top: 3px solid #2c3e50;">
                            <td colspan="2" style="padding: 10px 12px; font-weight: bold; font-size: 18px; color: white; text-transform: uppercase; letter-spacing: 1px;">SUMMARY</td>
                        </tr>
                        
                        <tr style="border-bottom: 2px solid #2c3e50; background: #f8f9fa;">
                            <td style="padding: 8px 12px; font-weight: bold; font-size: 16px; border-right: 2px solid #ddd;">Gross Profit</td>
                            <td style="padding: 8px 12px; text-align: right; font-weight: bold; font-size: 16px; color: ${grossProfit >= 0 ? '#27ae60' : '#e74c3c'};">${formatCurrency(grossProfit)}</td>
                        </tr>
                        <tr style="border-bottom: 2px solid #2c3e50; background: #f8f9fa;">
                            <td style="padding: 8px 12px; font-weight: bold; font-size: 16px; border-right: 2px solid #ddd;">Total Expenses</td>
                            <td style="padding: 8px 12px; text-align: right; font-weight: bold; font-size: 16px;">${formatCurrency(data.expense_total || 0)}</td>
                        </tr>
                        <tr style="background: #2c3e50; color: white;">
                            <td style="padding: 10px 12px; font-weight: bold; font-size: 18px; border-right: 2px solid #34495e;">Net Profit/Loss</td>
                            <td style="padding: 10px 12px; text-align: right; font-weight: bold; font-size: 18px; color: ${netProfit >= 0 ? '#27ae60' : '#e74c3c'};">${formatCurrency(netProfit)}</td>
                        </tr>
                    </tbody>
                </table>
            `;
        }

        function generateProfessionalReceiptContent80MM(data, formatCurrency) {
            // Calculate totals
            var grossProfit = parseFloat(data.gross_profit || 0);
            var netProfit = parseFloat(data.net_profit || 0);
            var totalRevenue = parseFloat(data.sal_total || 0);
            var totalExpenses = parseFloat(data.pur_total || 0) + parseFloat(data.expense_total || 0);
            
            return `
                <table class="receipt-table">
                    <tr class="section-header">
                        <th colspan="2">OPENING STOCK</th>
                    </tr>
                    <tr>
                        <td>Opening Stock</td>
                        <td class="amount">${formatCurrency(data.opening_stock_price || 0)}</td>
                    </tr>
                </table>
                
                <table class="receipt-table">
                    <tr class="section-header">
                        <th colspan="2">PURCHASES</th>
                    </tr>
                    <tr>
                        <td>Total Purchase</td>
                        <td class="amount">${formatCurrency(data.pur_total || 0)}</td>
                    </tr>
                    <tr>
                        <td>Purchase Tax</td>
                        <td class="amount">${formatCurrency(data.purchase_tax_amt || 0)}</td>
                    </tr>
                    <tr>
                        <td>Other Charges</td>
                        <td class="amount">${formatCurrency(data.pur_other_charges_amt || 0)}</td>
                    </tr>
                    <tr>
                        <td>Discount</td>
                        <td class="amount">${formatCurrency(data.purchase_discount_amt || 0)}</td>
                    </tr>
                </table>
                
                <table class="receipt-table">
                    <tr class="section-header">
                        <th colspan="2">SALES</th>
                    </tr>
                    <tr>
                        <td>Sales (Before Tax)</td>
                        <td class="amount">${formatCurrency(data.sal_total || 0)}</td>
                    </tr>
                    <tr>
                        <td>Sales Tax</td>
                        <td class="amount">${formatCurrency(data.sales_tax_amt || 0)}</td>
                    </tr>
                    <tr>
                        <td>Other Charges</td>
                        <td class="amount">${formatCurrency(data.sal_other_charges_amt || 0)}</td>
                    </tr>
                    <tr>
                        <td>Discount</td>
                        <td class="amount">${formatCurrency(data.sales_discount_amt || 0)}</td>
                    </tr>
                    <tr>
                        <td>Coupon Discount</td>
                        <td class="amount">${formatCurrency(data.coupon_discount_amt || 0)}</td>
                    </tr>
                </table>
                
                <table class="receipt-table">
                    <tr class="section-header">
                        <th colspan="2">EXPENSES</th>
                    </tr>
                    <tr>
                        <td>Total Expense</td>
                        <td class="amount">${formatCurrency(data.expense_total || 0)}</td>
                    </tr>
                </table>
                
                <table class="receipt-table">
                    <tr class="section-header">
                        <th colspan="2">SUMMARY</th>
                    </tr>
                    <tr>
                        <td><strong>Gross Profit</strong></td>
                        <td class="amount ${grossProfit >= 0 ? 'positive' : 'negative'}"><strong>${formatCurrency(grossProfit)}</strong></td>
                    </tr>
                    <tr>
                        <td><strong>Total Expenses</strong></td>
                        <td class="amount"><strong>${formatCurrency(data.expense_total || 0)}</strong></td>
                    </tr>
                    <tr class="total">
                        <td><strong>Net Profit/Loss</strong></td>
                        <td class="amount ${netProfit >= 0 ? 'positive' : 'negative'}"><strong>${formatCurrency(netProfit)}</strong></td>
                    </tr>
                </table>
            `;
        }
        
        function generateReceiptContent() {
            // Get the actual report data from the loaded report
            var content = '';
            
            // Get all the tables from the main report
            var tables = document.querySelectorAll('#report-container .pl-table');
            tables.forEach(function(table) {
                content += table.outerHTML;
            });
            
            // If no tables found, show a message
            if (content === '') {
                content = '<div style="text-align: center; padding: 20px; color: #666;">No data available. Please generate the report first.</div>';
            }
            
            return content;
        }
        
        function generateReceiptContent80MM() {
            // Get the actual report data from the loaded report for 80MM format
            var content = '';
            
            // Get all the tables from the main report
            var tables = document.querySelectorAll('#report-container .pl-table');
            tables.forEach(function(table) {
                // Clone the table and modify for 80MM
                var clonedTable = table.cloneNode(true);
                clonedTable.className = 'receipt-table';
                
                // Make it more compact for 80MM
                var cells = clonedTable.querySelectorAll('th, td');
                cells.forEach(function(cell) {
                    cell.style.padding = '2px 4px';
                    cell.style.fontSize = '8px';
                });
                
                content += clonedTable.outerHTML;
            });
            
            // If no tables found, show a message
            if (content === '') {
                content = '<div style="text-align: center; padding: 10px; color: #666; font-size: 8px;">No data available. Please generate the report first.</div>';
            }
            
            return content;
        }
    </script>
    
    <!-- Footer -->
    <?php include"footer.php"; ?>
    <div class="control-sidebar-bg"></div>
    </div>
    <!-- ./wrapper -->

    <?php include "comman/code_js.php"; ?>
    <!-- Make sidebar menu highlighter/selector -->
    <script>$(".report-profit-loss-professional-active-li").addClass("active");</script>
   </body>
</html>
