<div class="container">
    <div class="text-right mb-3" style="margin-bottom: 15px;">
        <button id="downloadPdf" class="btn btn-primary">Download Deemand Sheet</button>
    </div>

    <table class="table table-striped table-bordered table-hover table-responsive" id="accountTable">
      <tr>
        <th>SL</th>
        <th>Type</th>
        <th>AC No</th>
        <th>Name</th>
        <th>Account Creation Date</th>
        <th>Maturity Value</th>
        <th>Balance</th>
        <th>No Of Installment</th>
        <th>No Of Paid Installment</th>
        <th>Installment Amount</th>
      </tr>
      <?php
        $conn = new mysqli($GLOBALS['host'], $GLOBALS['user'], $GLOBALS['pass'], $GLOBALS['db']);
        if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); }

        $agent_id = $_SESSION['user_id'];
        if ($_SESSION['type'] === 'admin') {
            $sql = "SELECT * FROM `" . $GLOBALS['arif_ac'] . "` WHERE `AA_BAL` < 0 ORDER BY `AA_ID` DESC";
            $stmt = $conn->prepare($sql);
        } elseif ($_SESSION['type'] === 'agent') {
            $sql = "SELECT * FROM `" . $GLOBALS['arif_ac'] . "` WHERE `AA_BAL` < 0 AND `AA_AGENT` = ? ORDER BY `AA_ID` DESC";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("s", $agent_id);
        }

        $stmt->execute();
        $result = $stmt->get_result();

        $pdfData = []; // PDF এর জন্য array
        if ($result->num_rows > 0) {
            while ($row = $result->fetch_assoc()) {
                $tt = $row["AA_ID"] - 10;
                echo "
                  <tr>
                    <td>{$tt}</td>                
                    <td>{$row["AA_ACTYPE"]},{$row["AA_TYPE"]}</td>
                    <td>{$row["AA_ACNO"]}</td>
                    <td>{$row["AA_NAME"]}</td>
                    <td>{$row["AA_DATE"]}</td>
                    <td>{$row["AA_MATURE_VALUE"]}</td>
                    <td>{$row["AA_BAL"]}</td>
                    <td>{$row["AA_NO_OF_PAYMENT"]}</td>
                    <td>{$row["AA_NO_OF_PAYPAID"]}</td>
                    <td>{$row["AA_INSTALLMENT"]}</td>
                  </tr>";

                // PDF data push
                $pdfData[] = [
                    $tt,
                    $row["AA_ACTYPE"] . "," . $row["AA_TYPE"],
                    $row["AA_ACNO"],
                    $row["AA_NAME"],
                    $row["AA_DATE"],
                    $row["AA_MATURE_VALUE"],
                    $row["AA_BAL"],
                    $row["AA_NO_OF_PAYMENT"],
                    $row["AA_NO_OF_PAYPAID"],
                    $row["AA_INSTALLMENT"]
                ];
            }
        } else {
            echo "<tr><td colspan='10'>0 results</td></tr>";
        }
        $conn->close();
      ?>
    </table>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf-autotable/3.5.28/jspdf.plugin.autotable.min.js"></script>

<script>
document.addEventListener('DOMContentLoaded', function() {
    document.getElementById('downloadPdf').addEventListener('click', function() {
        const { jsPDF } = window.jspdf;
        const doc = new jsPDF('p', 'pt', 'a4');

        const userType = "<?php echo $_SESSION['type']; ?>";
        const userName = "<?php echo $_SESSION['user_id']; ?>";
        const now = new Date();
        const dateTime = now.toLocaleDateString() + " " + now.toLocaleTimeString();

        let titleText = (userType === 'admin') 
            ? "Full Demand Sheet" 
            : `Agent Demand Sheet (Agent ID: ${userName})`;

        const tableData = <?php echo json_encode($pdfData); ?>;

        function formatCurrency(value) {
            // Remove commas, currency symbols, spaces
            let cleaned = String(value).replace(/[₹,\s]/g, '');
            
            // Ensure minus sign stays
            let num = parseFloat(cleaned) || 0;
            
            // Format with Indian locale
            return (num < 0 ? '-' : '') + '₹' + Math.abs(num).toLocaleString('en-IN', { 
                minimumFractionDigits: 2, 
                maximumFractionDigits: 2 
            });
        }

        const logo = new Image();
        logo.src = '/asset/images/new_logo2.jpg';
        logo.onload = function() { addHeader(); };
        logo.onerror = function() { addHeader(); };

        function addHeader() {
            try { doc.addImage(logo, 'PNG', 40, 30, 40, 40); } catch(e) {}

            doc.setFontSize(16);
            doc.text(titleText, 100, 50);
            doc.setFontSize(10);
            doc.text(`Generated on: ${dateTime}`, 40, 80);
            doc.text(`User Type: ${userType}`, 40, 95);
            doc.text(`User ID: ${userName}`, 40, 110);
            addTable();
        }

        function addTable() {
            const headers = ["SL", "Type", "AC No", "Name", "Creation Date", "Maturity Value", "Balance", "Inst.", "Paid", "Amount"];

            let totalBalance = 0, totalInstallment = 0;
            const rows = tableData.map(r => {
                totalBalance += parseFloat(r[6]) || 0;
                totalInstallment += parseFloat(r[9]) || 0;
                return [
                    r[0], r[1], r[2], r[3], r[4],
                    r[5], r[6],
                    r[7], r[8],
                    r[9]
                ];
            });

            doc.autoTable({
                head: [headers],
                body: rows,
                startY: 130,
                styles: { 
                    fontSize: 8, 
                    cellPadding: { top: 6, right: 5, bottom: 6, left: 5 }, // custom padding
                    overflow: 'hidden' 
                },
                headStyles: { fillColor: [233, 84, 32], textColor: 255 },
                bodyStyles: { valign: 'middle' } // vertically center align
            });

            // let finalY = doc.lastAutoTable.finalY + 20;
            // doc.setFont(undefined, 'bold');
            // doc.text(`Total Accounts: ${rows.length}`, 40, finalY);
            // doc.text(`Total Balance: ${totalBalance}`, 40, finalY + 15);
            // doc.text(`Total Installment Amount: ${totalInstallment}`, 40, finalY + 30);

            const pageCount = doc.internal.getNumberOfPages();
            for (let i = 1; i <= pageCount; i++) {
                doc.setPage(i);
                doc.setFontSize(9);
                doc.setFont(undefined, 'normal');
                doc.text(`Generated by Loan Portal - Confidential`, 40, doc.internal.pageSize.height - 20);
                doc.text(`Page ${i} of ${pageCount}`, doc.internal.pageSize.width - 60, doc.internal.pageSize.height - 20);
            }

            doc.save(`Demand_Sheet_${userType}_${userName}_${now.toISOString().slice(0,10)}.pdf`);
        }
    });
});
</script>
