<?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 contact_person LIKE '%$search%' OR phone LIKE '%$search%')";
}

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

// Get all suppliers with their current balance
$sql = "SELECT id, name, contact_person, phone, email, address, opening_balance, current_balance, date_time 
        FROM suppliers 
        $where_clause 
        ORDER BY name ASC";
$result = mysqli_query($conn, $sql);

// Calculate totals
$total_opening_balance = 0;
$total_current_balance = 0;
$suppliers_data = [];

while($row = mysqli_fetch_assoc($result)) {
    $total_opening_balance += $row['opening_balance'];
    $total_current_balance += $row['current_balance'];
    
    // Get last transaction date
    $last_trans_sql = "SELECT MAX(date_time) as last_date FROM (
        SELECT date_time FROM purchases WHERE supplier_id = {$row['id']}
        UNION ALL
        SELECT date_time FROM supplier_payments WHERE supplier_id = {$row['id']}
    ) as transactions";
    $last_trans_result = mysqli_query($conn, $last_trans_sql);
    $last_trans = mysqli_fetch_assoc($last_trans_result);
    $row['last_transaction'] = $last_trans['last_date'] ? date('d-m-Y', strtotime($last_trans['last_date'])) : 'No transaction';
    
    $suppliers_data[] = $row;
}
mysqli_data_seek($result, 0);
?>

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

<div class="supplier-closing-container">
    <!-- Page Header -->
    <div class="page-header">
        <div class="header-left">
            <h2><i class="fas fa-file-invoice"></i> Suppliers Closing Report</h2>
            <p>Complete summary of all supplier 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 -->
    <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">
                <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 Supplier</label>
                        <input type="text" name="search" class="form-control-modern" placeholder="Name, contact, phone..." 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="supplier_closing_report.php" class="btn-reset"><i class="fas fa-sync-alt"></i> Reset</a>
                        <button type="button" onclick="window.print()" class="btn-print"><i class="fas fa-print"></i> Print</button>
                        <button type="button" class="btn-pdf" onclick="downloadPDF()"><i class="fas fa-file-pdf"></i> PDF</button>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <!-- Report Content for PDF capture -->
    <div id="report-content-supplier">
        <!-- Summary Cards -->
        <div class="summary-cards">
            <div class="summary-card">
                <div class="summary-icon total-suppliers"><i class="fas fa-truck"></i></div>
                <div class="summary-content">
                    <h4><?php echo count($suppliers_data); ?></h4>
                    <p>Total Suppliers</p>
                    <small>Registered Suppliers</small>
                </div>
            </div>
            <div class="summary-card">
                <div class="summary-icon total-opening"><i class="fas fa-play-circle"></i></div>
                <div class="summary-content">
                    <h4>Rs <?php echo number_format($total_opening_balance, 2); ?></h4>
                    <p>Total Opening Balance</p>
                    <small>Initial Balance</small>
                </div>
            </div>
            <div class="summary-card">
                <div class="summary-icon total-payable"><i class="fas fa-hand-holding-usd"></i></div>
                <div class="summary-content">
                    <h4>Rs <?php echo number_format($total_current_balance, 2); ?></h4>
                    <p>Total Payable</p>
                    <small>Amount to Pay</small>
                </div>
            </div>
            <div class="summary-card">
                <div class="summary-icon net-balance"><i class="fas fa-balance-scale"></i></div>
                <div class="summary-content">
                    <h4 class="<?php echo $total_current_balance > 0 ? 'text-danger' : 'text-success'; ?>">
                        Rs <?php echo number_format(abs($total_current_balance), 2); ?>
                        <?php echo $total_current_balance > 0 ? 'Dr' : ($total_current_balance < 0 ? 'Cr' : ''); ?>
                    </h4>
                    <p>Net Payable</p>
                    <small>Outstanding Balance</small>
                </div>
            </div>
        </div>

        <!-- Suppliers Table -->
        <div class="table-card">
            <div class="table-card-header">
                <div class="header-info"><i class="fas fa-list"></i><h4>Suppliers Closing Balance</h4></div>
                <div class="table-stats">Showing <strong><?php echo count($suppliers_data); ?></strong> suppliers</div>
            </div>
            <div class="table-card-body">
                <div class="table-responsive">
                    <table class="modern-table" id="suppliersTable">
                        <thead>
                            <tr>
                                <th>#</th>
                                <th>Supplier Name</th>
                                <th>Contact Person</th>
                                <th>Phone</th>
                                <th>Opening Balance</th>
                                <th>Purchases</th>
                                <th>Payments</th>
                                <th>Current Balance</th>
                                <th>Status</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if(count($suppliers_data) > 0): ?>
                                <?php 
                                $sr_no = 1;
                                foreach($suppliers_data as $supplier): 
                                    $purchases_sql = "SELECT SUM(total_amount) as total_purchases FROM purchases WHERE supplier_id = {$supplier['id']}";
                                    $purchases_result = mysqli_query($conn, $purchases_sql);
                                    $purchases_data = mysqli_fetch_assoc($purchases_result);
                                    $total_purchases = $purchases_data['total_purchases'] ?? 0;
                                    
                                    $payments_sql = "SELECT SUM(amount) as total_payments FROM supplier_payments WHERE supplier_id = {$supplier['id']}";
                                    $payments_result = mysqli_query($conn, $payments_sql);
                                    $payments_data = mysqli_fetch_assoc($payments_result);
                                    $total_payments = $payments_data['total_payments'] ?? 0;
                                    
                                    $balance_status = $supplier['current_balance'] > 0 ? 'due' : 'clear';
                                    $balance_text = $supplier['current_balance'] > 0 ? 'Payable' : ($supplier['current_balance'] < 0 ? 'Advance' : 'Settled');
                                ?>
                                    <tr>
                                        <td data-label="#"><?php echo $sr_no++; ?></td>
                                        <td data-label="Supplier Name">
                                            <div class="supplier-cell">
                                                <div class="supplier-avatar"><i class="fas fa-building"></i></div>
                                                <div class="supplier-info">
                                                    <strong><?php echo htmlspecialchars($supplier['name']); ?></strong>
                                                    <small><?php echo htmlspecialchars($supplier['email'] ?: 'No email'); ?></small>
                                                </div>
                                            </div>
                                        </div>
                                        <td data-label="Contact Person">
                                            <div class="contact-cell"><i class="fas fa-user"></i> <?php echo htmlspecialchars($supplier['contact_person'] ?: '—'); ?></div>
                                        </div>
                                        <td data-label="Phone">
                                            <div class="phone-cell"><i class="fas fa-phone-alt"></i> <?php echo htmlspecialchars($supplier['phone']); ?></div>
                                        </div>
                                        <td data-label="Opening Balance" class="opening-balance">Rs <?php echo number_format($supplier['opening_balance'], 2); ?></div>
                                        <td data-label="Purchases" class="purchases-amount">Rs <?php echo number_format($total_purchases, 2); ?></div>
                                        <td data-label="Payments" class="payments-amount">Rs <?php echo number_format($total_payments, 2); ?></div>
                                        <td data-label="Current Balance">
                                            <div class="balance-cell <?php echo $balance_status; ?>">
                                                Rs <?php echo number_format(abs($supplier['current_balance']), 2); ?>
                                                <?php if($supplier['current_balance'] > 0): ?>
                                                    <span class="dr-cr">Dr</span>
                                                <?php elseif($supplier['current_balance'] < 0): ?>
                                                    <span class="dr-cr">Cr</span>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                        <td data-label="Status">
                                            <span class="status-badge <?php echo $balance_status; ?>">
                                                <i class="fas <?php echo $balance_status == 'due' ? 'fa-hourglass-half' : 'fa-check-circle'; ?>"></i>
                                                <?php echo $balance_text; ?>
                                            </span>
                                        </div>
                                    </tr>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="9" class="empty-state">
                                        <i class="fas fa-truck"></i>
                                        <p>No suppliers 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="opening-balance"><strong>Rs <?php echo number_format($total_opening_balance, 2); ?></strong></div>
                                <td>—</div>
                                <td>—</div>
                                <td class="current-balance-total"><strong>Rs <?php echo number_format($total_current_balance, 2); ?></strong></div>
                                <td>—</div>
                            </tr>
                        </tfoot>
                    </table>
                </div>
            </div>
        </div>
    </div><!-- end report-content-supplier -->

    <!-- Summary Footer -->
    <div class="summary-footer">
        <div class="footer-note"><i class="fas fa-info-circle"></i> Report generated on: <?php echo date('d-m-Y h:i A'); ?></div>
        <div class="footer-note"><i class="fas fa-rupee-sign"></i> Total Payable to Suppliers: <strong>Rs <?php echo number_format($total_current_balance, 2); ?></strong></div>
    </div>
</div>

<style>
/* Supplier 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;
}

.supplier-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-suppliers { background: rgba(160,70,87,0.1); }
.total-suppliers i { color: #A04657; }
.total-opening { background: rgba(108,92,231,0.1); }
.total-opening i { color: #6c5ce7; }
.total-payable { background: rgba(220,53,69,0.1); }
.total-payable i { color: #dc3545; }
.net-balance { background: rgba(40,167,69,0.1); }
.net-balance 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;
    flex-wrap: wrap;
}

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

.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;
    text-decoration: none;
    color: #555;
}

.btn-print {
    background: #6c5ce7;
    color: #fff;
}

.btn-print:hover {
    background: #5a4ad1;
}

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

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

/* 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: 900px;
}

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

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

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

.supplier-cell {
    display: flex;
    align-items: center;
    gap: 10px;
}

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

.supplier-avatar i {
    font-size: 16px;
    color: #A04657;
}

.supplier-info strong {
    display: block;
    font-size: 13px;
    color: #1a1a2e;
}

.supplier-info small {
    font-size: 9px;
    color: #999;
}

.contact-cell, .phone-cell {
    display: flex;
    align-items: center;
    gap: 6px;
}

.contact-cell i, .phone-cell i {
    color: #A04657;
    font-size: 12px;
}

.opening-balance {
    font-weight: 500;
    color: #6c5ce7;
}

.purchases-amount {
    color: #dc3545;
    font-weight: 600;
}

.payments-amount {
    color: #28a745;
    font-weight: 600;
}

.balance-cell {
    font-weight: 700;
    font-size: 13px;
}

.balance-cell.due {
    color: #dc3545;
}

.balance-cell.clear {
    color: #28a745;
}

.dr-cr {
    font-size: 10px;
    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.clear {
    background: #e8f5e9;
    color: #2e7d32;
}

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

.current-balance-total {
    color: #A04657;
    font-size: 14px;
}

.summary-footer {
    background: #f8f9fc;
    border-radius: 14px;
    padding: 12px 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    gap: 12px;
    border: 1px solid #f0f0f0;
}

.footer-note {
    font-size: 11px;
    color: #666;
    display: flex;
    align-items: center;
    gap: 6px;
}

.footer-note strong {
    color: #A04657;
    font-size: 15px;
}

.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 12px;
    }
    .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;
    }
    .modern-table td::before {
        content: attr(data-label);
        position: absolute;
        left: 12px;
        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;
    }
    .supplier-cell {
        justify-content: flex-end;
    }
    .summary-footer {
        flex-direction: column;
        text-align: center;
    }
    .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, .page-header, .filter-card, .summary-footer,
    .btn-print, .btn-reset, .btn-search, .btn-pdf {
        display: none !important;
    }
    .main-content {
        margin: 0;
        padding: 0;
        width: 100%;
    }
    body {
        background: #fff;
        padding: 0;
    }
    .modern-table {
        border: 1px solid #ddd;
    }
    .modern-table th {
        background: #f0f0f0 !important;
        color: #000 !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 pdfFromDate = '<?php echo $from_date ? date('d-m-Y', strtotime($from_date)) : 'All Dates'; ?>';
const pdfToDate = '<?php echo $to_date ? date('d-m-Y', strtotime($to_date)) : 'All Dates'; ?>';
const reportTitle = 'Suppliers Closing Report';

async function downloadPDF() {
    const element = document.getElementById('report-content-supplier');
    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 imgData = canvas.toDataURL('image/png');
        const imgWidth = 210;
        const pageHeight = 297;
        const pageWidth = imgWidth - 20;
        const imgHeight = (canvas.height * pageWidth) / canvas.width;
        
        const { jsPDF } = window.jspdf;
        const pdf = new jsPDF('p', 'mm', 'a4');

        function addHeader() {
            pdf.setFont('helvetica', 'bold');
            pdf.setFontSize(18);
            pdf.setTextColor(160, 70, 87);
            pdf.text('ALFATEH PETROLEUM SERVICE', 105, 20, { align: 'center' });
            
            pdf.setFontSize(11);
            pdf.setTextColor(100, 100, 100);
            pdf.text('Complete Fuel Station Management Solution', 105, 27, { align: 'center' });
            
            pdf.setFontSize(10);
            pdf.setTextColor(80, 80, 80);
            pdf.text('Shaikh bhirkyo road Tando Muhammad khan', 105, 34, { align: 'center' });
            
            pdf.setDrawColor(160, 70, 87);
            pdf.setLineWidth(0.5);
            pdf.line(15, 40, 195, 40);
            
            pdf.setFontSize(16);
            pdf.setTextColor(0, 0, 0);
            pdf.text(reportTitle, 105, 48, { align: 'center' });
            
            const periodText = (pdfFromDate === 'All Dates' && pdfToDate === 'All Dates') ?
                'Period: All Dates' : `Period: ${pdfFromDate} To ${pdfToDate}`;
            pdf.setFontSize(10);
            pdf.setTextColor(80, 80, 80);
            pdf.text(periodText, 105, 55, { align: 'center' });
            
            pdf.line(15, 59, 195, 59);
        }
        addHeader();

        const topMargin = 65;
        const bottomMargin = 10;
        const availableHeightPage1 = pageHeight - topMargin - bottomMargin;
        
        if (imgHeight <= availableHeightPage1) {
            pdf.addImage(imgData, 'PNG', 10, topMargin, pageWidth, imgHeight);
        } else {
            let remainingHeight = imgHeight;
            let sourceY = 0;
            let pageNum = 1;
            const canvasHeight = canvas.height;

            while (remainingHeight > 0) {
                const available = (pageNum === 1) ? availableHeightPage1 : (pageHeight - topMargin - bottomMargin);
                let sliceHeight = Math.min(remainingHeight, available);
                const sourceHeightPx = (sliceHeight / imgHeight) * canvasHeight;

                pdf.addImage(imgData, 'PNG', 10, topMargin, pageWidth, sliceHeight, undefined, 'FAST', 0, 0, sourceY, canvas.width, sourceHeightPx);

                remainingHeight -= sliceHeight;
                sourceY += sourceHeightPx;

                if (remainingHeight > 0) {
                    pdf.addPage();
                    pageNum++;
                    pdf.setFontSize(8);
                    pdf.setTextColor(150);
                    pdf.text('Continued...', 105, 10, { align: 'center' });
                }
            }
        }

        const fileName = `Suppliers_Closing_Report_${pdfFromDate}_to_${pdfToDate}.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'); ?>