<!DOCTYPE html>
<html>
<head>
    <!-- TABLES CSS CODE -->
    <?php include"comman/code_css.php"; ?>
     <style>

/* ==========================================================
   CUSTOMER STATEMENT REPORT
   Optimized for:
   - Screen
   - A4 PDF
   - 80MM Thermal Receipt
   ========================================================== */

:root{
    --primary:#1f2937;
    --primary-light:#374151;
    --border:#d9dee5;
    --soft:#f8fafc;
    --soft-dark:#f1f5f9;
    --text:#111827;
    --text-light:#6b7280;
    --success:#15803d;
    --danger:#b91c1c;
}

/* ==========================================================
   GLOBAL
   ========================================================== */

body{
    font-family: Arial, Helvetica, sans-serif;
    background:#f5f7fa;
    color:var(--text);
    font-size:13px;
    line-height:1.5;
}

.report-container{
    background:#fff;
    max-width:1200px;
    margin:15px auto;
    padding:24px;
    border:1px solid var(--border);
    border-radius:6px;
    box-shadow:0 1px 3px rgba(0,0,0,.06);
}

/* ==========================================================
   COMPANY HEADER
   ========================================================== */

.company-header{
    text-align:center;
    border-bottom:2px solid var(--primary);
    padding-bottom:15px;
    margin-bottom:20px;
}

.company-logo{
    max-height:70px;
    width:auto;
    margin-bottom:10px;
}

.company-name{
    font-size:28px;
    font-weight:700;
    color:var(--primary);
    margin-bottom:6px;
    letter-spacing:.5px;
}

.company-details{
    font-size:13px;
    color:var(--text-light);
    line-height:1.7;
}

/* ==========================================================
   REPORT TITLE
   ========================================================== */

.report-title{
    text-align:center;
    font-size:20px;
    font-weight:700;
    color:var(--primary);
    padding:12px 16px;
    margin:15px 0;
    background:#f8fafc;
    border:1px solid var(--border);
    border-radius:4px;
}

.report-period,
.report-currency{
    text-align:center;
    font-size:14px;
    font-weight:600;
    color:#374151;
    margin-bottom:6px;
}

/* ==========================================================
   CUSTOMER INFORMATION
   ========================================================== */

.customer-info{
    margin:20px 0;
    padding:18px;
    background:#fafbfc;
    border:1px solid var(--border);
    border-left:4px solid var(--primary);
    border-radius:4px;
}

.customer-info h3{
    margin:0 0 15px;
    font-size:16px;
    font-weight:700;
    color:var(--primary);
}

.customer-details{
    display:grid;
    grid-template-columns:repeat(auto-fit,minmax(220px,1fr));
    gap:14px;
}

.customer-detail{
    min-width:0;
}

.customer-detail strong{
    display:block;
    font-size:11px;
    text-transform:uppercase;
    letter-spacing:.8px;
    color:var(--text-light);
    margin-bottom:4px;
}

.customer-detail span{
    font-size:14px;
    color:var(--text);
    font-weight:600;
    word-break:break-word;
}

/* ==========================================================
   SUMMARY CARDS
   ========================================================== */

.summary-cards{
    display:flex;
    flex-wrap:wrap;
    gap:15px;
    margin:25px 0;
}

.summary-card{
    flex:1;
    min-width:220px;
    background:#fff;
    border:1px solid var(--border);
    border-top:4px solid var(--primary);
    border-radius:6px;
    padding:18px;
    text-align:center;
    box-shadow:none;
}

.summary-card h3{
    font-size:14px;
    color:#555;
    margin-bottom:10px;
    text-transform:uppercase;
}

.summary-card .amount{
    font-size:24px;
    font-weight:700;
    color:var(--primary);
}

/* ==========================================================
   TABLE
   ========================================================== */

.statement-table{
    width:100%;
    border-collapse:collapse;
    margin-top:20px;
    background:#fff;
    table-layout:auto;
}

.statement-table thead{
    display:table-header-group;
}

.statement-table th{
    background:var(--primary);
    color:#fff;
    font-size:11px;
    font-weight:700;
    text-transform:uppercase;
    letter-spacing:.5px;
    padding:10px 8px;
    border:1px solid #d1d5db;
    white-space:nowrap;
}

.statement-table td{
    padding:8px;
    border:1px solid #e5e7eb;
    font-size:12px;
    color:#111;
    vertical-align:top;
}

.statement-table tbody tr:nth-child(even){
    background:#fafafa;
}

.statement-table tbody tr:hover{
    background:#f3f7fb;
}

/* ==========================================================
   MONEY COLUMNS
   ========================================================== */

.amount{
    text-align:right;
    font-weight:700;
    white-space:nowrap;
    font-variant-numeric:tabular-nums;
}

.positive{
    color:var(--success);
}

.negative{
    color:var(--danger);
}

/* ==========================================================
   SPECIAL ROWS
   ========================================================== */

.section-title{
    background:#eef2f7 !important;
    color:#111 !important;
    font-weight:700 !important;
    font-size:13px !important;
}

.total-row{
    background:#e9edf3 !important;
    color:#111 !important;
    font-weight:700 !important;
}

.total-row td{
    font-weight:700 !important;
}

/* ==========================================================
   EXPORT BUTTONS
   ========================================================== */

.export-buttons{
    text-align:center;
    padding:18px;
    margin:20px 0;
    background:#fafafa;
    border:1px solid var(--border);
    border-radius:6px;
}

.export-btn{
    display:inline-block;
    padding:11px 18px;
    margin:5px;
    border:none;
    border-radius:4px;
    color:#fff;
    font-size:13px;
    font-weight:600;
    cursor:pointer;
    transition:.2s;
    text-decoration:none;
}

.export-btn:hover{
    opacity:.92;
}

.export-btn.primary{background:#2563eb;}
.export-btn.success{background:#16a34a;}
.export-btn.warning{background:#ea580c;}
.export-btn.info{background:#0891b2;}
.export-btn.danger{background:#dc2626;}

/* ==========================================================
   FILTERS
   ========================================================== */

.filters{
    background:#fff;
    border:1px solid var(--border);
    border-radius:6px;
    padding:20px;
    margin-bottom:20px;
}

.form-group{
    margin-bottom:15px;
}

.form-group label{
    font-weight:600;
    color:#374151;
    margin-bottom:6px;
    display:block;
}

.btn-primary{
    background:#2563eb;
    border-color:#2563eb;
    font-weight:600;
}

.btn-primary:hover{
    background:#1d4ed8;
    border-color:#1d4ed8;
}

.btn-block{
    width:100%;
}

/* ==========================================================
   LOADING / ERROR
   ========================================================== */

.loading,
.error{
    text-align:center;
    padding:40px;
}

.loading{
    color:#6b7280;
}

.error{
    color:#dc2626;
}

/* ==========================================================
   PAGE HEADER
   ========================================================== */

.content-wrapper .content-header.statement-header{
    background:#fff;
    border-bottom:1px solid #e5e7eb;
    padding:18px;
}

.content-header.statement-header h1{
    margin:0;
    font-size:22px;
    font-weight:700;
    color:var(--primary);
}

.content-header.statement-header h1 small{
    display:block;
    margin-top:4px;
    color:#6b7280;
    font-size:12px;
    font-weight:400;
}

.content-header.statement-header .breadcrumb{
    background:transparent;
    padding:0;
    margin-top:8px;
    font-size:12px;
}

.content-header.statement-header .breadcrumb li a{
    color:var(--primary);
}

/* ==========================================================
   RESPONSIVE
   ========================================================== */

@media (max-width:768px){

    .report-container{
        padding:12px;
    }

    .company-name{
        font-size:22px;
    }

    .customer-details{
        grid-template-columns:1fr;
    }

    .summary-cards{
        flex-direction:column;
    }

    .statement-table{
        font-size:11px;
    }

    .statement-table th,
    .statement-table td{
        padding:6px;
    }
}

/* ==========================================================
   PRINT (A4 + PDF)
   ========================================================== */

@media print{

    body{
        background:#fff !important;
        color:#000 !important;
        font-size:11px;
        line-height:1.35;
        margin:0;
        padding:0;
    }

    .no-print,
    .sidebar,
    .main-sidebar,
    .navbar,
    .content-header,
    .export-buttons{
        display:none !important;
    }

    .report-container{
        border:none !important;
        box-shadow:none !important;
        padding:0 !important;
        margin:0 !important;
        width:100%;
        max-width:100%;
    }

    .summary-cards{
        display:none !important;
    }

    .company-header{
        border-bottom:2px solid #000;
        margin-bottom:15px;
        padding-bottom:10px;
    }

    .company-name{
        color:#000 !important;
        font-size:18px;
        font-weight:700;
    }

    .company-details{
        color:#000 !important;
        font-size:11px;
    }

    .report-title{
        background:#f0f0f0 !important;
        color:#000 !important;
        border:1px solid #000 !important;
        font-size:15px;
        font-weight:700;
    }

    .report-period,
    .report-currency{
        color:#000 !important;
        font-size:11px;
    }

    .customer-info{
        background:#fff !important;
        border:1px solid #000 !important;
        margin-bottom:12px;
    }

    .statement-table{
        width:100%;
        border-collapse:collapse;
        font-size:10px;
        page-break-inside:auto;
    }

    .statement-table thead{
        display:table-header-group;
    }

    .statement-table tr{
        page-break-inside:avoid;
        page-break-after:auto;
    }

    .statement-table th{
        background:#e5e5e5 !important;
        color:#000 !important;
        border:1px solid #000 !important;
        padding:6px;
        font-size:10px;
        font-weight:700;
    }

    .statement-table td{
        border:1px solid #000 !important;
        color:#000 !important;
        padding:5px;
        font-size:10px;
        font-weight:400;
    }

    .amount{
        font-weight:700 !important;
    }

    .positive,
    .negative{
        color:#000 !important;
    }

    .section-title,
    .total-row{
        background:#e5e5e5 !important;
        color:#000 !important;
    }

    *{
        -webkit-print-color-adjust:exact;
        print-color-adjust:exact;
    }

    @page{
        size:A4 portrait;
        margin:8mm;
    }
}

/* ==========================================================
   80MM RECEIPT PRINTING
   ========================================================== */

@media print and (max-width:80mm){

    body{
        font-size:9px;
    }

    .company-logo{
        max-height:45px;
    }

    .company-name{
        font-size:14px;
    }

    .company-details{
        font-size:8px;
        line-height:1.3;
    }

    .report-title{
        font-size:11px;
        padding:6px;
    }

    .report-period,
    .report-currency{
        font-size:8px;
    }

    .customer-details{
        display:block;
    }

    .customer-detail{
        margin-bottom:6px;
    }

    .customer-detail strong{
        font-size:8px;
    }

    .customer-detail span{
        font-size:9px;
    }

    .statement-table{
        font-size:8px;
    }

    .statement-table th{
        font-size:7px;
        padding:3px;
    }

    .statement-table td{
        font-size:8px;
        padding:3px;
    }

    .amount{
        font-size:8px;
    }

    @page{
        size:80mm auto;
        margin:2mm;
    }
}

</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 statement-header">
                <h1>
                    Supplier Statement
                    <small>View and export statements by supplier and date range</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">Supplier Statement</li>
                </ol>
            </section>
            
            <section class="content">
                <div class="row">
                    <div class="col-md-12">
                        <!-- Filters -->
                        <div class="box box-primary no-print statement-filters">
                            <div class="box-header with-border">
                                <h3 class="box-title">Filters</h3>
                            </div>
                            <div class="box-body">
                                <div class="row">
                                    <div class="col-md-3">
                                        <div class="form-group">
                                            <label>Select Supplier</label>
                                            <select class="form-control" id="supplier_id" name="supplier_id">
                                                <option value="">— Select Supplier —</option>
                                                <?php
                                                $this->db->where('store_id', get_current_store_id());
                                                $this->db->order_by('supplier_name', 'ASC');
                                                $suppliers = $this->db->get('db_suppliers')->result();
                                                if(!empty($suppliers)) {
                                                    foreach($suppliers as $supplier) {
                                                        $extra = trim($supplier->mobile ?? '') !== '' ? ' (' . htmlspecialchars($supplier->mobile) . ')' : '';
                                                        echo '<option value="'.$supplier->id.'">'.htmlspecialchars($supplier->supplier_name).$extra.'</option>';
                                                    }
                                                } else {
                                                    echo '<option value="">No suppliers found</option>';
                                                }
                                                ?>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="col-md-3">
                                        <div class="form-group">
                                            <label>Date Range</label>
                                            <div class="input-group">
                                                <button type="button" class="btn btn-default" id="ss-daterange-btn">
                                                    <i class="fa fa-calendar"></i> <span></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>
                            </div>
                        </div>
                        
                        <!-- Report Container -->
                        <div class="report-container" id="report-container" style="display: none;">
                            <!-- Welcome Message -->
                            <div id="welcome-message" class="text-center" style="padding: 40px; color: #666;">
                                <i class="fa fa-truck fa-3x" style="margin-bottom: 20px; color: #f39c12;"></i>
                                <h3>Supplier Statement Report</h3>
                                <p>Select a supplier from the dropdown above to view their statement</p>
                                <p><small>You can also adjust the date range to filter transactions</small></p>
                            </div>
                            <!-- 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">Supplier Statement</div>
                            <div class="report-period" id="report-period">Period: Loading...</div>
                            <?php 
                            $base_currency = isset($base_currency) ? $base_currency : null;
                            $statement_currency_code = $base_currency && isset($base_currency->currency_code) ? $base_currency->currency_code : '';
                            $statement_currency_symbol = $base_currency ? (isset($base_currency->symbol) ? $base_currency->symbol : (isset($base_currency->currency_symbol) ? $base_currency->currency_symbol : '')) : '';
                            if ($statement_currency_code && $statement_currency_symbol) {
                                $currency_display = $statement_currency_code . ' (' . $statement_currency_symbol . ')';
                            } elseif ($statement_currency_code) {
                                $currency_display = $statement_currency_code;
                            } elseif ($statement_currency_symbol) {
                                $currency_display = $statement_currency_symbol;
                            } else {
                                $currency_display = 'USD ($)';
                            }
                            ?>
                            <div class="report-currency" id="report-currency">Amounts in <?php echo htmlspecialchars($currency_display); ?></div>
                            
                            <!-- Supplier Info -->
                            <div class="supplier-info" id="supplier-info">
                                <!-- Will be populated by JavaScript -->
                            </div>
                            
                            <!-- Export Buttons -->
                            <div class="export-buttons no-print">
                                <button class="export-btn success" onclick="exportToPDF()">
                                    <i class="fa fa-file-pdf-o"></i> Export PDF
                                </button>
                                <button class="export-btn warning" onclick="exportToImage()">
                                    <i class="fa fa-image"></i> Export Image
                                </button>
                                <button class="export-btn info" onclick="exportToA4()">
                                    <i class="fa fa-file-text"></i> A4 Format
                                </button>
                                <button class="export-btn danger" onclick="exportTo80MM()">
                                    <i class="fa fa-print"></i> 80MM Receipt
                                </button>
                            </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>
                    </div>
                </div>
            </section>
        </div>
    </div>

    <!-- Include JavaScript -->
    <?php include"comman/code_js.php"; ?>
    
    <script>
        <?php $store = get_store_details(); ?>
        var _fallbackCompanyName = <?php echo json_encode(get_store_name() ? get_store_name() : 'Company Name'); ?>;
        var _fallbackCompanyDetails = <?php echo json_encode((isset($store->address) ? $store->address : 'Company Address') . '<br>' . (isset($store->mobile) ? 'Phone: ' . $store->mobile : 'Phone: Company Phone') . '<br>' . (isset($store->email) ? 'Email: ' . $store->email : 'Email: Company Email')); ?>;
        var _sessionCurrencyCode = <?php echo json_encode($this->session->userdata('currency_code') ?: 'USD'); ?>;
        var _sessionCurrencySymbol = <?php echo json_encode($this->session->userdata('currency_symbol') ?: '$'); ?>;
        var _sessionCurrencyPlacement = <?php echo json_encode($this->session->userdata('currency_placement') ?: 'Left'); ?>;
        $(document).ready(function() {
            // Initialize date range picker
            $('#ss-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 when supplier is selected
            $('#supplier_id').change(function() {
                if($(this).val()) {
                    generateReport();
                } else {
                    $('#report-container').hide();
                }
            });
            
            // Update date range display
            $('#ss-daterange-btn').on('apply.daterangepicker', function(ev, picker) {
                $(this).find('span').html(picker.startDate.format('MMM DD, YYYY') + ' - ' + picker.endDate.format('MMM DD, YYYY'));
                // Auto-generate report when date range changes
                if($('#supplier_id').val()) {
                    generateReport();
                }
            });
            
            // Set initial date range display
            var startDate = moment().subtract(29, 'days');
            var endDate = moment();
            $('#ss-daterange-btn').find('span').html(startDate.format('MMM DD, YYYY') + ' - ' + endDate.format('MMM DD, YYYY'));
            
            // Show welcome message on page load
            generateReport();
        });
        
        function generateReport() {
            var supplierId = $('#supplier_id').val();
            var dateRange = $('#ss-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();
            
            if (!supplierId) {
                // Show welcome message when no supplier selected
                $('#report-container').show();
                $('#welcome-message').show();
                $('#loading-state').hide();
                $('#error-state').hide();
                return;
            }
            
            // 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_supplier_statement',
                type: 'POST',
                data: {
                    supplier_id: supplierId,
                    from_date: fromDate,
                    to_date: toDate,
                    store_id: storeId
                },
                dataType: 'json',
                success: function(response) {
                    $('#loading-state').hide();
                    console.log('Response received:', response);
                    if (response.error) {
                        $('#error-state').show();
                        console.error('Report Error:', response.message);
                    } else {
                        displayReport(response);
                        $('#welcome-message').hide();
                        $('#report-container').show();
                    }
                },
                error: function(xhr, status, error) {
                    $('#loading-state').hide();
                    $('#error-state').show();
                    console.error('AJAX Error:', error);
                    console.error('Status:', status);
                    console.error('Response:', xhr.responseText);
                    console.error('Status Code:', xhr.status);
                }
            });
        }
        
        // Store report data globally for export functions
        var currentReportData = null;
        
        function displayReport(data) {
            // Store data globally for export functions
            currentReportData = data;
            
            // Format currency function with dynamic currency support
            function formatCurrency(amount, currencyInfo) {
                var num = parseFloat(amount);
                
                // Use transaction currency if available, otherwise fallback to session currency
                var currencyCode = currencyInfo && currencyInfo.currency_code ? currencyInfo.currency_code : _sessionCurrencyCode;
                var currencySymbol = currencyInfo && currencyInfo.currency_symbol ? currencyInfo.currency_symbol : _sessionCurrencySymbol;
                var currencyPosition = currencyInfo && currencyInfo.currency_position ? currencyInfo.currency_position : _sessionCurrencyPlacement;
                
                // 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;
                }
            }
            
            // Display supplier info
            var supplierInfo = `
                <h3>Supplier Information</h3>
                <div class="supplier-details">
                    <div class="supplier-detail">
                        <strong>Supplier Name</strong>
                        <span>${data.supplier.supplier_name}</span>
                    </div>
                    <div class="supplier-detail">
                        <strong>Mobile</strong>
                        <span>${data.supplier.mobile || 'N/A'}</span>
                    </div>
                    <div class="supplier-detail">
                        <strong>Email</strong>
                        <span>${data.supplier.email || 'N/A'}</span>
                    </div>
                    <div class="supplier-detail">
                        <strong>Address</strong>
                        <span>${data.supplier.address || 'N/A'}</span>
                    </div>
                </div>
            `;
            $('#supplier-info').html(supplierInfo);
            
            // Hide summary cards
            $('#summary-cards').hide();
            
            // Display transactions
            var transactionsHtml = `
                <table class="statement-table">
                    <thead>
                        <tr>
                            <th>Date</th>
                            <th>Type</th>
                            <th>Reference</th>
                            <th>Description</th>
                            <th>Credit Amount</th>
                            <th> Debit Amount</th>
                            <th>Balance Amount</th>
                        </tr>
                    </thead>
                    <tbody>
            `;
            
            data.transactions.forEach(function(transaction) {
                transactionsHtml += `
                    <tr>
                        <td>${transaction.date}</td>
                        <td>${transaction.type}</td>
                        <td>${transaction.reference}</td>
                        <td>${transaction.description}</td>
                        <td class="amount ${transaction.debit > 0 ? 'negative' : ''}">${transaction.debit > 0 ? formatCurrency(transaction.debit, transaction) : ''}</td>
                        <td class="amount ${transaction.credit > 0 ? 'positive' : ''}">${transaction.credit > 0 ? formatCurrency(transaction.credit, transaction) : ''}</td>
                        <td class="amount ${transaction.balance < 0 ? 'negative' : 'positive'}">${formatCurrency(transaction.balance, transaction)}</td>
                    </tr>
                `;
            });
            
            transactionsHtml += `
                    </tbody>
                </table>
            `;
            
            $('#report-content').html(transactionsHtml);
        }
        
        function exportToPDF() {
            var newWindow = window.open('', '_blank');
            newWindow.document.write(`
                <!DOCTYPE html>
                <html>
                <head>
                    <title>Supplier Statement - 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: #000;
                            font-weight: bold;
                            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;
                        }
                        .company-details {
                            font-size: 11px;
                            color: #000;
                            line-height: 1.3;
                        }
                        .report-title {
                            font-size: 18px;
                            font-weight: bold;
                            margin: 15px 0 8px 0;
                            text-transform: uppercase;
                            letter-spacing: 1px;
                            text-align: center;
                            color: #000;
                            background: #e8e8e8;
                            padding: 8px 12px;
                            border: 2px solid #000;
                            border-radius: 4px;
                        }
                        .report-period {
                            font-size: 12px;
                            color: #000;
                            margin-bottom: 20px;
                            font-weight: bold;
                            text-align: center;
                        }
                        .supplier-info {
                            background: #f8f9fa;
                            padding: 15px;
                            border-radius: 5px;
                            margin-bottom: 20px;
                            border-left: 4px solid #f39c12;
                        }
                        .statement-table {
                            width: 100%;
                            border-collapse: collapse;
                            margin: 10px 0;
                            font-size: 11px;
                        }
                        .statement-table th {
                            background: #d0d0d0;
                            color: #000;
                            padding: 8px 10px;
                            text-align: left;
                            font-weight: bold;
                            font-size: 10px;
                            text-transform: uppercase;
                            letter-spacing: 0.5px;
                        }
                        .statement-table td {
                            padding: 6px 10px;
                            border-bottom: 1px solid #000;
                            vertical-align: top;
                            color: #000;
                            font-weight: bold;
                        }
                        .statement-table .amount {
                            text-align: right;
                            font-weight: bold;
                        }
                        .positive { color: #000; }
                        .negative { color: #000; }
                        .separator {
                            border-top: 1px solid #000;
                            margin: 15px 0;
                        }
                        .footer {
                            margin-top: 30px;
                            text-align: center;
                            font-size: 10px;
                            color: #000;
                            font-weight: bold;
                            border-top: 1px solid #000;
                            padding-top: 10px;
                        }
                        .statement-table th, .statement-table td, .statement-table * { color: #000 !important; font-weight: bold !important; }
                        @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">
                        <div class="receipt-header">
                            <div class="company-name">${$('.company-name').text() || _fallbackCompanyName}</div>
                            <div class="company-details">
                                ${$('.company-details').html() || _fallbackCompanyDetails}
                            </div>
                        </div>
                        
                        <div class="report-title">Supplier Statement</div>
                        <div class="supplier-name" style="font-size: 16px; font-weight: bold; color: #000; margin: 10px 0; text-align: center;">Supplier: ${currentReportData ? currentReportData.supplier.supplier_name : 'N/A'}</div>
                        <div class="report-period">${$('#report-period').text() || 'Period: Not Set'}</div>
                        <div class="report-currency">${$('#report-currency').text() || 'Amounts in USD ($)'}</div>
                        
                        <div class="separator"></div>
                        
                        ${generateReceiptContent()}
                        
                        <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();
            
            // Use html2pdf on the new window
            setTimeout(function() {
                if (typeof html2pdf !== 'undefined') {
                    var element = newWindow.document.body;
                    var opt = {
                        margin: 0.5,
                        filename: 'Supplier_Statement_' + 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();
                }
            }, 1000);
        }
        
        function exportToImage() {
            var btn = event.target;
            btn.classList.add('loading');
            btn.disabled = true;
            
            // 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() {
            var element = document.getElementById('report-container');
            html2canvas(element, {
                scale: 2,
                useCORS: true,
                backgroundColor: '#ffffff'
            }).then(function(canvas) {
                var link = document.createElement('a');
                link.download = 'Supplier_Statement_' + new Date().toISOString().split('T')[0] + '.png';
                link.href = canvas.toDataURL();
                link.click();
            });
        }
        
        function exportToA4() {
            var newWindow = window.open('', '_blank');
            newWindow.document.write(`
                <!DOCTYPE html>
                <html>
                <head>
                    <title>Supplier Statement - A4 Format</title>
                    <style>
                        * { margin: 0; padding: 0; box-sizing: border-box; }
                        body { 
                            font-family: 'Arial', sans-serif; 
                            font-size: 11px; 
                            line-height: 1.3;
                            color: #000;
                            font-weight: bold;
                            background: white;
                        }
                        .receipt-container {
                            width: 210mm;
                            max-height: 297mm;
                            margin: 0 auto;
                            padding: 8mm;
                            background: white;
                            overflow: hidden;
                        }
                        .receipt-header {
                            text-align: center;
                            margin-bottom: 12px;
                            padding-bottom: 8px;
                            border-bottom: 2px solid #000;
                        }
                        .company-name {
                            font-size: 18px;
                            font-weight: bold;
                            margin-bottom: 4px;
                            text-transform: uppercase;
                            letter-spacing: 1px;
                            color: #000;
                        }
                        .company-details {
                            font-size: 9px;
                            color: #000;
                            font-weight: bold;
                            line-height: 1.2;
                        }
                        .report-title {
                            font-size: 14px;
                            font-weight: bold;
                            margin: 10px 0 4px 0;
                            text-transform: uppercase;
                            letter-spacing: 1px;
                            text-align: center;
                            color: #000;
                            background: #f0f0f0;
                            padding: 8px 12px;
                            border: 2px solid #000;
                            border-radius: 4px;
                        }
                        .report-period {
                            font-size: 10px;
                            color: #000;
                            font-weight: bold;
                            margin-bottom: 12px;
                            text-align: center;
                        }
                        .statement-table {
                            width: 100%;
                            border-collapse: collapse;
                            margin: 6px 0;
                            font-size: 9px;
                        }
                        .statement-table th {
                            background: #d0d0d0;
                            color: #000;
                            padding: 4px 6px;
                            text-align: left;
                            font-weight: bold;
                            font-size: 8px;
                            text-transform: uppercase;
                            letter-spacing: 0.3px;
                        }
                        .statement-table td {
                            padding: 3px 6px;
                            border-bottom: 1px solid #000;
                            vertical-align: top;
                            font-size: 9px;
                            color: #000;
                            font-weight: bold;
                        }
                        .statement-table .amount {
                            text-align: right;
                            font-weight: bold;
                        }
                        .positive { color: #000; }
                        .negative { color: #000; }
                        .separator {
                            border-top: 1px solid #000;
                            margin: 8px 0;
                        }
                        .footer {
                            margin-top: 15px;
                            text-align: center;
                            font-size: 8px;
                            color: #000;
                            font-weight: bold;
                            border-top: 1px solid #000;
                            padding-top: 6px;
                        }
                        .statement-table th, .statement-table td, .statement-table * { color: #000 !important; font-weight: bold !important; }
                        @media print {
                            body { margin: 0; padding: 0; }
                            .receipt-container { margin: 0; padding: 8mm; }
                            @page { size: A4; margin: 0; }
                        }
                    </style>
                </head>
                <body>
                    <div class="receipt-container">
                        <div class="receipt-header">
                            <div class="company-name">${$('.company-name').text() || _fallbackCompanyName}</div>
                            <div class="company-details">
                                ${$('.company-details').html() || _fallbackCompanyDetails}
                            </div>
                        </div>
                        
                        <div class="report-title">Supplier Statement</div>
                        <div class="supplier-name" style="font-size: 16px; font-weight: bold; color: #000; margin: 10px 0; text-align: center;">Supplier: ${currentReportData ? currentReportData.supplier.supplier_name : 'N/A'}</div>
                        <div class="report-period">${$('#report-period').text() || 'Period: Not Set'}</div>
                        <div class="report-currency">${$('#report-currency').text() || 'Amounts in USD ($)'}</div>
                        
                        <div class="separator"></div>
                        
                        ${generateReceiptContent()}
                        
                        <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();
            }, 500);
        }
        
        function exportTo80MM() {
            var newWindow = window.open('', '_blank');
            newWindow.document.write(`
                <!DOCTYPE html>
                <html>
                <head>
                    <title>Supplier Statement - 80MM Receipt</title>
                    <style>
                         * { margin: 0; padding: 0; box-sizing: border-box; }
                        body{
    font-family: Arial, Helvetica, sans-serif;
    font-size:11px;
    line-height:1.35;
    color:#000;
    background:#fff;
    width:80mm;
    font-weight:700;
    -webkit-font-smoothing:none;
}
*{
    color:#000 !important;
    font-weight:700 !important;
}
                        .receipt-container {
                            width:72mm;
                            margin:auto;
                            padding:2mm;
                            background:#fff;
                        }
                        .receipt-header {
                            text-align: center;
                            margin-bottom: 8px;
                            padding-bottom: 8px;
                            border-bottom: 1px solid #000;
                        }
                        .company-name{
    font-size:18px;
    font-weight:900;
    letter-spacing:1px;
    margin-bottom:5px;
    text-transform:uppercase;
    color:#000;
}
                        .company-details{
    font-size:10px;
    line-height:1.4;
    font-weight:700;
    color:#000;
}
                        .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;
                        }
                      
                        .positive { color: #000; }
                        .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">
                        <div class="receipt-header">
                            <div class="company-name">${$('.company-name').text() || 'COMPANY'}</div>
                            <div class="company-details">
                                ${$('.company-details').text() || 'Address'}
                            </div>
                        </div>
                        
                         <div class="report-title">Supplier Statement</div>
                        <div class="supplier-name" style="font-size: 16px; font-weight: bold; color: #000; margin: 10px 0; text-align: center;">Supplier: ${currentReportData ? currentReportData.supplier.supplier_name : 'N/A'}</div>
                        <div class="report-period">${$('#report-period').text() || 'Period: Not Set'}</div>
                        <div class="report-currency">${$('#report-currency').text() || 'Amounts in USD ($)'}</div>
                        
                        <div class="separator"></div>
                        
                        ${generateReceiptContent80MM()}
                        
                        <div class="footer">
                            <div>Generated: ${new Date().toLocaleString()}</div>
                        </div>
                    </div>
                </body>
                </html>
            `);
            newWindow.document.close();
            
            setTimeout(function() {
                newWindow.print();
            }, 500);
        }
        
        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 .statement-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() {

    if (!currentReportData || !currentReportData.transactions) {
        return `
            <div style="text-align:center;padding:10px;">
                No data available
            </div>
        `;
    }

    let content = '';

    currentReportData.transactions.forEach(function(tx,index){

        const credit =
            parseFloat(tx.credit) > 0
                ? tx.credit
                : '-';

        const debit =
            parseFloat(tx.debit) > 0
                ? tx.debit
                : '-';

        const balance =
            tx.balance || 0;

        content += `
        
        <div style="
            border-bottom:2px solid #000;;
            padding:6px 0;
            margin-bottom:4px;
        ">

            <div style="
                display:flex;
                justify-content:space-between;
                font-weight:bold;
                font-size:10px;
            ">
                <span>${tx.date}</span>
                <span>${tx.type}</span>
            </div>

            <div style="
                margin-top:2px;
                font-size:11px;
                font-weight:700;
            ">
                Ref: ${tx.reference || '-'}
            </div>

            <div style="
                margin-top:2px;
                font-size:9px;
            ">
                ${tx.description || '-'}
            </div>

            <div style="
                margin-top:4px;
                font-size:9px;
            ">
                Credit : ${credit}
            </div>

            <div style="
                font-size:9px;
            ">
                Debit  : ${debit}
            </div>

            <div style="
                margin-top:3px;
                font-size:10px;
                font-weight:bold;
            ">
                Balance: ${balance}
            </div>

        </div>
        `;
    });

    return content;
}
    </script>
</body>
</html>
