<?php
include("../../classes/manager.class.php");
ini_set('display_errors', 1);
error_reporting(E_ALL);

$m = new Manager();
$datefrom = "";
$dateto = "";
$supplierId = "All";
$openingBalance = 0;

// Flag to determine if the report should be displayed
$showReport = false;

if (!isset($_SESSION['sess_userid'])) {
    header("Location: " . PROJECT_ADMIN_URL);
    exit();
}

if ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['view'])) {
    $showReport = true;

    $datefrom = isset($_GET['datefrom']) ? date("Y-m-d", strtotime($_GET['datefrom'])) : date('d-m-Y', strtotime("-30 days"));
    $dateto = isset($_GET['dateto']) ? date("Y-m-d", strtotime($_GET['dateto'])) : date('d-m-Y');
    $supplierId = isset($_GET['supplier_name']) ? $_GET['supplier_name'] : 'All';

    $result = SupplierSetup::GetSupplierLedger($datefrom, $dateto, $supplierId);
    $opening_balance = isset($result['opening_balance']) ? $result['opening_balance'] : [];
    $ledger = isset($result['ledger']) ? $result['ledger'] : [];
} else {
    $datefrom = date('d-m-Y', strtotime("-30 days"));
    $dateto = date('d-m-Y');
    $supplierId = "All";
    $opening_balance = [];
    $ledger = [];
}

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <?php include('../includes/inc_head.php'); ?>
  	 <script>
        $(function () {
            $('#datepicker').pickadate({
                format: 'dd-mm-yyyy',
                selectMonths: true,
                selectYears: true,
            });
            
        });
        $(function () {
            $('#datepicker1').pickadate({
                format: 'dd-mm-yyyy',
                selectMonths: true,
                selectYears: true,
            });
            
        });
    </script>
</head>
<body>
<div id="container">
    <?php include('../includes/inc_top.php'); ?>
    <div class="row">
        <div class="col s12 m12">
            <div>
                <h3>Supplier Ledger Report</h3>
            </div>
            <form action="" method="get" name="search" id="searchfrm">
                <table class="table">
                    <tr>
                        <td class="col m6">Date From<br>
                            <input type="text" name="datefrom" id="datepicker"
                                   placeholder="Date From"
                                   value="<?= isset($_GET['datefrom']) ? $_GET['datefrom'] : date('d-m-Y', strtotime("-30 days")) ?>" class="form-control"/>
                            <input type="hidden" name="view" id="view" class="form-control" value="1"/>
                        </td>
                        <td class="col m6"> Date To<br>
                            <input type="text" name="dateto" id="datepicker1"
                                   placeholder="Date To"
                                   value="<?= isset($_GET['dateto']) ? $_GET['dateto'] : date('d-m-Y') ?>" class="form-control"/>
                        </td>
                    </tr>
                    <tr>
                        <td class="col m6">Supplier<br>
                            <?php
                            $suppliers = SupplierSetup::GetSupplierSetupList("WHERE status = 'active'");
                            ?>
                            <select class="form-control" name="supplier_name" required>
                                <option value="All" <?= $supplierId === 'All' ? 'selected' : '' ?>>All Suppliers</option>
                                <?php foreach ($suppliers as $supplier): ?>
                                    <option value="<?= $supplier->id ?>" <?= $supplier->id == $supplierId ? 'selected' : '' ?>>
                                        <?= $supplier->name ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </td>
                    </tr>
                    <tr>
                        <td colspan="2" class="col s12">
                            <button type="submit" class="btn waves-effect waves-light" style="float:left;">Search</button>
                          <?php if (isset($_GET['view'])) { ?>
                                <button
    onclick="exportTableToCSV('balance_stock_report_data-<?= date('d-m-Y-h-i-a') ?>.csv')"
    class="btn waves-effect waves-light"
    style="float:left; margin-left: 15px;">
    Export CSV
</button>

                                <button
                                    id="print"
                                    class="btn waves-effect waves-light"
                                    style="float:left; margin-left: 15px;">
                                    Print
                                </button>
                            <?php } ?>
                          
                        </td>
                    </tr>
                </table>
            </form>
            <hr>

            <?php if ($showReport): ?>
                <div id="floatThead" class="section">
                    <table class="striped demo1 bordered" id="invoiceTable">
                        <thead>
                        <tr style="border: 1px solid #666;">
                            <th>Type</th>
                            <th>Date</th>
                            <th>Reference #</th>
                            <th>Payment Type</th>
                            <th>Cheque Details</th>
                            <th class="right-align">Debit</th>
                            <th class="right-align">Credit</th>
                            <th class="right-align">Balance</th>
                        </tr>
                        </thead>
                       <tbody>
<?php
$grandTotalDebit = $grandTotalCredit = $grandTotalBalance = 0;
$finalRunningBalance = 0; // Track the final balance after all calculations

$supplierIds = array_unique(array_merge(
    array_column($opening_balance, 'supplier_id'),
    array_column($ledger, 'supplier_id')
));

foreach ($supplierIds as $supplierId) {
    $supplierOpeningData = current(array_filter($opening_balance, function ($ob) use ($supplierId) {
        return $ob->supplier_id === $supplierId;
    }));

    $supplierOpeningBalance = $supplierOpeningData->opening_balance ?? 0;
    $supplierName = $supplierOpeningData->supplier_name ?? 'Unknown';

    $supplierTotalDebit = $supplierTotalCredit = 0;
    $supplierRunningBalance = $supplierOpeningBalance;

    $supplierLedgerEntries = array_filter($ledger, function ($entry) use ($supplierId) {
        return $entry->supplier_id === $supplierId;
    });

    if (empty($supplierLedgerEntries) && $supplierOpeningBalance == 0) continue;

    echo "
    <tr class='table-heading' style='border: 2px solid #666; background-color: #f9f9f9;'>
        <td colspan='8' style='text-align: left; font-weight: bold; font-size: 16px;'>Supplier: {$supplierName}</td>
    </tr>";

    echo "
    <tr class='table-info' style='border: 1px solid #666;'>
        <td>Opening Balance</td>
        <td>-</td>
        <td>-</td>
        <td>-</td>
        <td></td>
        <td></td>
        <td></td>
        <td class='right-align'>" . number_format($supplierOpeningBalance, 2) . "</td>
    </tr>";

    foreach ($supplierLedgerEntries as $entry) {
        $debit = (float)($entry->debit ?? 0);
        $credit = (float)($entry->credit ?? 0);

        // ✅ **Show balance after applying the first transaction impact**
        $supplierRunningBalance += ($debit - $credit);

        echo "
        <tr style='border: 1px solid #666;'>
            <td>".ucfirst($entry->source)."</td>
            <td>".date('d-m-Y', strtotime($entry->date))."</td>
            <td>{$entry->reference}</td>
            <td>".ucfirst($entry->supplier_payment_type)."</td>
            <td>{$entry->cheque_details}</td>
            <td class='right-align'>" . number_format($debit, 2) . "</td>
            <td class='right-align'>" . number_format($credit, 2) . "</td>
            <td class='right-align'>" . number_format($supplierRunningBalance, 2) . "</td>
        </tr>";

        $supplierTotalDebit += $debit;
        $supplierTotalCredit += $credit;
    }

    echo "
    <tr class='table-warning' style='border: 1px solid #666;'>
        <td colspan='5' class='text-right'><strong>Total for {$supplierName}</strong></td>
        <td class='right-align'><strong>" . number_format($supplierTotalDebit, 2) . "</strong></td>
        <td class='right-align'><strong>" . number_format($supplierTotalCredit, 2) . "</strong></td>
        <td class='right-align'><strong>" . number_format($supplierRunningBalance, 2) . "</strong></td>
    </tr>";

    $grandTotalDebit += $supplierTotalDebit;
    $grandTotalCredit += $supplierTotalCredit;
    $grandTotalBalance += $supplierRunningBalance; // Store the last supplier's running balance as the final balance
}

echo "
<tr class='table-success' style='border: 1px solid #666;'>
    <td colspan='5' class='text-right'><strong>Grand Total</strong></td>
    <td class='right-align'><strong>" . number_format($grandTotalDebit, 2) . "</strong></td>
    <td class='right-align'><strong>" . number_format($grandTotalCredit, 2) . "</strong></td>
    <td class='right-align'><strong>" . number_format($grandTotalBalance, 2) . "</strong></td>
</tr>";
?>
</tbody>


                    </table>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>
<?php include('../includes/inc_footer.php'); ?>
<script type="text/javascript" src="<?= PROJECT_URL ?>js/download.js"></script>
<?php include('../includes/inc_js.php'); ?>
<script type="text/javascript" src="<?= PROJECT_URL ?>js/plugins/floatThead/jquery.floatThead.min.js"></script>
<script type="text/javascript"
        src="<?= PROJECT_URL ?>js/plugins/floatThead/jquery.floatThead-slim.min.js"></script>
<script type="application/javascript">
    $(document).ready(function () {
        $("#print").on("click", function (e) {
            var fewSeconds = 2;
            e.preventDefault();
            $('#searchfrm').prop('target', '_blank');
            $('#searchfrm').prop('action', "<?=PROJECT_ADMIN_URL?>report/print/supplier_ledger.php?").submit();
            setTimeout(function () {
                $('#searchfrm').prop('target', "");
                $('#searchfrm').prop('action', "");
            }, fewSeconds * 1000);
        });
        $('table.demo1').floatThead({
            position: 'fixed',
            scrollingTop: 65
        });
        $('table.demo1 thead').css('background', '#ECEFF1');
    });

    function exportTableToCSV(filename) {
        var csv = [];
        var rows = document.querySelectorAll("table.demo1 tr");

        // Variable to track if the current row is a total row
        var currentItem = "";

        // Loop through each row in the table
        for (var i = 0; i < rows.length; i++) {
            var row = [], cols = rows[i].querySelectorAll("td, th");

            if (cols.length > 0 && cols[3] && cols[3].innerText.trim().startsWith("Total for")) {
                // This is the total row, place "Total for" in the 4th column
                row.push('""', '""', '""'); // Empty for first 3 columns
                row.push('"' + cols[3].innerText.trim().replace(/"/g, '""') + '"'); // "Total for" in 4th column
                for (var j = 4; j < cols.length; j++) {
                    var totalCellValue = cols[j].innerText.trim().replace(/"/g, '""');
                    row.push('"' + totalCellValue + '"'); // Add total values to the respective columns
                }
            } else {
                // For normal rows, include all columns as usual
                for (var j = 0; j < cols.length; j++) {
                    var cellValue = cols[j].innerText.trim().replace(/"/g, '""');
                    row.push('"' + cellValue + '"');
                }
                // Track the current item name (assuming it's in column 3 - "Item Name")
                if (cols[3]) {
                    currentItem = cols[3].innerText.trim();
                }
            }

            // Push the row into the CSV array
            csv.push(row.join(","));
        }

        // Create CSV file and trigger download
        downloadCSV(csv.join("\n"), filename);
    }

    function downloadCSV(csv, filename) {
        var csvFile;
        var downloadLink;

        // Create a Blob from the CSV data
        csvFile = new Blob([csv], { type: "text/csv" });

        // Create a link element for download
        downloadLink = document.createElement("a");

        // Set the download filename
        downloadLink.download = filename;

        // Create a link to the CSV file
        downloadLink.href = window.URL.createObjectURL(csvFile);

        // Hide the download link
        downloadLink.style.display = "none";

        // Append the link to the body
        document.body.appendChild(downloadLink);

        // Automatically click the link to trigger the download
        downloadLink.click();

        // Remove the link from the document after download
        document.body.removeChild(downloadLink);
    }


$(document).ready(function () {
    $('table.demo1').floatThead({
        position: 'fixed',
        scrollingTop: 65 // Adjust this value based on your layout (e.g., height of the navbar)
    });

    // Optional: Set a background color for better visibility
    $('table.demo1 thead').css('background', '#ECEFF1');
});
</script>
</body>
</html>
