<?php
include("../../classes/manager.class.php");
//ini_set('display_errors', 1);
//error_reporting(E_ALL);
$m = new Manager();
$output = '';
$datefrom = "";
$dateto = "";
$bank_name = "";


if (!isset($_SESSION['sess_userid'])) {
    header("Location: " . PROJECT_ADMIN_URL);
    exit();
}
extract($_REQUEST);
if ($datefrom == "") {
    $datefrom = date('Y-m-d', strtotime("-30 days"));
} else {
    $datefrom = date("Y-m-d", strtotime($datefrom));
}
if ($dateto == "") {
    $dateto = date('Y-m-d');
} else {
    $dateto = date("Y-m-d", strtotime($dateto));
}
$datefrom = date("d-m-Y", strtotime($datefrom));
$dateto = date("d-m-Y", strtotime($dateto));

$qryDate = date("Y-m-d", strtotime($datefrom));
$qryTo = date("Y-m-d", strtotime($dateto));


$filterReportOpening = " WHERE DATE_FORMAT(date,'%Y-%m-%d')>='2016-01-01' and DATE_FORMAT(date,'%Y-%m-%d')<'$qryDate'";
$supplier_id = $_GET['supplier_id'] ?? 'All';

$filterReportOpening = " WHERE DATE_FORMAT(date,'%Y-%m-%d')>='2016-01-01' AND DATE_FORMAT(date,'%Y-%m-%d')<'$qryDate'";
$filterReport = " WHERE DATE_FORMAT(date,'%Y-%m-%d')>='$qryDate' AND DATE_FORMAT(date,'%Y-%m-%d')<='$qryTo'";

if (!empty($supplier_id) && $supplier_id !== "All") {
    $supplier_id = intval($supplier_id);
    $filterReportOpening .= " AND supplier_id = $supplier_id";
    $filterReport .= " AND supplier_id = $supplier_id";
}


//if (isset($bank_name) && $bank_name != 'All') {
//    $filterReport .= " AND statement_bank_id ='$bank_name'";
//	$filterReportOpening .= " AND statement_bank_id ='$bank_name'";
//}
//$filterReport .= " ORDER BY date";
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <?php include('../includes/inc_head.php'); ?>
</head>
<body>
<!-- Start Page Loading -->
<div id="loader-wrapper">
    <div id="loader"></div>
    <div class="loader-section section-left"></div>
    <div class="loader-section section-right"></div>
</div>
<!-- End Page Loading -->
<div id="container">
    <?php include('../includes/inc_top.php'); ?>
    <div class="row">
        <div class="col s12 m12">
            <div class="">
                <h3>Cash Ledger</h3>
            </div>
            <script>
                $(function () {
                    $('#datepicker').pickadate({
                        format: 'dd-mm-yyyy',
                        selectMonths: true,
                        selectYears: true, // Creates a dropdown to control year
                    });
                    $('#datepicker1').pickadate({
                        format: 'dd-mm-yyyy',
                        selectMonths: true,
                        selectYears: true, // Creates a dropdown to control year
                    });
                });
            </script>
            <form action="" method="get" name="search"
                  id="searchfrm">
                <table class="table">
                    <tr>
                        <td class="col s4">Date From<br>
                            <input type="text" name="datefrom" id="datepicker"
                                   placeholder="Date From"
                                   value="<?= $datefrom ?>" class="form-control"/>
                            <input type="hidden" name="view" id="view" class="form-control"/>
                        </td>
                        <td class="col s4"> Date To<br>
                            <input type="text" name="dateto" id="datepicker1"
                                   placeholder="Date To"
                                   value="<?= $dateto ?>" class="form-control"/>
                        </td>
                        <td class="col s4">Supplier<br>
                            <?php $suppliers = SupplierSetup::GetSupplierSetupList(); ?>
                            <select class="form-control" id="supplier_id" name="supplier_id">
                                <option>All</option>
                                <?php
                                if ($suppliers) {
                                    foreach ($suppliers as $supplier) {
                                        echo '<option ';
                                        if ($supplier->id == $supplier_id) echo 'selected';
                                        echo ' value="' . $supplier->id . '">' . $supplier->name . '</option>';
                                    }
                                }
                                ?>
                            </select><br/>
                        </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
                                    id="print"
                                    class="btn waves-effect waves-light"
                                    style="float:left; margin-left: 15px;">
                                    Print
                                </button>
                            <?php } ?>
                        </td>
                    </tr>
                </table>
            </form>
            <hr><?php
            if (isset($_GET['view'])) {
                ?>
                <div id="floatThead" class="section">
                    <table class="striped demo1 bordered">
                        <thead>
                        <tr>
                            <th>Date</th>
                            <th>Supplier</th>
                            <th>Sub Category</th>
                            <th>Description</th>
                            <th style="text-align:right;">Credit</th>
                            <th style="text-align:right;">Debit</th>
                            <th style="text-align:right;">Balance</th>
                        </tr>
                        </thead>

                        <tbody>
                        <?php
                        $qryOpening = PettyCashIn::GetPettyCashOpeningBalance($filterReportOpening);
                        $balanceOpening = 0;
                        $balance = 0;
                        $totalInflow = 0;
                        $totalOutflow = 0;

                        if ($qryOpening) {
                            foreach ($qryOpening as $qryOpeningRow) {
                                if ($qryOpeningRow->type == 'outflow') {
                                    $balanceOpening -= $qryOpeningRow->amount;
                                } else {
                                    $balanceOpening += $qryOpeningRow->amount;
                                }
                            }
                            $balance = $balanceOpening;
                        }

                        // Opening balance row
                        echo "<tr style='font-weight:bold; background:#f2f2f2;'>
                                <td colspan='2'><strong>Opening Balance as of " . date('d M Y', strtotime($qryDate)) . "</strong></td>
                                <td>Opening Balance</td>
                                <td style='text-align:right;'></td>
                                <td style='text-align:right;'></td>
                                <td style='text-align:right;'>" . number_format($balance, 2) . "</td>
                              </tr>";

                        $qry = PettyCashIn::GetPettyCashLedgerData($filterReport);
                        if ($qry) {
                            foreach ($qry as $qery) {
                                $type         = $qery->type;
                                $amount       = $qery->amount;
                                $desc         = $qery->description;
                                $supplier     = $qery->supplier_name;
                                $subcategory  = $qery->category_name;
                                $bank         = $qery->bank_name;
                                $cheque_no    = $qery->chq_no;
                                $date         = date('d - M - Y', strtotime($qery->date));

                                // NEW: source_type handling (bank / other)
                                $sourceType   = isset($qery->source_type) && $qery->source_type ? $qery->source_type : 'bank';

                                if ($type == 'inflow') {
                                    $balance += $amount;
                                    $totalInflow += $amount;
                                } else {
                                    $balance -= $amount;
                                    $totalOutflow += $amount;
                                }

                                // Updated: show Bank/Cheque only for inflow + bank,
                                // show "Other Source" for inflow + other, nothing for outflow
                                if ($type == 'inflow') {
    if ($sourceType === 'bank') {
        // Inflow from bank
        $bankChequeInfo = ($bank || $cheque_no)
            ? "Bank: {$bank}<br>Cheque No: {$cheque_no}"
            : 'Bank';
    } else {
        // Inflow from "other" → show description as the source
        if (!empty($desc)) {
            $bankChequeInfo = $desc;
        } else {
            $bankChequeInfo = 'Other Source';
        }
    }
} else {
    // Outflow rows: no credit-side source text
    $bankChequeInfo = '';
}


                                echo "<tr>
                                        <td>{$date}</td>
                                        <td>{$supplier}</td>
                                        <td>{$subcategory}</td>
                                        <td>{$desc}</td>
                                        <td>{$bankChequeInfo}</td>
                                        <td style='text-align:right;'>" . ($type == 'inflow' ? number_format($amount, 2) : '') . "</td>
                                        <td style='text-align:right;'>" . ($type == 'outflow' ? number_format($amount, 2) : '') . "</td>
                                        <td style='text-align:right;'>" . number_format($balance, 2) . "</td>
                                      </tr>";
                            }

                            // Totals row
                            echo "<tr style='font-weight:bold; background:#eee;'>
                                    <td colspan='5' style='text-align:right;'>Total</td>
                                    <td style='text-align:right;'>" . number_format($totalInflow, 2) . "</td>
                                    <td style='text-align:right;'>" . number_format($totalOutflow, 2) . "</td>
                                    <td></td>
                                  </tr>";
                        } else {
                            echo "<tr><td colspan='8' style='text-align:center;'>No transactions found</td></tr>";
                        }

                        ?>
                        </tbody>


                    </table>
                </div>
                <?php

            } // close view
            ?>
        </div>
    </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 () {
        // initialize
        $('#customer_name').material_select();

        // setup listener for custom event to re-initialize on change
        $('#customer_name').on('contentChanged', function () {
            $(this).material_select();
        });
        $('#cat_name').on('change', function () {
            $('body.container').block({message: 'Loading...'});
            $.get('getFilterCustomersAll.php?id=' + $(this).val(), function (data) {
                $("#customer_name").empty();
                $("#customer_name").append(data);
                $('body.container').unblock();
                $('#customer_name').trigger('contentChanged');
            });
        });
        $("#print").on("click", function (e) {
            var fewSeconds = 2;
            e.preventDefault();
            $('#searchfrm').prop('target', '_blank');
            $('#searchfrm').prop('action', "<?=PROJECT_ADMIN_URL?>report/print/petty_cash_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');
    });
</script>
</body>
</html>
