<?php include '../header.php'; ?>
<?php include '../sidemenu.php'; ?>

<div class="page-header d-print-none">
    <div class="container-xl">
        <div class="row g-2 align-items-center">
            <div class="col d-flex justify-content-between">
                <h2 class="page-title">Cash Book Report</h2>
            </div>
        </div>
    </div>
</div>

<div class="page-body">
    <div class="container-xl">
        <div class="row row-cards">
            <div class="col-12">
                <div class="row">
                    <div class="col-3 mb-3 row">
                        <label class="col-4 col-form-label text-end">Date From</label>
                        <div class="col">
                            <input type="text" class="flatpickr flatpickr-input active form-control" id="dateFrom" required>
                        </div>
                    </div>
                    <div class="col-3 mb-3 row">
                        <label class="col-4 col-form-label text-end">Date To</label>
                        <div class="col">
                            <input type="text" class="flatpickr flatpickr-input active form-control" id="dateTo" required>
                        </div>
                    </div>
                    <div class="col-3 mb-3 row">
                        <label class="col-4 col-form-label text-end">Type</label>
                        <div class="col">
                            <select type="text" class="form-select" id="cboType">
                                <option value="all">All</option>
                                <option value="main cash">Main Cash</option>
                                <option value="petty cash">Petty Cash</option>
                            </select>
                        </div>
                    </div>
                </div>

                <div class="d-flex justify-content-between">
                    <h3 class="card-title"><span id="total_records" style="font-weight:bold;"> </span></h3>
                    <div class="export-buttons-container" style="margin-bottom: 10px;">
                        <button id="exportCSV" class="btn btn-outline-primary">Export to CSV</button>
                        <button id="exportExcel" class="btn btn-outline-primary">Export to Excel</button>
                        <button id="exportPDF" class="btn btn-outline-primary">Export to PDF</button>
                        <button id="printTable" class="btn btn-outline-primary">Print Table</button>
                    </div>
                </div>

                <div class="card-body p-0 table-responsive " style="max-height: 500px;">
                    <table class="table table-striped table-head-fixed table-bordered" id="myTable">
                        <thead class="sticky-top bg-light">                  
                            <tr>
                                <th style="width: 3%">#</th>
                                <th>Date</th>
                                <th>Account Type</th>
                                <th>Account Head</th>
                                <th>Particular</th>
                                <th>Income</th>
                                <th>Expense</th>
                                <th>Balance</th>
                            </tr>
                        </thead>
                        <tbody>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<?php include '../footer.php'; ?>

<!-- Required Libraries -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.4.0/jspdf.umd.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf-autotable/3.5.25/jspdf.plugin.autotable.min.js"></script>

<script>
    var today = new Date().toISOString().split('T')[0];
    const today1 = new Date();
    const firstDayOfMonth = new Date(today1.getFullYear(), today1.getMonth(), 1);

    $(function () {
        flatpickr("#dateFrom", {
            dateFormat: "Y-m-d",
            defaultDate: firstDayOfMonth,
            maxDate: today,
        });
        flatpickr("#dateTo", {
            dateFormat: "Y-m-d",
            defaultDate: today,
            maxDate: today,
        });
        search();
    });

    $("#dateFrom, #dateTo, #cboType").change(function () {
        search();
    });

    function search() {
        var df = $("#dateFrom").val();
        var dt = $("#dateTo").val();
        var type = $("#cboType").val();
        $.ajax({
            type: "POST",
            url: APP_URL + "api/sales/search_cash_book.php",
            data: JSON.stringify({ df: df, dt: dt, type: type }),
            error: function (data) {
                $("#loading").css("display", "none");
            }
        }).done(function (data) {
            console.log(data);
            $("#myTable").find("tbody").find("tr").remove();
            $("#myTable").find("tbody")
                .append($('<tr>')
                    .append("<td>1</td>")
                    .append("<td colspan='6'><b stylestyle='white-space: nowrap;'>Opening Balance</b></td>")
                    .append("<td style='text-align: right;font-weight:bold;font-size:20px;'><span id='openingbalance'></span></td>")
                );
            $("#openingdate").text(df);
            $("#openingbalance").text(parseFloat(data.balance).toFixed(2));
            var balance = parseFloat(data.balance);

            $.each(data.records, function (i, v) {
                balance -= parseFloat(v.ex_amt);
                balance += parseFloat(v.in_amt);
                $("#myTable").find("tbody")
                    .append($('<tr>')
                        .append("<td>" + (i + 2) + "</td>")
                        .append("<td>" + v.date + "</td>")
                        .append("<td>" + v.account_head + "</td>")
                        .append("<td>" + v.head + "</td>")
                        .append("<td>" + v.particular + "</td>")
                        .append("<td style='text-align: right;'>" + ((v.in_amt == 0) ? "" : Number(v.in_amt).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })) + "</td>")
                        .append("<td style='text-align: right;'>" + ((v.ex_amt == 0) ? "" : Number(v.ex_amt).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })) + "</td>")
                        .append("<td style='text-align: right;" + (data.records.length == (i + 1) ? "font-weight:bold;font-size:20px;" : "") + "'>" + Number(balance).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 }) + "</td>")
                    );
            });

            $("#myTable").find("tbody")
                .append($('<tr style="font-weight:bold;">')
                    .append("<td colspan='8'>Total Amount From " + df + " To " + dt + " By Account Head</td>")
                );

            $.each(data.records1, function (i, b) {
                $("#myTable").find("tbody")
                    .append($('<tr style="font-weight:bold;">')
                        .append("<td colspan='2'>" + b.R + "</td>")
                        .append("<td colspan='1'>" + b.account_head + "</td>")
                        .append("<td style='text-align:right;'>" + Number(b.amount).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 }) + "</td>")
                    );
            });

            $("#myTable").find("tbody")
                .append($('<tr style="font-weight:bold;">')
                    .append("<td colspan='8'>Total Amount From " + df + " To " + dt + " By Type</td>")
                );

            $.each(data.records2, function (i, b) {
                $("#myTable").find("tbody")
                    .append($('<tr style="font-weight:bold;">')
                        .append("<td colspan='2'>" + b.R + "</td>")
                        .append("<td style='text-align:right;'>" + Number(b.amount).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 }) + "</td>")
                    );
            });

            $("#total_records").text("Closing Balance = " + Number(balance).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 }));
        });
    }

    // Export to CSV
    $("#exportCSV").click(function () {
        var table = document.getElementById("myTable");
        var rows = table.querySelectorAll("tr");
        var csvContent = "";

        rows.forEach(function (row) {
            var cols = row.querySelectorAll("td, th");
            var rowData = [];
            cols.forEach(function (col) {
                rowData.push('"' + col.innerText.replace(/"/g, '""') + '"');
            });
            csvContent += rowData.join(",") + "\n";
        });

        var blob = new Blob([csvContent], { type: "text/csv" });
        var link = document.createElement("a");
        link.href = URL.createObjectURL(blob);
        link.download = "cash_book_report.csv";
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    });

    // Export to Excel
    $("#exportExcel").click(function () {
        var table = document.getElementById("myTable");
        var workbook = XLSX.utils.table_to_book(table, { sheet: "Cash Book Report" });
        XLSX.writeFile(workbook, "cash_book_report.xlsx");
    });

    // Export to PDF
    $("#exportPDF").click(function () {
        const { jsPDF } = window.jspdf;
        const doc = new jsPDF();

        doc.text("Cash Book Report", 14, 10);

        doc.autoTable({
            html: "#myTable",
            startY: 20,
            styles: { fontSize: 10 },
        });

        doc.save("cash_book_report.pdf");
    });

    // Print Table
    $("#printTable").click(function () {
        var printContents = document.getElementById("myTable").outerHTML;
        var printWindow = window.open("", "_blank");
        printWindow.document.open();
        printWindow.document.write(`
            <html>
                <head>
                    <title>Print Table</title>
                    <style>
                        table { border-collapse: collapse; width: 100%; }
                        table, th, td { border: 1px solid black; }
                        th, td { padding: 8px; text-align: left; }
                    </style>
                </head>
                <body>
                    ${printContents}
                </body>
            </html>
        `);
        printWindow.document.close();
        printWindow.print();
    });
</script>
