<?php
session_start();
include_once('../includes/config.php');
if (!isset($_SESSION['uid'])) {
    header('location:../login.php');
    exit();
}

$currentUserId = $_SESSION['uid'];
$userType = $_SESSION['usertype'];

// Get all customers for dropdown
$customersQuery = "SELECT ID, CustomerID, CustomerCode, CustomerName, Mobile, City, CurrentBalance FROM tblcustomers WHERE IsActive = 1 ORDER BY CustomerName";
$customersResult = mysqli_query($con, $customersQuery);
$availableCustomers = [];
if ($customersResult) {
    while ($customer = mysqli_fetch_assoc($customersResult)) {
        $availableCustomers[] = $customer;
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>Customer Ledger Report | UZRS Inventory</title>
    
    <link href="../vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css">
    <link href="../css/sb-admin-2.min.css" rel="stylesheet">
    <link href="../css/modern-messagebox.css" rel="stylesheet">
    
    <!-- Select2 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    
    <style>
        :root {
            --primary-color: #4e73df;
            --success-color: #1cc88a;
            --danger-color: #e74a3b;
            --warning-color: #f6c23e;
            --info-color: #36b9cc;
            --dark-color: #5a5c69;
        }
        
        body {
            font-size: 14px;
            line-height: 1.4;
        }
        
        .report-container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 15px;
        }
        
        .report-header {
            text-align: center;
            margin-bottom: 15px;
            padding: 10px 0;
            border-bottom: 2px solid var(--primary-color);
        }
        
        .report-header h1 {
            font-size: 18px;
            font-weight: 700;
            color: var(--primary-color);
            margin: 0;
        }
        
        .report-header .company-name {
            font-size: 14px;
            font-weight: 600;
            color: var(--dark-color);
            margin-bottom: 2px;
        }
        
        .report-header .report-meta {
            font-size: 11px;
            color: #858796;
            margin-top: 3px;
        }
        
        .filter-section {
            background: #f8f9fc;
            padding: 12px;
            border-radius: 8px;
            margin-bottom: 15px;
        }
        
        .quick-filters {
            display: flex;
            gap: 6px;
            margin-bottom: 12px;
            flex-wrap: wrap;
        }
        
        .quick-filter-btn {
            padding: 6px 12px;
            background: white;
            color: var(--dark-color);
            border: 1px solid #d1d3e2;
            border-radius: 5px;
            cursor: pointer;
            font-weight: 500;
            font-size: 12px;
            transition: all 0.2s;
        }
        
        .quick-filter-btn:hover {
            background: var(--primary-color);
            color: white;
            border-color: var(--primary-color);
        }
        
        .quick-filter-btn.active {
            background: var(--primary-color);
            color: white;
            border-color: var(--primary-color);
        }
        
        .filter-row {
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
            align-items: end;
            margin-top: 12px;
        }
        
        .custom-dates-row {
            display: none;
            flex-wrap: wrap;
            gap: 8px;
            align-items: end;
            margin-top: 8px;
        }
        
        .custom-dates-row.show {
            display: flex;
        }
        
        .filter-group {
            flex: 1;
            min-width: 120px;
        }
        
        .filter-group label {
            display: block;
            font-size: 11px;
            font-weight: 600;
            margin-bottom: 4px;
            color: var(--dark-color);
        }
        
        .filter-group input,
        .filter-group select {
            width: 100%;
            padding: 7px 8px;
            border: 1px solid #d1d3e2;
            border-radius: 5px;
            font-size: 12px;
        }
        
        .select2-container--default .select2-selection--single {
            height: 34px;
            border: 1px solid #d1d3e2;
            border-radius: 5px;
        }
        
        .select2-container--default .select2-selection--single .select2-selection__rendered {
            line-height: 34px;
            padding-left: 8px;
            font-size: 12px;
        }
        
        .select2-container--default .select2-selection--single .select2-selection__arrow {
            height: 32px;
        }
        
        .select2-container {
            width: 100% !important;
        }
        
        .btn-filter {
            padding: 7px 16px;
            background: var(--primary-color);
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-weight: 600;
            font-size: 12px;
            height: 34px;
        }
        
        .btn-filter:hover {
            background: #2e59d9;
        }
        
        .btn-print {
            padding: 7px 16px;
            background: var(--success-color);
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-weight: 600;
            font-size: 12px;
            height: 34px;
        }
        
        .btn-export {
            padding: 7px 16px;
            background: #f6c23e;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-weight: 600;
            font-size: 12px;
            height: 34px;
        }
        
        .summary-cards {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
            gap: 12px;
            margin-bottom: 20px;
        }
        
        .summary-card {
            background: white;
            border-left: 4px solid var(--primary-color);
            border-radius: 6px;
            padding: 12px 15px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.08);
        }
        
        .summary-card.credit {
            border-left-color: var(--success-color);
        }
        
        .summary-card.debit {
            border-left-color: var(--danger-color);
        }
        
        .summary-card.balance-positive {
            border-left-color: var(--success-color);
        }
        
        .summary-card.balance-negative {
            border-left-color: var(--danger-color);
        }
        
        .summary-card h3 {
            font-size: 11px;
            font-weight: 700;
            text-transform: uppercase;
            color: #858796;
            margin: 0 0 8px 0;
        }
        
        .summary-card .amount {
            font-size: 20px;
            font-weight: 700;
            color: var(--dark-color);
        }
        
        .summary-card.credit .amount {
            color: var(--success-color);
        }
        
        .summary-card.debit .amount {
            color: var(--danger-color);
        }
        
        .section-title {
            font-size: 16px;
            font-weight: 700;
            color: var(--dark-color);
            margin: 20px 0 10px 0;
            padding-bottom: 8px;
            border-bottom: 2px solid #e3e6f0;
        }
        
        .data-table {
            width: 100%;
            border-collapse: collapse;
            background: white;
            box-shadow: 0 2px 4px rgba(0,0,0,0.08);
            margin-bottom: 20px;
            font-size: 12px;
        }
        
        .data-table thead {
            background: linear-gradient(135deg, var(--primary-color), #224abe);
            color: white;
        }
        
        .data-table thead th {
            padding: 10px 8px;
            text-align: left;
            font-weight: 600;
            font-size: 11px;
            text-transform: uppercase;
        }
        
        .data-table tbody td {
            padding: 8px;
            border-bottom: 1px solid #e3e6f0;
        }
        
        .data-table tbody tr:hover {
            background: #f8f9fc;
        }
        
        .data-table tbody tr.opening-balance-row {
            background: #f8f9fc;
            font-weight: 700;
        }
        
        .data-table tfoot td {
            padding: 10px 8px;
            font-weight: 700;
            background: #e3e6f0;
            border-top: 2px solid var(--primary-color);
        }
        
        .data-table tfoot tr:last-child td {
            background: var(--primary-color);
            color: white;
            font-size: 14px;
            padding: 12px 8px;
        }
        
        .text-right {
            text-align: right;
        }
        
        .text-center {
            text-align: center;
        }
        
        .amount-positive {
            color: var(--success-color);
            font-weight: 600;
        }
        
        .amount-negative {
            color: var(--danger-color);
            font-weight: 600;
        }
        
        .badge {
            display: inline-block;
            padding: 4px 8px;
            font-size: 11px;
            font-weight: 600;
            border-radius: 4px;
            text-align: center;
        }
        
        .badge-sale {
            background: #d4edda;
            color: #155724;
        }
        
        .badge-payment {
            background: #f8d7da;
            color: #721c24;
        }
        
        .badge-adjustment {
            background: #fff3cd;
            color: #856404;
        }
        
        .no-data {
            text-align: center;
            padding: 30px;
            color: #858796;
            font-style: italic;
        }
        
        .loading {
            text-align: center;
            padding: 40px;
            font-size: 16px;
            color: var(--primary-color);
        }
        
        @media (max-width: 768px) {
            .report-container {
                padding: 8px;
            }
            
            .summary-cards {
                grid-template-columns: repeat(2, 1fr);
                gap: 8px;
            }
            
            .data-table {
                font-size: 10px;
                display: block;
                overflow-x: auto;
            }
            
            .filter-row {
                flex-direction: column;
            }
        }
    </style>
</head>

<body id="page-top">
    <div id="wrapper">
        <div id="content-wrapper" class="d-flex flex-column" style="margin-left: 0;">
            <div id="content">
                <div class="report-container">
                    <!-- Report Header -->
                    <div class="report-header">
                        <div class="d-flex justify-content-between align-items-center mb-2">
                            <a href="index.php" class="btn btn-sm btn-secondary">
                                <i class="fas fa-arrow-left mr-1"></i> Back to POS
                            </a>
                        </div>
                        <div class="company-name">UZRS INVENTORY SYSTEM</div>
                        <h1>Customer Ledger Report</h1>
                        <div class="report-meta">
                            <span id="reportPeriod">-</span>
                        </div>
                    </div>
                    
                    <!-- Filter Section -->
                    <div class="filter-section">
                        <div class="quick-filters">
                            <button type="button" class="quick-filter-btn" onclick="setQuickFilter('today')">Today</button>
                            <button type="button" class="quick-filter-btn" onclick="setQuickFilter('yesterday')">Yesterday</button>
                            <button type="button" class="quick-filter-btn" onclick="setQuickFilter('thisWeek')">This Week</button>
                            <button type="button" class="quick-filter-btn" onclick="setQuickFilter('lastWeek')">Last Week</button>
                            <button type="button" class="quick-filter-btn active" onclick="setQuickFilter('thisMonth')">This Month</button>
                            <button type="button" class="quick-filter-btn" onclick="setQuickFilter('lastMonth')">Last Month</button>
                            <button type="button" class="quick-filter-btn" onclick="setQuickFilter('custom')">Custom Range</button>
                        </div>
                        
                        <div id="customDatesRow" class="custom-dates-row">
                            <div class="filter-group">
                                <label>Start Date</label>
                                <input type="date" id="startDate" class="form-control form-control-sm">
                            </div>
                            <div class="filter-group">
                                <label>End Date</label>
                                <input type="date" id="endDate" class="form-control form-control-sm">
                            </div>
                        </div>
                        
                        <div class="filter-row">
                            <div class="filter-group" style="flex: 2;">
                                <label>Customer</label>
                                <select id="customerFilter" class="form-control form-control-sm">
                                    <option value="">All Customers</option>
                                    <?php foreach ($availableCustomers as $customer): ?>
                                        <option value="<?php echo $customer['ID']; ?>" 
                                                data-name="<?php echo htmlspecialchars($customer['CustomerName']); ?>"
                                                data-code="<?php echo htmlspecialchars($customer['CustomerCode']); ?>"
                                                data-phone="<?php echo htmlspecialchars($customer['Mobile']); ?>">
                                            <?php echo htmlspecialchars($customer['CustomerCode'] . ' - ' . $customer['CustomerName'] . ' (' . $customer['Mobile'] . ')'); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <button type="button" class="btn-filter" onclick="loadReport()">
                                <i class="fas fa-search"></i> Load Report
                            </button>
                            <button type="button" class="btn-print" onclick="openPrintView()">
                                <i class="fas fa-print"></i> Print
                            </button>
                            <button type="button" class="btn-export" onclick="exportToExcel()">
                                <i class="fas fa-file-excel"></i> Export
                            </button>
                        </div>
                    </div>
                    
                    <!-- Loading State -->
                    <div id="loadingState" class="loading">
                        <i class="fas fa-spinner fa-spin"></i> Loading report data...
                    </div>
                    
                    <!-- Report Content -->
                    <div id="reportContent" style="display: none;">
                        <!-- Summary Cards -->
                        <div class="summary-cards">
                            <div class="summary-card" id="openingCard">
                                <h3>Opening Balance</h3>
                                <div class="amount" id="openingBalance">₹0.00</div>
                            </div>
                            <div class="summary-card debit">
                                <h3>Total Sales</h3>
                                <div class="amount" id="totalSales">₹0.00</div>
                            </div>
                            <div class="summary-card credit">
                                <h3>Total Payments</h3>
                                <div class="amount" id="totalPayments">₹0.00</div>
                            </div>
                            <div class="summary-card" id="closingCard">
                                <h3>Outstanding Balance</h3>
                                <div class="amount" id="closingBalance">₹0.00</div>
                            </div>
                        </div>
                        
                        <!-- Transaction Ledger -->
                        <div class="section-title">
                            Transaction Ledger <span id="ledgerCount" style="font-size: 12px; font-weight: 400; color: #858796;">(0 transactions)</span>
                        </div>
                        
                        <table class="data-table">
                            <thead>
                                <tr>
                                    <th width="10%">Date</th>
                                    <th width="15%">Invoice No</th>
                                    <th width="18%">Customer</th>
                                    <th width="10%">Type</th>
                                    <th width="20%">Notes</th>
                                    <th width="12%" class="text-right">Debit (₹)</th>
                                    <th width="12%" class="text-right">Credit (₹)</th>
                                    <th width="3%"></th>
                                </tr>
                            </thead>
                            <tbody id="ledgerTableBody">
                                <tr><td colspan="8" class="no-data">Select filters and click "Load Report"</td></tr>
                            </tbody>
                            <tfoot>
                                <tr>
                                    <td colspan="5" class="text-right">PERIOD TOTALS:</td>
                                    <td class="text-right amount-negative" id="totalDebitFooter">₹0.00</td>
                                    <td class="text-right amount-positive" id="totalCreditFooter">₹0.00</td>
                                    <td></td>
                                </tr>
                                <tr>
                                    <td colspan="6" class="text-right">OUTSTANDING BALANCE:</td>
                                    <td class="text-right" id="closingBalanceFooter">₹0.00</td>
                                    <td></td>
                                </tr>
                            </tfoot>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <script src="../vendor/jquery/jquery.min.js"></script>
    <script src="../vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script src="../js/sb-admin-2.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    
    <script>
        function formatCurrency(amount) {
            return '₹' + parseFloat(amount).toLocaleString('en-IN', {
                minimumFractionDigits: 2,
                maximumFractionDigits: 2
            });
        }
        
        function formatDate(dateStr) {
            if (!dateStr) return '-';
            const date = new Date(dateStr);
            const day = String(date.getDate()).padStart(2, '0');
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const year = date.getFullYear();
            return `${day}/${month}/${year}`;
        }
        
        function formatDateForInput(date) {
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            return `${year}-${month}-${day}`;
        }
        
        function setQuickFilter(filter) {
            const today = new Date();
            let startDate, endDate;
            
            document.querySelectorAll('.quick-filter-btn').forEach(btn => {
                btn.classList.remove('active');
            });
            
            event.target.classList.add('active');
            
            const customDatesRow = document.getElementById('customDatesRow');
            
            if (filter === 'custom') {
                customDatesRow.classList.add('show');
                return;
            } else {
                customDatesRow.classList.remove('show');
            }
            
            switch(filter) {
                case 'today':
                    startDate = endDate = new Date(today);
                    break;
                    
                case 'yesterday':
                    const yesterday = new Date(today);
                    yesterday.setDate(yesterday.getDate() - 1);
                    startDate = endDate = yesterday;
                    break;
                    
                case 'thisWeek':
                    const firstDayOfWeek = new Date(today);
                    const dayOfWeek = today.getDay();
                    const diff = dayOfWeek === 0 ? -6 : 1 - dayOfWeek;
                    firstDayOfWeek.setDate(today.getDate() + diff);
                    startDate = firstDayOfWeek;
                    endDate = new Date(today);
                    break;
                    
                case 'lastWeek':
                    const lastWeekEnd = new Date(today);
                    const currentDay = today.getDay();
                    const daysToSubtract = currentDay === 0 ? 7 : currentDay;
                    lastWeekEnd.setDate(today.getDate() - daysToSubtract);
                    const lastWeekStart = new Date(lastWeekEnd);
                    lastWeekStart.setDate(lastWeekEnd.getDate() - 6);
                    startDate = lastWeekStart;
                    endDate = lastWeekEnd;
                    break;
                    
                case 'thisMonth':
                    startDate = new Date(today.getFullYear(), today.getMonth(), 1);
                    endDate = new Date(today);
                    break;
                    
                case 'lastMonth':
                    startDate = new Date(today.getFullYear(), today.getMonth() - 1, 1);
                    endDate = new Date(today.getFullYear(), today.getMonth(), 0);
                    break;
                    
                default:
                    startDate = new Date(today.getFullYear(), today.getMonth(), 1);
                    endDate = new Date(today);
            }
            
            document.getElementById('startDate').value = formatDateForInput(startDate);
            document.getElementById('endDate').value = formatDateForInput(endDate);
            
            loadReport();
        }
        
        function loadReport() {
            const startDate = document.getElementById('startDate').value;
            const endDate = document.getElementById('endDate').value;
            const customerId = document.getElementById('customerFilter').value;
            
            if (!startDate || !endDate) {
                alert('Please select both start and end dates');
                return;
            }
            
            document.getElementById('loadingState').style.display = 'block';
            document.getElementById('reportContent').style.display = 'none';
            
            let apiUrl = `api/get-customer-ledger.php?startDate=${startDate}&endDate=${endDate}`;
            if (customerId) {
                apiUrl += `&customerId=${customerId}`;
            }
            
            fetch(apiUrl)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        renderReport(data);
                    } else {
                        alert('Error: ' + data.message);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('Error loading report data');
                })
                .finally(() => {
                    document.getElementById('loadingState').style.display = 'none';
                    document.getElementById('reportContent').style.display = 'block';
                });
        }
        
        function renderReport(data) {
            const { summary, transactions, startDate, endDate, customerInfo } = data;
            
            let periodText = `${formatDate(startDate)} to ${formatDate(endDate)}`;
            if (customerInfo) {
                periodText += ` - ${customerInfo.CustomerName}`;
            } else {
                periodText += ' - All Customers';
            }
            document.getElementById('reportPeriod').textContent = periodText;
            
            document.getElementById('openingBalance').textContent = formatCurrency(summary.openingBalance);
            document.getElementById('openingCard').className = `summary-card ${summary.openingBalance >= 0 ? 'balance-negative' : 'balance-positive'}`;
            
            document.getElementById('totalSales').textContent = formatCurrency(summary.totalSales);
            document.getElementById('totalPayments').textContent = formatCurrency(summary.totalPayments);
            
            document.getElementById('closingBalance').textContent = formatCurrency(summary.closingBalance);
            document.getElementById('closingBalanceFooter').textContent = formatCurrency(summary.closingBalance);
            document.getElementById('closingCard').className = `summary-card ${summary.closingBalance >= 0 ? 'balance-negative' : 'balance-positive'}`;
            
            const closingClass = summary.closingBalance >= 0 ? 'amount-negative' : 'amount-positive';
            document.getElementById('closingBalanceFooter').className = `text-right ${closingClass}`;
            
            document.getElementById('totalDebitFooter').textContent = formatCurrency(summary.totalSales);
            document.getElementById('totalCreditFooter').textContent = formatCurrency(summary.totalPayments);
            
            renderLedger(transactions, summary);
        }
        
        function renderLedger(transactions, summary) {
            const tbody = document.getElementById('ledgerTableBody');
            
            document.getElementById('ledgerCount').textContent = `(${transactions.length} transactions)`;
            
            if (transactions.length === 0) {
                tbody.innerHTML = '<tr><td colspan="8" class="no-data">No transactions found for the selected period.</td></tr>';
                return;
            }
            
            let rows = '';
            
            rows += `
                <tr class="opening-balance-row">
                    <td colspan="5">OPENING BALANCE</td>
                    <td class="text-right">${summary.openingBalance >= 0 ? formatCurrency(summary.openingBalance) : '-'}</td>
                    <td class="text-right">${summary.openingBalance < 0 ? formatCurrency(Math.abs(summary.openingBalance)) : '-'}</td>
                    <td></td>
                </tr>
            `;
            
            transactions.forEach(txn => {
                const typeClass = txn.TransactionType === 'Sale' ? 'badge-sale' : 
                                 txn.TransactionType === 'Payment' ? 'badge-payment' : 'badge-adjustment';
                
                rows += `
                    <tr>
                        <td>${formatDate(txn.TransactionDate)}</td>
                        <td>${txn.InvoiceNumber || '-'}</td>
                        <td>${txn.CustomerName || '-'}</td>
                        <td><span class="badge ${typeClass}">${txn.TransactionType}</span></td>
                        <td title="${txn.Notes || '-'}">${(txn.Notes || '-').substring(0, 40)}</td>
                        <td class="text-right ${txn.DebitAmount ? 'amount-negative' : ''}">${txn.DebitAmount ? formatCurrency(txn.DebitAmount) : '-'}</td>
                        <td class="text-right ${txn.CreditAmount ? 'amount-positive' : ''}">${txn.CreditAmount ? formatCurrency(txn.CreditAmount) : '-'}</td>
                        <td></td>
                    </tr>
                `;
            });
            
            tbody.innerHTML = rows;
        }
        
        document.addEventListener('DOMContentLoaded', function() {
            $('#customerFilter').select2({
                placeholder: 'Type to search customer...',
                allowClear: true,
                width: '100%'
            });
            
            const urlParams = new URLSearchParams(window.location.search);
            const customerId = urlParams.get('customerId');
            const startDate = urlParams.get('startDate');
            const endDate = urlParams.get('endDate');
            
            if (customerId) {
                $('#customerFilter').val(customerId).trigger('change');
            }
            
            if (startDate) {
                document.getElementById('startDate').value = startDate;
            }
            if (endDate) {
                document.getElementById('endDate').value = endDate;
            }
            
            // Set default dates to this month
            const today = new Date();
            document.getElementById('startDate').value = formatDateForInput(new Date(today.getFullYear(), today.getMonth(), 1));
            document.getElementById('endDate').value = formatDateForInput(today);
            
            loadReport();
        });
        
        function exportToExcel() {
            const startDate = document.getElementById('startDate').value;
            const endDate = document.getElementById('endDate').value;
            
            if (!startDate || !endDate) {
                alert('Please generate a report first');
                return;
            }
            
            const table = document.getElementById('ledgerTableBody').parentElement;
            
            let html = '<html xmlns:x="urn:schemas-microsoft-com:office:excel">';
            html += '<head><meta charset="UTF-8"><style>';
            html += 'table { border-collapse: collapse; width: 100%; }';
            html += 'th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }';
            html += 'th { background-color: #4e73df; color: white; font-weight: bold; }';
            html += '</style></head><body>';
            html += '<h2>UZRS Inventory - Customer Ledger Report</h2>';
            html += '<p>Period: ' + formatDate(startDate) + ' to ' + formatDate(endDate) + '</p>';
            html += table.outerHTML;
            html += '</body></html>';
            
            const blob = new Blob([html], { type: 'application/vnd.ms-excel' });
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = 'Customer_Ledger_Report_' + startDate + '_to_' + endDate + '.xls';
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            window.URL.revokeObjectURL(url);
        }

        function openPrintView() {
            const startDate = document.getElementById('startDate').value;
            const endDate = document.getElementById('endDate').value;
            const customerId = document.getElementById('customerFilter').value;

            if (!startDate || !endDate) {
                alert('Please generate a report first');
                return;
            }

            const params = new URLSearchParams({ startDate, endDate });
            if (customerId) {
                params.append('customerId', customerId);
            }

            window.open('print-customer-ledger.php?' + params.toString(), '_blank');
        }
    </script>
</body>
</html>
