<?php
session_start();
if(!isset($_SESSION['username'])) {
    header("Location: ../login.php");
    exit();
}

include('../includes/db.php');

$from_date = isset($_GET['from_date']) ? $_GET['from_date'] : '';
$to_date = isset($_GET['to_date']) ? $_GET['to_date'] : '';
$search = isset($_GET['search']) ? mysqli_real_escape_string($conn, $_GET['search']) : '';

// Build query with date filters
$where_conditions = [];
if(!empty($from_date)) {
    $where_conditions[] = "DATE(date_time) >= '$from_date'";
}
if(!empty($to_date)) {
    $where_conditions[] = "DATE(date_time) <= '$to_date'";
}
if(!empty($search)) {
    $where_conditions[] = "(name LIKE '%$search%' OR phone LIKE '%$search%' OR vehicle_no LIKE '%$search%')";
}

$where_clause = !empty($where_conditions) ? "WHERE " . implode(" AND ", $where_conditions) : "";

// Get all customers with their balance
$sql = "SELECT id, name, phone, vehicle_no, balance, advance_balance, date_time 
        FROM customers 
        $where_clause 
        ORDER BY name ASC";
$result = mysqli_query($conn, $sql);

// Calculate totals
$total_balance = 0;
$total_advance_balance = 0;
$total_net_receivable = 0;
$customers_data = [];

while($row = mysqli_fetch_assoc($result)) {
    $total_balance += $row['balance'];
    $total_advance_balance += $row['advance_balance'];
    $net_receivable = $row['balance'] - $row['advance_balance'];
    $total_net_receivable += $net_receivable;
    
    // Calculate total credit sales for this customer
    $credit_sales_sql = "SELECT SUM(amount) as total_credit FROM credit_sales WHERE customer_id = {$row['id']}";
    $credit_sales_result = mysqli_query($conn, $credit_sales_sql);
    $credit_data = mysqli_fetch_assoc($credit_sales_result);
    $row['total_credit_sales'] = $credit_data['total_credit'] ?? 0;
    
    // Calculate total payments received
    $payments_sql = "SELECT SUM(amount) as total_payments FROM customer_payments WHERE customer_id = {$row['id']} AND payment_type = 'payment'";
    $payments_result = mysqli_query($conn, $payments_sql);
    $payments_data = mysqli_fetch_assoc($payments_result);
    $row['total_payments'] = $payments_data['total_payments'] ?? 0;
    
    // Calculate total advance deposits
    $advance_deposits_sql = "SELECT SUM(amount) as total_advance FROM customer_payments WHERE customer_id = {$row['id']} AND payment_type = 'advance'";
    $advance_deposits_result = mysqli_query($conn, $advance_deposits_sql);
    $advance_data = mysqli_fetch_assoc($advance_deposits_result);
    $row['total_advance_deposits'] = $advance_data['total_advance'] ?? 0;
    
    $customers_data[] = $row;
}
mysqli_data_seek($result, 0);
?>

<?php include('../includes/log.php'); ?>
<?php include('../includes/sd.php'); ?>

<div class="customer-closing-container">
    <!-- Page Header -->
    <div class="page-header">
        <div class="header-left">
            <h2><i class="fas fa-users"></i> Customers Closing Report</h2>
            <p>Complete summary of all customer outstanding balances</p>
        </div>
        <div class="header-right">
            <div class="stats-badge">
                <i class="fas fa-chart-line"></i>
                <span>Closing Report</span>
            </div>
        </div>
    </div>

    <!-- Filter Card (NOT included in PDF capture) -->
    <div class="filter-card">
        <div class="filter-header">
            <i class="fas fa-filter"></i> Filter Report
        </div>
        <div class="filter-body">
            <form method="GET" action="" class="filter-form" id="filterForm">
                <div class="filter-row">
                    <div class="filter-group">
                        <label><i class="fas fa-calendar-alt"></i> From Date</label>
                        <input type="date" name="from_date" class="form-control-modern" value="<?php echo $from_date; ?>">
                    </div>
                    <div class="filter-group">
                        <label><i class="fas fa-calendar-alt"></i> To Date</label>
                        <input type="date" name="to_date" class="form-control-modern" value="<?php echo $to_date; ?>">
                    </div>
                    <div class="filter-group">
                        <label><i class="fas fa-search"></i> Search Customer</label>
                        <input type="text" name="search" class="form-control-modern" placeholder="Name, phone, vehicle..." value="<?php echo htmlspecialchars($search); ?>">
                    </div>
                    <div class="filter-actions">
                        <button type="submit" class="btn-search">
                            <i class="fas fa-search"></i> Filter
                        </button>
                        <a href="customer_closing_report.php" class="btn-reset">
                            <i class="fas fa-sync-alt"></i> Reset
                        </a>
                        <button type="button" onclick="downloadPDF()" class="btn-pdf">
                            <i class="fas fa-file-pdf"></i> Download PDF
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <!-- Report Content for PDF capture -->
    <div id="report-content-customer">
        <!-- Summary Cards -->
        <div class="summary-cards">
            <div class="summary-card">
                <div class="summary-icon total-customers"><i class="fas fa-users"></i></div>
                <div class="summary-content">
                    <h4><?php echo count($customers_data); ?></h4>
                    <p>Total Customers</p>
                    <small>Registered Customers</small>
                </div>
            </div>
            <div class="summary-card">
                <div class="summary-icon total-receivable"><i class="fas fa-rupee-sign"></i></div>
                <div class="summary-content">
                    <h4>Rs <?php echo number_format($total_balance, 2); ?></h4>
                    <p>Total Receivable</p>
                    <small>Customer Credit Balance</small>
                </div>
            </div>
            <div class="summary-card">
                <div class="summary-icon total-advance"><i class="fas fa-hand-holding-usd"></i></div>
                <div class="summary-content">
                    <h4>Rs <?php echo number_format($total_advance_balance, 2); ?></h4>
                    <p>Total Advance</p>
                    <small>Customer Advance Balance</small>
                </div>
            </div>
            <div class="summary-card">
                <div class="summary-icon net-receivable"><i class="fas fa-balance-scale"></i></div>
                <div class="summary-content">
                    <h4 class="<?php echo $total_net_receivable > 0 ? 'text-danger' : ($total_net_receivable < 0 ? 'text-success' : ''); ?>">
                        Rs <?php echo number_format(abs($total_net_receivable), 2); ?>
                        <?php echo $total_net_receivable > 0 ? 'Dr' : ($total_net_receivable < 0 ? 'Cr' : ''); ?>
                    </h4>
                    <p>Net Receivable</p>
                    <small>Receivable - Advance</small>
                </div>
            </div>
        </div>

        <!-- Customers Table -->
        <div class="table-card">
            <div class="table-card-header">
                <div class="header-info"><i class="fas fa-list"></i><h4>Customers Closing Balance</h4></div>
                <div class="table-stats">Showing <strong><?php echo count($customers_data); ?></strong> customers</div>
            </div>
            <div class="table-card-body">
                <div class="table-responsive">
                    <table class="modern-table" id="customersTable">
                        <thead>
                            <tr>
                                <th>#</th>
                                <th>Customer Name</th>
                                <th>Phone</th>
                                <th>Vehicle No</th>
                                <th>Credit Sales</th>
                                <th>Payments</th>
                                <th>Advance Deposits</th>
                                <th>Receivable</th>
                                <th>Advance</th>
                                <th>Net Balance</th>
                                <th>Status</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if(count($customers_data) > 0): ?>
                                <?php 
                                $sr_no = 1;
                                foreach($customers_data as $customer): 
                                    $net_balance = $customer['balance'] - $customer['advance_balance'];
                                    $balance_status = $net_balance > 0 ? 'due' : ($net_balance < 0 ? 'advance' : 'clear');
                                ?>
                                    <tr>
                                        <td data-label="#"><?php echo $sr_no++; ?></td>
                                        <td data-label="Customer Name">
                                            <div class="customer-cell">
                                                <div class="customer-avatar"><i class="fas fa-user-circle"></i></div>
                                                <div class="customer-info">
                                                    <strong><?php echo htmlspecialchars($customer['name']); ?></strong>
                                                </div>
                                            </div>
                                        </div>
                                        <td data-label="Phone"><?php echo htmlspecialchars($customer['phone']); ?></div>
                                        <td data-label="Vehicle No"><?php echo htmlspecialchars($customer['vehicle_no']); ?></div>
                                        <td data-label="Credit Sales" class="credit-sales-amount">Rs <?php echo number_format($customer['total_credit_sales'], 2); ?></div>
                                        <td data-label="Payments" class="payments-amount">Rs <?php echo number_format($customer['total_payments'], 2); ?></div>
                                        <td data-label="Advance Deposits" class="advance-deposits-amount">Rs <?php echo number_format($customer['total_advance_deposits'], 2); ?></div>
                                        <td data-label="Receivable" class="receivable-amount">Rs <?php echo number_format($customer['balance'], 2); ?></div>
                                        <td data-label="Advance" class="advance-amount">Rs <?php echo number_format($customer['advance_balance'], 2); ?></div>
                                        <td data-label="Net Balance">
                                            <div class="balance-cell <?php echo $balance_status; ?>">
                                                Rs <?php echo number_format(abs($net_balance), 2); ?>
                                                <?php if($net_balance > 0): ?>
                                                    <span class="dr-cr">Dr</span>
                                                <?php elseif($net_balance < 0): ?>
                                                    <span class="dr-cr">Cr</span>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                        <td data-label="Status">
                                            <span class="status-badge <?php echo $balance_status; ?>">
                                                <?php if($balance_status == 'due'): ?>
                                                    <i class="fas fa-hourglass-half"></i> Due
                                                <?php elseif($balance_status == 'advance'): ?>
                                                    <i class="fas fa-money-bill-wave"></i> Advance
                                                <?php else: ?>
                                                    <i class="fas fa-check-circle"></i> Clear
                                                <?php endif; ?>
                                            </span>
                                        </div>
                                    </tr>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="11" class="empty-state">
                                        <i class="fas fa-users"></i>
                                        <p>No customers found</p>
                                        <small>Try changing your search criteria</small>
                                    </div>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                        <tfoot>
                            <tr class="totals-row">
                                <td colspan="4"><strong>GRAND TOTALS</strong></div>
                                <td class="credit-sales-amount"><strong>—</strong></div>
                                <td class="payments-amount"><strong>—</strong></div>
                                <td class="advance-deposits-amount"><strong>—</strong></div>
                                <td class="receivable-amount"><strong>Rs <?php echo number_format($total_balance, 2); ?></strong></div>
                                <td class="advance-amount"><strong>Rs <?php echo number_format($total_advance_balance, 2); ?></strong></div>
                                <td class="net-balance-total"><strong>Rs <?php echo number_format($total_net_receivable, 2); ?></strong></div>
                                <td>—</div>
                            </tr>
                        </tfoot>
                    </table>
                </div>
            </div>
        </div>
    </div><!-- end #report-content-customer -->
</div>

<style>
/* Customer Closing Report Styles - Page Specific Only */
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700;800&display=swap');

* {
    font-family: 'Poppins', sans-serif;
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body {
    background: #f5f7fb;
    overflow-x: hidden;
}

h1, h2, h3, h4, h5, h6,
.page-header h2,
.header-info h4,
.summary-card p {
    font-family: 'Poppins', sans-serif;
    font-weight: 600;
}

/* Main Content */
.main-content {
    margin-left: 280px;
    padding: 15px 20px;
    transition: all 0.3s;
    background: #f5f7fb;
}

.customer-closing-container {
    max-width: 100%;
    width: 100%;
    margin: 0;
    padding: 0;
}

/* Page Header */
.page-header {
    background: linear-gradient(135deg, #A04657 0%, #6b2a36 100%);
    border-radius: 16px;
    padding: 16px 24px;
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    color: #fff;
    width: 100%;
}

.page-header h2 {
    margin: 0 0 4px 0;
    font-size: 22px;
}

.page-header p {
    margin: 0;
    font-size: 12px;
    opacity: 0.9;
}

.stats-badge {
    background: rgba(255,255,255,0.2);
    padding: 6px 16px;
    border-radius: 40px;
    font-size: 12px;
}

/* Summary Cards */
.summary-cards {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 16px;
    margin-bottom: 20px;
    width: 100%;
}

.summary-card {
    background: #fff;
    border-radius: 16px;
    padding: 16px;
    display: flex;
    align-items: center;
    gap: 14px;
    border: 1px solid #f0f0f0;
    transition: all 0.3s;
}

.summary-card:hover {
    transform: translateY(-3px);
    box-shadow: 0 8px 18px rgba(160,70,87,0.1);
}

.summary-icon {
    width: 48px;
    height: 48px;
    border-radius: 14px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.summary-icon i {
    font-size: 22px;
}

.total-customers { background: rgba(160,70,87,0.1); }
.total-customers i { color: #A04657; }
.total-receivable { background: rgba(220,53,69,0.1); }
.total-receivable i { color: #dc3545; }
.total-advance { background: rgba(23,162,184,0.1); }
.total-advance i { color: #17a2b8; }
.net-receivable { background: rgba(40,167,69,0.1); }
.net-receivable i { color: #28a745; }

.summary-content h4 {
    margin: 0;
    font-size: 20px;
    font-weight: 800;
}

.summary-content p {
    margin: 3px 0 0;
    font-size: 11px;
    color: #666;
}

.summary-content small {
    font-size: 9px;
    color: #999;
    display: block;
    margin-top: 2px;
}

.text-danger { color: #dc3545; }
.text-success { color: #28a745; }

/* Filter Card */
.filter-card {
    background: #fff;
    border-radius: 16px;
    margin-bottom: 20px;
    overflow: hidden;
    border: 1px solid #f0f0f0;
    width: 100%;
}

.filter-header {
    background: linear-gradient(135deg, #A04657, #6b2a36);
    padding: 10px 20px;
    color: #fff;
    font-weight: 600;
    font-size: 13px;
}

.filter-body {
    padding: 16px;
}

.filter-row {
    display: flex;
    flex-wrap: wrap;
    gap: 12px;
    align-items: flex-end;
}

.filter-group {
    flex: 1;
    min-width: 160px;
}

.filter-group label {
    display: block;
    font-size: 10px;
    font-weight: 600;
    text-transform: uppercase;
    color: #666;
    margin-bottom: 4px;
}

.form-control-modern {
    width: 100%;
    padding: 8px 12px;
    border: 1.5px solid #e8e8e8;
    border-radius: 10px;
    font-size: 12px;
    transition: all 0.3s;
    background: #fafafa;
}

.form-control-modern:focus {
    border-color: #A04657;
    outline: none;
}

.filter-actions {
    display: flex;
    gap: 8px;
}

.btn-search, .btn-reset, .btn-pdf {
    padding: 8px 16px;
    border-radius: 10px;
    font-weight: 600;
    font-size: 12px;
    cursor: pointer;
    border: none;
    display: inline-flex;
    align-items: center;
    gap: 6px;
    transition: all 0.3s;
}

.btn-search {
    background: linear-gradient(135deg, #A04657, #6b2a36);
    color: #fff;
}

.btn-search:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(160,70,87,0.3);
}

.btn-reset {
    background: #f0f0f0;
    color: #555;
    text-decoration: none;
}

.btn-reset:hover {
    background: #e0e0e0;
}

.btn-pdf {
    background: #dc3545;
    color: #fff;
}

.btn-pdf:hover {
    background: #b71c1c;
}

/* Table Card */
.table-card {
    background: #fff;
    border-radius: 16px;
    overflow: hidden;
    border: 1px solid #f0f0f0;
    margin-bottom: 20px;
    width: 100%;
}

.table-card-header {
    padding: 12px 20px;
    border-bottom: 1px solid #f0f0f0;
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    gap: 12px;
}

.header-info {
    display: flex;
    align-items: center;
    gap: 8px;
}

.header-info i {
    font-size: 18px;
    color: #A04657;
}

.header-info h4 {
    margin: 0;
    font-size: 16px;
}

.table-stats {
    font-size: 12px;
    color: #666;
}

.table-responsive {
    overflow-x: auto;
    width: 100%;
}

.modern-table {
    width: 100%;
    border-collapse: collapse;
    font-size: 12px;
    min-width: 1000px;
}

.modern-table th {
    padding: 10px 10px;
    background: #f8f9fc;
    font-weight: 700;
    color: #445566;
    font-size: 11px;
    text-transform: uppercase;
    border-bottom: 2px solid #e8e8e8;
}

.modern-table td {
    padding: 10px 10px;
    border-bottom: 1px solid #f0f0f0;
    vertical-align: middle;
    font-size: 12px;
}

.modern-table tbody tr:hover {
    background: #fef8f9;
}

.customer-cell {
    display: flex;
    align-items: center;
    gap: 8px;
}

.customer-avatar {
    width: 30px;
    height: 30px;
    background: rgba(160,70,87,0.1);
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.customer-avatar i {
    font-size: 14px;
    color: #A04657;
}

.customer-info strong {
    font-size: 13px;
}

.credit-sales-amount { color: #dc3545; font-weight: 600; }
.payments-amount { color: #28a745; font-weight: 600; }
.advance-deposits-amount { color: #17a2b8; font-weight: 600; }
.receivable-amount { font-weight: 600; color: #ff9800; }
.advance-amount { font-weight: 600; color: #17a2b8; }

.balance-cell.due { color: #dc3545; font-weight: 700; }
.balance-cell.advance { color: #17a2b8; font-weight: 700; }
.balance-cell.clear { color: #28a745; font-weight: 700; }

.dr-cr {
    font-size: 9px;
    font-weight: 600;
    margin-left: 2px;
}

.status-badge {
    display: inline-flex;
    align-items: center;
    gap: 5px;
    padding: 4px 10px;
    border-radius: 20px;
    font-size: 10px;
    font-weight: 600;
}

.status-badge.due {
    background: #ffebee;
    color: #c62828;
}
.status-badge.advance {
    background: #e3f2fd;
    color: #1565c0;
}
.status-badge.clear {
    background: #e8f5e9;
    color: #2e7d32;
}

.totals-row {
    background: #e9ecef;
    font-weight: 700;
}

.net-balance-total {
    color: #A04657;
    font-size: 13px;
}

.empty-state {
    text-align: center;
    padding: 40px !important;
}

.empty-state i {
    font-size: 48px;
    color: #A04657;
    opacity: 0.3;
    margin-bottom: 12px;
    display: block;
}

.empty-state p {
    font-size: 13px;
    color: #666;
}

.empty-state small {
    font-size: 11px;
    color: #999;
}

/* Responsive */
@media (max-width: 1200px) {
    .summary-cards {
        grid-template-columns: repeat(2, 1fr);
    }
}

@media (max-width: 992px) {
    .main-content {
        margin-left: 0;
        padding: 12px 15px;
    }
}

@media (max-width: 768px) {
    .main-content {
        padding: 10px;
    }
    .page-header {
        flex-direction: column;
        text-align: center;
        gap: 12px;
        padding: 14px 18px;
    }
    .page-header h2 {
        font-size: 18px;
    }
    .summary-cards {
        grid-template-columns: 1fr;
        gap: 12px;
    }
    .filter-row {
        flex-direction: column;
        gap: 10px;
    }
    .filter-actions {
        flex-direction: row;
        flex-wrap: wrap;
    }
    .modern-table th {
        display: none;
    }
    .modern-table td {
        display: block;
        text-align: right;
        padding-left: 45%;
        position: relative;
        border-bottom: none;
    }
    .modern-table td::before {
        content: attr(data-label);
        position: absolute;
        left: 10px;
        width: 45%;
        text-align: left;
        font-weight: 700;
        font-size: 10px;
        color: #555;
    }
    .modern-table tr {
        display: block;
        margin-bottom: 10px;
        border: 1px solid #e8e8e8;
        border-radius: 12px;
        overflow: hidden;
    }
    .modern-table td:last-child {
        border-bottom: none;
    }
    .summary-card {
        padding: 12px;
    }
    .summary-icon {
        width: 42px;
        height: 42px;
    }
    .summary-icon i {
        font-size: 20px;
    }
    .summary-content h4 {
        font-size: 18px;
    }
}

/* Print Styles */
@media print {
    .sidebar, .top-header, .footer, .filter-card, .btn-pdf, .btn-search, .btn-reset {
        display: none !important;
    }
    .main-content {
        margin: 0;
        padding: 0;
        width: 100%;
    }
    .modern-table {
        border: 1px solid #ddd;
    }
    .modern-table th {
        background: #f0f0f0 !important;
        -webkit-print-color-adjust: exact;
        print-color-adjust: exact;
    }
}

/* Scrollbar */
::-webkit-scrollbar {
    width: 6px;
    height: 6px;
}

::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 10px;
}

::-webkit-scrollbar-thumb {
    background: #A04657;
    border-radius: 10px;
}

::-webkit-scrollbar-thumb:hover {
    background: #6b2a36;
}
</style>

<!-- PDF Generation Libraries -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>

<script>
const pdfDateFrom = '<?php echo $from_date ? date('d-m-Y', strtotime($from_date)) : "All Dates"; ?>';
const pdfDateTo = '<?php echo $to_date ? date('d-m-Y', strtotime($to_date)) : "All Dates"; ?>';
const reportTitle = 'Customers Closing Report';

async function downloadPDF() {
    const element = document.getElementById('report-content-customer');
    if (!element) {
        alert('No report content to download.');
        return;
    }

    const pdfBtn = document.querySelector('.btn-pdf');
    const originalHTML = pdfBtn.innerHTML;
    pdfBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Generating PDF...';
    pdfBtn.disabled = true;

    try {
        const canvas = await html2canvas(element, {
            scale: 2,
            useCORS: true,
            logging: false,
            allowTaint: true,
            backgroundColor: '#ffffff'
        });

        const { jsPDF } = window.jspdf;
        const pdf = new jsPDF('p', 'mm', 'a4');

        const pageWidthMM = 210;
        const pageHeightMM = 297;
        const marginMM = 10;
        const contentWidthMM = pageWidthMM - marginMM * 2;
        const headerHeightMM = 62;
        const bottomMarginMM = 10;
        const availHeightMM = pageHeightMM - headerHeightMM - bottomMarginMM;
        const pxPerMM = canvas.width / contentWidthMM;
        const totalImgHeightMM = canvas.height / pxPerMM;

        function addHeader() {
            pdf.setFont('helvetica', 'bold');
            pdf.setFontSize(18);
            pdf.setTextColor(160, 70, 87);
            pdf.text('ALFATEH PETROLEUM SERVICE', pageWidthMM / 2, 20, { align: 'center' });

            pdf.setFont('helvetica', 'normal');
            pdf.setFontSize(11);
            pdf.setTextColor(100, 100, 100);
            pdf.text('Complete Fuel Station Management Solution', pageWidthMM / 2, 27, { align: 'center' });

            pdf.setFontSize(10);
            pdf.setTextColor(80, 80, 80);
            pdf.text('Shaikh bhirkyo road Tando Muhammad khan', pageWidthMM / 2, 34, { align: 'center' });

            pdf.setDrawColor(160, 70, 87);
            pdf.setLineWidth(0.5);
            pdf.line(marginMM, 40, pageWidthMM - marginMM, 40);

            pdf.setFont('helvetica', 'bold');
            pdf.setFontSize(16);
            pdf.setTextColor(0, 0, 0);
            pdf.text(reportTitle, pageWidthMM / 2, 48, { align: 'center' });

            const periodText = (pdfDateFrom === 'All Dates' && pdfDateTo === 'All Dates')
                ? 'Period: All Dates'
                : `Period: ${pdfDateFrom} To ${pdfDateTo}`;
            pdf.setFont('helvetica', 'normal');
            pdf.setFontSize(10);
            pdf.setTextColor(80, 80, 80);
            pdf.text(periodText, pageWidthMM / 2, 55, { align: 'center' });

            pdf.setDrawColor(160, 70, 87);
            pdf.line(marginMM, 59, pageWidthMM - marginMM, 59);
        }

        let remainingMM = totalImgHeightMM;
        let sourceYpx = 0;
        addHeader();

        while (remainingMM > 0.5) {
            const sliceHeightMM = Math.min(remainingMM, availHeightMM);
            const sliceHeightPx = Math.round(sliceHeightMM * pxPerMM);
            const tmpCanvas = document.createElement('canvas');
            tmpCanvas.width = canvas.width;
            tmpCanvas.height = sliceHeightPx;
            const ctx = tmpCanvas.getContext('2d');
            ctx.drawImage(canvas, 0, sourceYpx, canvas.width, sliceHeightPx, 0, 0, canvas.width, sliceHeightPx);
            const sliceDataURL = tmpCanvas.toDataURL('image/png');
            pdf.addImage(sliceDataURL, 'PNG', marginMM, headerHeightMM, contentWidthMM, sliceHeightMM);
            sourceYpx += sliceHeightPx;
            remainingMM -= sliceHeightMM;
            if (remainingMM > 0.5) {
                pdf.addPage();
                addHeader();
            }
        }

        const fileName = `Customers_Closing_Report_${pdfDateFrom}_to_${pdfDateTo}.pdf`.replace(/\s+/g, '_');
        pdf.save(fileName);

    } catch (error) {
        console.error('Error generating PDF:', error);
        alert('An error occurred while generating the PDF. Please try again.');
    } finally {
        pdfBtn.innerHTML = originalHTML;
        pdfBtn.disabled = false;
    }
}
</script>

<?php include('../includes/ft.php'); ?>