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

$m = new Manager();
$output = '';

$datefrom = "";
$dateto = "";
$customer_name = "All";
$cat_type = "All";
$cat_name = "All";
$catType = "";

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));

/* -------- Same filter logic pattern (type/category/customer) -------- */
if (isset($cat_type) && $cat_type == 'All') {
    if (isset($cat_name) && $cat_name != 'All' && $cat_name != '') {
        $cat = CustomerCategorySetup::GetCustomerCategorySetupById($cat_name);
        $filterCat = " WHERE category_id = '$cat->id'";
        $cust = CustomerSetup::GetCustomerSetupList($filterCat);

        $custArray = array();
        if ($cust) {
            foreach ($cust as $custRow) {
                $custArray[] = $custRow->id;
            }
        }

        if (!empty($custArray)) {
            $customers = implode(',', $custArray);
            // ✅ for this report filter is on cs.id
            $catType .= " AND cs.id IN ($customers)";
        } else {
            $catType .= " AND cs.id IN (0)";
        }
    }
} else {
    // 0 wholesaler, 1 local mart
    $catType .= " AND cs.is_mart = '$cat_type'";
}

/* -------- Fetch report only when Search clicked -------- */
$rows = false;
if (isset($_GET['search'])) {
    $rows = Invoice::GetCustomerBalanceSummaryReport($qryTo, $catType, $customer_name);
}

/* Categories dropdown */
$categories = CustomerCategorySetup::GetCustomerCategorySetupList(" WHERE 1=1 ORDER BY name ASC ");
?>
<!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>Customer Balance Summary Report</h3>
            </div>

            <script>
                $(function () {
                    $('#datepicker').pickadate({
                        format: 'dd-mm-yyyy',
                        selectMonths: true,
                        selectYears: true,
                    });
                    $('#datepicker1').pickadate({
                        format: 'dd-mm-yyyy',
                        selectMonths: true,
                        selectYears: true,
                    });
                });
            </script>

            <form action="" method="get" name="search" id="searchfrm">
                <input type="hidden" name="search" value="1">

                <table class="table">
                    <tr>
                        <td class="col s6">Date From<br>
                            <input type="text" name="datefrom" id="datepicker"
                                   placeholder="Date From"
                                   value="<?= $datefrom ?>" class="form-control"/>
                        </td>
                        <td class="col s6">Date To<br>
                            <input type="text" name="dateto" id="datepicker1"
                                   placeholder="Date To"
                                   value="<?= $dateto ?>" class="form-control"/>
                        </td>
                    </tr>

                    <tr>
                        <td class="col s4">Type<br>
                            <select class="form-control" required id="cat_type" name="cat_type">
                                <option value="All" <?= ($cat_type == 'All') ? 'selected' : '' ?>>All</option>
                                <option value="0" <?= ($cat_type == '0') ? 'selected' : '' ?>>Wholesaler</option>
                                <option value="1" <?= ($cat_type == '1') ? 'selected' : '' ?>>Local Mart</option>
                            </select>
                        </td>

                        <td class="col s4">Category<br>
                            <select class="form-control" id="cat_name" name="cat_name">
                                <option value="All" <?= ($cat_name == 'All') ? 'selected' : '' ?>>All</option>
                                <?php
                                if ($categories) {
                                    foreach ($categories as $cat) {
                                        ?>
                                        <option value="<?= $cat->id ?>" <?= ($cat_name == $cat->id) ? 'selected' : '' ?>>
                                            <?= $cat->name ?>
                                        </option>
                                        <?php
                                    }
                                }
                                ?>
                            </select>
                        </td>

                        <td class="col s4">Customer<br>
                            <select class="form-control" id="customer_name" name="customer_name">
                                <option value="All">All</option>
                            </select>
                        </td>
                    </tr>

                    <tr>
                        <td colspan="3" class="col s12">
                            <button type="submit" class="btn waves-effect waves-light" style="float:left;">
                                Search
                            </button>

                            <?php if (isset($_GET['search']) && $rows) { ?>
                                <button
                                    onclick="exportTableToCSV('customer-balance-summary-<?= date('d-m-Y-h-i-a') ?>.csv')"
                                    type="button"
                                    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 (isset($_GET['search'])) { ?>
                <div id="floatThead" class="section">
                    <table class="striped demo1 bordered">
                        <thead>
                        <tr style="border: 1px solid #666;">
                            <th>S.No</th>
                            <th>Customer</th>
                            <th>Last Invoice Date</th>
                            <th>Last Payment Date</th>
                            <th class="right-align">Last Payment Amount</th>
                            <th class="right-align">Remaining Balance</th>
                        </tr>
                        </thead>
                        <tbody>
                        <?php
                        $counter = 1;
                        $grandBalance = 0;

                        if ($rows) {
                            foreach ($rows as $r) {

                                $lastInv = (!empty($r->last_invoice_date)) ? date('d-m-Y', strtotime($r->last_invoice_date)) : '-';
                                $lastPay = (!empty($r->last_payment_date)) ? date('d-m-Y', strtotime($r->last_payment_date)) : '-';
                                $lastPayAmt = (!empty($r->last_payment_amount)) ? (float)$r->last_payment_amount : 0;

                                $bal = (float)$r->remaining_balance;
                                $grandBalance += $bal;

                                echo "<tr style='border: 1px solid #666;'>
                                        <td>{$counter}</td>
                                        <td>{$r->customer_name}</td>
                                        <td>{$lastInv}</td>
                                        <td>{$lastPay}</td>
                                        <td class='right-align'>" . number_format($lastPayAmt, 2) . "</td>
                                        <td class='right-align'>" . number_format($bal, 2) . "</td>
                                      </tr>";
                                $counter++;
                            }

                            echo "<tr style='font-weight: bold; background-color: #f1f1f1; border: 1px solid #666;'>
                                    <td colspan='5' style='text-align: right;'>Grand Total</td>
                                    <td class='right-align'>" . number_format($grandBalance, 2) . "</td>
                                  </tr>";
                        } else {
                            echo "<tr><td colspan='6' style='text-align:center; padding:12px;'>No record found.</td></tr>";
                        }
                        ?>
                        </tbody>
                    </table>
                </div>
            <?php } ?>

        </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 () {

        // Load customer dropdown by category (same helper)
        function loadCustomers(catId, cusId){
            $('body.container').block({message: 'Loading...'});
            $.get('getFilterCustomersAll.php?id=' + catId + '&cus_id=' + cusId, function (data) {
                $("#customer_name").empty();
                $("#customer_name").append(data);
                $('body.container').unblock();
                $('#customer_name').trigger('contentChanged');
            });
        }

        // initialize material select
        $('#customer_name').material_select();
        $('#customer_name').on('contentChanged', function () { $(this).material_select(); });

        var catname = $('#cat_name').val();
        var customername = "<?= $customer_name ?>";

        if (catname != '') {
            loadCustomers(catname, customername);
        }

        $('#cat_name').on('change', function () {
            loadCustomers($(this).val(), 0);
        });

        $("#print").on("click", function (e) {
            var fewSeconds = 2;
            e.preventDefault();
            $('#searchfrm').prop('target', '_blank');
            $('#searchfrm').prop('action', "<?=PROJECT_ADMIN_URL?>report/print/customer_balance_summary_print.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>