<!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;
            }
            .statement-table {
                font-size: 11px;
                border-collapse: collapse;
            }
            .statement-table th,
            .statement-table td {
                padding: 6px 8px;
                border: 1px solid #000;
            }
            .statement-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);
            max-width: 1200px;
            margin: 0 auto;
        }
        
        .company-header {
            text-align: center;
            margin-bottom: 30px;
            padding-bottom: 20px;
            border-bottom: 2px solid #2c3e50;
        }
        
        .company-logo {
            max-height: 80px;
            margin-bottom: 15px;
        }
        
        .company-name {
            font-size: 28px;
            font-weight: bold;
            color: #2c3e50;
            margin-bottom: 10px;
            text-transform: uppercase;
            letter-spacing: 2px;
        }
        
        .company-details {
            font-size: 14px;
            color: #666;
            line-height: 1.6;
        }
        
        .report-title {
            font-size: 24px;
            font-weight: bold;
            color: #e74c3c;
            text-align: center;
            margin: 20px 0;
            text-transform: uppercase;
            letter-spacing: 1px;
            background: #fdf2f2;
            padding: 15px;
            border: 2px solid #e74c3c;
            border-radius: 8px;
        }
        
        .report-period {
            font-size: 16px;
            color: #666;
            text-align: center;
            margin-bottom: 30px;
            font-weight: bold;
        }
        
        .customer-info {
            background: #f8f9fa;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 30px;
            border-left: 4px solid #3498db;
        }
        
        .customer-info h3 {
            color: #2c3e50;
            margin-bottom: 15px;
            font-size: 18px;
        }
        
        .customer-details {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 15px;
        }
        
        .customer-detail {
            display: flex;
            flex-direction: column;
        }
        
        .customer-detail strong {
            color: #2c3e50;
            font-size: 12px;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            margin-bottom: 5px;
        }
        
        .customer-detail span {
            color: #666;
            font-size: 14px;
        }
        
        .export-buttons {
            text-align: center;
            margin: 20px 0;
            padding: 20px;
            background: #f8f9fa;
            border-radius: 8px;
        }
        
        .export-btn {
            display: inline-block;
            padding: 12px 24px;
            margin: 5px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 14px;
            font-weight: bold;
            text-decoration: none;
            transition: all 0.3s ease;
            min-width: 120px;
        }
        
        .export-btn.primary { background: #3498db; color: white; }
        .export-btn.success { background: #27ae60; color: white; }
        .export-btn.warning { background: #f39c12; color: white; }
        .export-btn.info { background: #17a2b8; color: white; }
        .export-btn.danger { background: #e74c3c; color: white; }
        
        .export-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.2);
        }
        
        .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;
            margin: 10px;
            min-width: 200px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
        }
        
        .summary-card h3 {
            margin: 0 0 10px 0;
            font-size: 18px;
        }
        
        .summary-card .amount {
            font-size: 24px;
            font-weight: bold;
        }
        
        .statement-table {
            width: 100%;
            border-collapse: collapse;
            margin: 20px 0;
            background: white;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        .statement-table th {
            background: linear-gradient(135deg, #2c3e50 0%, #34495e 100%);
            color: white;
            padding: 15px 12px;
            text-align: left;
            font-weight: bold;
            font-size: 12px;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }
        
        .statement-table td {
            padding: 12px;
            border-bottom: 1px solid #e9ecef;
            font-size: 12px;
            line-height: 1.4;
        }
        
        .statement-table tr:nth-child(even) {
            background-color: #f8f9fa;
        }
        
        .statement-table tr:hover {
            background-color: #e3f2fd;
        }
        
        .amount {
            text-align: right;
            font-weight: bold;
        }
        
        .positive {
            color: #27ae60;
        }
        
        .negative {
            color: #e74c3c;
        }
        
        .section-title {
            background: #3498db !important;
            color: white !important;
            font-weight: bold;
            font-size: 13px;
            padding: 10px 15px !important;
        }
        
        .total-row {
            background: #2c3e50 !important;
            color: white !important;
            font-weight: bold;
            font-size: 14px;
            padding: 15px 12px !important;
        }
        
        .loading {
            text-align: center;
            padding: 40px;
            color: #666;
        }
        
        .error {
            text-align: center;
            padding: 40px;
            color: #e74c3c;
        }
        
        .filters {
            background: #f8f9fa;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 20px;
        }
        
        .form-group {
            margin-bottom: 15px;
        }
        
        .form-group label {
            font-weight: 600;
            margin-bottom: 5px;
            display: block;
        }
        
        .btn-primary {
            background: #3498db;
            border-color: #3498db;
            padding: 10px 30px;
            font-size: 16px;
            font-weight: bold;
        }
        
        .btn-primary:hover {
            background: #2980b9;
            border-color: #2980b9;
        }
        
        .daterangepicker {
            z-index: 9999;
        }
        
        .daterangepicker .ranges li:hover {
            background-color: #f5f5f5;
        }
        
        .daterangepicker .ranges li.active {
            background-color: #3c8dbc;
            color: white;
        }
        
        .form-group label {
            font-weight: 600;
            margin-bottom: 5px;
        }
        
        .btn-block {
            width: 100%;
        }
        
        .loading .export-btn {
            opacity: 0.6;
            cursor: not-allowed;
        }
        
        .loading .export-btn::after {
            content: " ⏳";
        }
        
        @media (max-width: 768px) {
            .summary-cards {
                flex-direction: column;
                align-items: center;
            }
            
            .statement-table {
                font-size: 11px;
            }
            
            .statement-table th,
            .statement-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">
                        <!-- Filters -->
                        <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>Select Customer</label>
                                            <select class="form-control" id="customer_id" name="customer_id">
                                                <option value="">Select Customer</option>
                                                <?php
                                                $this->db->where('store_id', get_current_store_id());
                                                $this->db->order_by('customer_name', 'ASC');
                                                $customers = $this->db->get('db_customers')->result();
                                                if(!empty($customers)) {
                                                    foreach($customers as $customer) {
                                                        echo '<option value="'.$customer->id.'">'.$customer->customer_name.' ('.$customer->mobile.')</option>';
                                                    }
                                                } else {
                                                    echo '<option value="">No customers 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="cs-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-user fa-3x" style="margin-bottom: 20px; color: #3498db;"></i>
                                <h3>Customer Statement Report</h3>
                                <p>Select a customer 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">Customer Statement</div>
                            <div class="report-period" id="report-period">Period: Loading...</div>
                            
                            <!-- Customer Info -->
                            <div class="customer-info" id="customer-info">
                                <!-- Will be populated by JavaScript -->
                            </div>
                            
                            <!-- Export Buttons -->
                            <div class="export-buttons no-print">
                                <button class="export-btn primary" onclick="printReport()">
                                    <i class="fa fa-print"></i> Print
                                </button>
                                <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>
        $(document).ready(function() {
            // Initialize date range picker
            $('#cs-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 customer is selected
            $('#customer_id').change(function() {
                if($(this).val()) {
                    generateReport();
                } else {
                    $('#report-container').hide();
                }
            });
            
            // Update date range display
            $('#cs-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($('#customer_id').val()) {
                    generateReport();
                }
            });
            
            // Set initial date range display
            var startDate = moment().subtract(29, 'days');
            var endDate = moment();
            $('#cs-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 customerId = $('#customer_id').val();
            var dateRange = $('#cs-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 (!customerId) {
                // Show welcome message when no customer 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_customer_statement',
                type: 'POST',
                data: {
                    customer_id: customerId,
                    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 : '<?php echo $this->session->userdata("currency_code") ?: "USD"; ?>';
                var currencySymbol = currencyInfo && currencyInfo.currency_symbol ? currencyInfo.currency_symbol : '<?php echo $this->session->userdata("currency_symbol") ?: "$"; ?>';
                var currencyPosition = currencyInfo && currencyInfo.currency_position ? currencyInfo.currency_position : '<?php echo $this->session->userdata("currency_placement") ?: "Left"; ?>';
                
                // 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 customer info
            var customerInfo = `
                <h3>Customer Information</h3>
                <div class="customer-details">
                    <div class="customer-detail">
                        <strong>Customer Name</strong>
                        <span>${data.customer.customer_name}</span>
                    </div>
                    <div class="customer-detail">
                        <strong>Mobile</strong>
                        <span>${data.customer.mobile || 'N/A'}</span>
                    </div>
                    <div class="customer-detail">
                        <strong>Email</strong>
                        <span>${data.customer.email || 'N/A'}</span>
                    </div>
                    <div class="customer-detail">
                        <strong>Address</strong>
                        <span>${data.customer.address || 'N/A'}</span>
                    </div>
                </div>
            `;
            $('#customer-info').html(customerInfo);
            
            // 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>Debit</th>
                            <th>Credit</th>
                            <th>Balance</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 printReport() {
            window.print();
        }
        
        function exportToPDF() {
            var newWindow = window.open('', '_blank');
            newWindow.document.write(`
                <!DOCTYPE html>
                <html>
                <head>
                    <title>Customer 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: #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;
                        }
                        .company-details {
                            font-size: 11px;
                            color: #666;
                            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: #e74c3c;
                            background: #fdf2f2;
                            padding: 8px 12px;
                            border: 2px solid #e74c3c;
                            border-radius: 4px;
                        }
                        .report-period {
                            font-size: 12px;
                            color: #666;
                            margin-bottom: 20px;
                            font-weight: bold;
                            text-align: center;
                        }
                        .customer-info {
                            background: #f8f9fa;
                            padding: 15px;
                            border-radius: 5px;
                            margin-bottom: 20px;
                            border-left: 4px solid #3498db;
                        }
                        .statement-table {
                            width: 100%;
                            border-collapse: collapse;
                            margin: 10px 0;
                            font-size: 11px;
                        }
                        .statement-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;
                        }
                        .statement-table td {
                            padding: 6px 10px;
                            border-bottom: 1px solid #ddd;
                            vertical-align: top;
                        }
                        .statement-table .amount {
                            text-align: right;
                            font-weight: bold;
                        }
                        .positive { color: #27ae60; }
                        .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">
                        <div class="receipt-header">
                            <div class="company-name">${$('.company-name').text() || '<?php echo get_store_name() ? get_store_name() : "Company Name"; ?>'}</div>
                            <div class="company-details">
                                ${$('.company-details').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">Customer Statement</div>
                        <div class="customer-name" style="font-size: 16px; font-weight: bold; color: #e74c3c; margin: 10px 0; text-align: center;">Customer: ${currentReportData ? currentReportData.customer.customer_name : 'N/A'}</div>
                        <div class="report-period">${$('#report-period').text() || 'Period: Not Set'}</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: 'Customer_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 = 'Customer_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>Customer 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: #333;
                            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;
                        }
                        .company-details {
                            font-size: 9px;
                            color: #666;
                            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: #e74c3c;
                            background: #fdf2f2;
                            padding: 8px 12px;
                            border: 2px solid #e74c3c;
                            border-radius: 4px;
                        }
                        .report-period {
                            font-size: 10px;
                            color: #666;
                            margin-bottom: 12px;
                            font-weight: bold;
                            text-align: center;
                        }
                        .statement-table {
                            width: 100%;
                            border-collapse: collapse;
                            margin: 6px 0;
                            font-size: 9px;
                        }
                        .statement-table th {
                            background: #2c3e50;
                            color: white;
                            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 #ddd;
                            vertical-align: top;
                            font-size: 9px;
                        }
                        .statement-table .amount {
                            text-align: right;
                            font-weight: bold;
                        }
                        .positive { color: #27ae60; }
                        .negative { color: #e74c3c; }
                        .separator {
                            border-top: 1px solid #000;
                            margin: 8px 0;
                        }
                        .footer {
                            margin-top: 15px;
                            text-align: center;
                            font-size: 8px;
                            color: #666;
                            border-top: 1px solid #ddd;
                            padding-top: 6px;
                        }
                        @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() || '<?php echo get_store_name() ? get_store_name() : "Company Name"; ?>'}</div>
                            <div class="company-details">
                                ${$('.company-details').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">Customer Statement</div>
                        <div class="customer-name" style="font-size: 16px; font-weight: bold; color: #e74c3c; margin: 10px 0; text-align: center;">Customer: ${currentReportData ? currentReportData.customer.customer_name : 'N/A'}</div>
                        <div class="report-period">${$('#report-period').text() || 'Period: Not Set'}</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>Customer Statement - 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;
                        }
                        .statement-table {
                            width: 100%;
                            border-collapse: collapse;
                            margin: 4px 0;
                            font-size: 8px;
                        }
                        .statement-table th {
                            background: #000;
                            color: white;
                            padding: 3px 4px;
                            text-align: left;
                            font-weight: bold;
                            font-size: 7px;
                            text-transform: uppercase;
                        }
                        .statement-table td {
                            padding: 2px 4px;
                            border-bottom: 1px solid #000;
                            vertical-align: top;
                        }
                        .statement-table .amount {
                            text-align: right;
                            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">CUSTOMER STATEMENT</div>
                        <div class="report-period">${$('#report-period').text() || 'Period: Not Set'}</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() {
            // 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 .statement-table');
            tables.forEach(function(table) {
                // Clone the table and modify for 80MM
                var clonedTable = table.cloneNode(true);
                clonedTable.className = 'statement-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>
</body>
</html>
