<?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[] = "(gp_name LIKE '%$search%' OR gp_id LIKE '%$search%' OR gp_phone LIKE '%$search%')";
}

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

// Get all general parties with their balances
$sql = "SELECT id, gp_id, gp_name, gp_address, gp_phone, opening_balance, current_balance, date_time 
        FROM general_parties 
        $where_clause 
        ORDER BY gp_name ASC";
$result = mysqli_query($conn, $sql);

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

while($row = mysqli_fetch_assoc($result)) {
    $total_opening_balance += $row['opening_balance'];
    $total_current_balance += $row['current_balance'];
    
    // Calculate total payable for this GP (Amount party owes us - Debit)
    $payable_sql = "SELECT COALESCE(SUM(amount), 0) as total FROM gp_payable WHERE gp_id = {$row['id']}";
    $payable_result = mysqli_query($conn, $payable_sql);
    $payable_data = mysqli_fetch_assoc($payable_result);
    $row['total_payable'] = $payable_data['total'] ?? 0;
    
    // Calculate total paid for this GP (Party paid us - Credit)
    $paid_sql = "SELECT COALESCE(SUM(amount), 0) as total FROM gp_paid WHERE gp_id = {$row['id']}";
    $paid_result = mysqli_query($conn, $paid_sql);
    $paid_data = mysqli_fetch_assoc($paid_result);
    $row['total_paid'] = $paid_data['total'] ?? 0;
    
    // Calculate total received for this GP (We paid to party - Debit)
    $received_sql = "SELECT COALESCE(SUM(amount), 0) as total FROM gp_received WHERE gp_id = {$row['id']}";
    $received_result = mysqli_query($conn, $received_sql);
    $received_data = mysqli_fetch_assoc($received_result);
    $row['total_received'] = $received_data['total'] ?? 0;
    
    $gp_data[] = $row;
}
mysqli_data_seek($result, 0);
?>

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

<div class="gp-closing-container">
    <!-- Page Header -->
    <div class="page-header">
        <div class="header-left">
            <h2><i class="fas fa-address-book"></i> General Party Closing Report</h2>
            <p>Complete summary of all general parties 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 Party</label>
                        <input type="text" name="search" class="form-control-modern" placeholder="Name, ID, 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="gp_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> PDF</button>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <!-- Report Content for PDF capture -->
    <div id="report-content-gp">
        <!-- Summary Cards -->
        <div class="summary-cards">
            <div class="summary-card">
                <div class="summary-icon total-parties"><i class="fas fa-address-book"></i></div>
                <div class="summary-content">
                    <h4><?php echo count($gp_data); ?></h4>
                    <p>Total Parties</p>
                    <small>Registered General Parties</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-arrow-up"></i></div>
                <div class="summary-content">
                    <h4 class="text-danger">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' : ($total_current_balance < 0 ? '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>

        <!-- General Parties Table -->
        <div class="table-card">
            <div class="table-card-header">
                <div class="header-info"><i class="fas fa-list"></i><h4>General Parties Closing Balance</h4></div>
                <div class="table-stats">Showing <strong><?php echo count($gp_data); ?></strong> parties</div>
            </div>
            <div class="table-card-body">
                <div class="table-responsive">
                    <table class="modern-table" id="gpTable">
                        <thead>
                            <tr>
                                <th>#</th>
                                <th>Party ID</th>
                                <th>Party Name</th>
                                <th>Phone</th>
                                <th>Opening Balance</th>
                                <th>Payable</th>
                                <th>Paid</th>
                                <th>Received</th>
                                <th>Closing Balance</th>
                                <th>Status</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if(count($gp_data) > 0): ?>
                                <?php 
                                $sr_no = 1;
                                foreach($gp_data as $gp): 
                                    $balance_status = $gp['current_balance'] > 0 ? 'due' : ($gp['current_balance'] < 0 ? 'advance' : 'clear');
                                ?>
                                    <tr>
                                        <td data-label="#"><?php echo $sr_no++; ?></td>
                                        <td data-label="Party ID"><span class="party-id-badge"><?php echo htmlspecialchars($gp['gp_id']); ?></span></div>
                                        <td data-label="Party Name">
                                            <div class="party-cell">
                                                <div class="party-avatar"><i class="fas fa-building"></i></div>
                                                <div class="party-info">
                                                    <strong><?php echo htmlspecialchars($gp['gp_name']); ?></strong>
                                                    <small><?php echo htmlspecialchars($gp['gp_address'] ?: 'No address'); ?></small>
                                                </div>
                                            </div>
                                        </div>
                                        <td data-label="Phone"><?php echo htmlspecialchars($gp['gp_phone']); ?></div>
                                        <td data-label="Opening Balance" class="opening-balance-cell">Rs <?php echo number_format($gp['opening_balance'], 2); ?></div>
                                        <td data-label="Payable" class="payable-cell">Rs <?php echo number_format($gp['total_payable'], 2); ?></div>
                                        <td data-label="Paid" class="paid-cell">Rs <?php echo number_format($gp['total_paid'], 2); ?></div>
                                        <td data-label="Received" class="received-cell">Rs <?php echo number_format($gp['total_received'], 2); ?></div>
                                        <td data-label="Closing Balance">
                                            <div class="closing-balance-cell <?php echo $balance_status; ?>">
                                                Rs <?php echo number_format(abs($gp['current_balance']), 2); ?>
                                                <?php if($gp['current_balance'] > 0): ?>
                                                    <span class="dr-cr">Dr</span>
                                                <?php elseif($gp['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; ?>">
                                                <?php if($balance_status == 'due'): ?>
                                                    <i class="fas fa-hourglass-half"></i> Payable
                                                <?php elseif($balance_status == 'advance'): ?>
                                                    <i class="fas fa-money-bill-wave"></i> Advance
                                                <?php else: ?>
                                                    <i class="fas fa-check-circle"></i> Settled
                                                <?php endif; ?>
                                            </span>
                                        </div>
                                    </tr>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="10" class="empty-state">
                                        <i class="fas fa-address-book"></i>
                                        <p>No general parties 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-cell"><strong>Rs <?php echo number_format($total_opening_balance, 2); ?></strong></div>
                                <td class="payable-cell"><strong>—</strong></div>
                                <td class="paid-cell"><strong>—</strong></div>
                                <td class="received-cell"><strong>—</strong></div>
                                <td class="closing-balance-total"><strong>Rs <?php echo number_format($total_current_balance, 2); ?></strong> <strong><?php echo $total_current_balance > 0 ? 'Dr' : ($total_current_balance < 0 ? 'Cr' : ''); ?></strong></div>
                                <td>—</div>
                            </tr>
                        </tfoot>
                    </table>
                </div>
            </div>
        </div>
    </div><!-- end #report-content-gp -->
</div>

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

.gp-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-parties { background: rgba(160,70,87,0.1); }
.total-parties 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;
}

.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 12px;
    background: #f8f9fc;
    font-weight: 700;
    color: #445566;
    font-size: 11px;
    text-transform: uppercase;
    border-bottom: 2px solid #e8e8e8;
}

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

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

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

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

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

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

.party-id-badge {
    background: #e3f2fd;
    color: #1976d2;
    padding: 3px 8px;
    border-radius: 10px;
    font-size: 10px;
    font-weight: 600;
    display: inline-block;
}

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

.payable-cell {
    color: #dc3545;
    font-weight: 600;
}

.paid-cell {
    color: #28a745;
    font-weight: 600;
}

.received-cell {
    color: #ff9800;
    font-weight: 600;
}

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

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

.closing-balance-cell.advance {
    color: #17a2b8;
}

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

.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;
}

.closing-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;
    margin-bottom: 4px;
}

.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: 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;
    }
    .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 = 'General Party Closing Report';

async function downloadPDF() {
    const element = document.getElementById('report-content-gp');
    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 = `General_Party_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'); ?>