<?php
include("../../classes/manager.class.php");
//include("../../classes/invoice.class.php"); // Added Invoice class for getLedgerReport
ini_set('display_errors', 1);
error_reporting(E_ALL);
$m = new Manager();
$output = '';
$datefrom = "";
$dateto = "";
$customer_name = "";
$balanceAmount = 0;
$totalCreditAmount = 0;
$totalDebitAmount = 0;
$cat_type = "";
$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));
//$catType = ($cat_type === '0') ? 'Wholesaler' : (($cat_type === '1') ? 'Local Mart' : 'All');

if (isset($cat_type) && $cat_type == 'All') {
    if (isset($cat_name) && $cat_name != 'All') {
        $cat = CustomerCategorySetup::GetCustomerCategorySetupById($cat_name);
        $filterCat = " WHERE category_id = '$cat->id'";
        $cust = CustomerSetup::GetCustomerSetupList($filterCat);
        $custArray = array();
        foreach ($cust AS $custRow) {
            $custArray[] = $custRow->id;
        }
        $customers = implode(',', $custArray);
        $catType .= " AND inv.customer_id IN ($customers)";
    }
} else {
    $catType .= " AND cs.is_mart = '$cat_type'";
}


// Check if the Search button was clicked
$reportData = [];  // Initialize report data as empty
$openingBalanceData = [];
$transactionData = [];

if (isset($_GET['search'])) {
    // Only fetch data when the Search button is clicked
    $reportData = Invoice::getLedgerReport($qryDate, $qryTo, $catType);

    $openingBalanceData = $reportData['opening_balance'] ?? [];
    $transactionData = $reportData['transactions'] ?? [];
}


?>
<!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 Type Ledger 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>
        </tr>
        <tr>
            <td colspan="2" class="col s12">
                <button type="submit" class="btn waves-effect waves-light"
                        style="float:left;">
                    Search
                </button>
                <?php if (!empty($reportData['opening_balance']) || !empty($reportData['transactions'])) { ?>
                    <button
                        onclick="exportTableToCSV('payment-<?= 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>

            <div id="floatThead" class="section">
                <table class="striped demo1 bordered">
                    <thead>
                        <tr style="border: 1px solid #666;">
                            <th>S.No</th>
                            <th>Head</th>
                            <th>Date</th>
                            <th>Reference Code</th>
                            <th>Customer</th>
                            <th>Status</th>
                            <th>Payment Type</th>
                            <th>Bank Name</th>
                            <th>CHQ Number</th>
                            <th>CHQ Date</th>
                            <th>Debit</th>
                            <th>Credit</th>
                            <th>Balance</th>
                        </tr>
                    </thead>
                     <tbody>
                    <?php
                    $grandTotalDebit = $grandTotalCredit = $grandTotalBalance = 0;
                    $counter = 1;

                    foreach ($openingBalanceData as $ob) {
                        $customerId = $ob->customer_id;
                        $customerName = $ob->customer_name;
                        $totalPayment = $ob->total_payment;
                        $totalInvoice = $ob->total_invoice;
                        $openingBalance = $ob->opening_balance;
                        $runningBalance = $openingBalance;

                        echo "<tr style='background-color: #e6e6e6; font-weight: bold; border: 1px solid #666;'>
                                <td colspan='13'>{$customerName}</td>
                              </tr>";

                        // Opening Balance Row
                        echo "<tr style='border: 1px solid #666;'>
                                <td>{$counter}</td>
                                <td>Opening Balance</td>
                                <td>-</td>
                                <td>-</td>
                                <td>{$customerName}</td>
                                <td>-</td>
                                <td>-</td>
                                <td>-</td>
                                <td>-</td>
                                <td>-</td>
                                <td>{$totalInvoice}</td>
                                <td>{$totalPayment}</td>
                                <td>{$openingBalance}</td>
                              </tr>";

                        $subtotalDebit = $totalInvoice;
                        $subtotalCredit = $totalPayment;

                        // Transactions for this customer
                        foreach ($transactionData as $transaction) {
                            if ($transaction->customer_id === $customerId) {
                                $counter++;
                                $debit = floatval($transaction->debit);
                                $credit = floatval($transaction->credit);
                                $runningBalance += (floatval($credit) - floatval($debit));

                                $subtotalDebit += floatval($debit);
                                $subtotalCredit += floatval($credit);

                                echo "<tr style='border: 1px solid #666;'>
                                        <td>{$counter}</td>
                                        <td>{$transaction->transaction_type}</td>
                                        <td>{$transaction->create_date}</td>
                                        <td>{$transaction->reference_code}</td>
                                        <td>{$customerName}</td>
                                        <td>{$transaction->status}</td>
                                        <td>{$transaction->payment_type}</td>
                                        <td>{$transaction->from_bank_name}</td>
                                        <td>{$transaction->cheque_number}</td>
                                        <td>{$transaction->cheque_date}</td>
                                        <td>{$debit}</td>
                                        <td>{$credit}</td>
                                        <td>{$runningBalance}</td>
                                    </tr>";
                            }
                        }

                        // Subtotal Row for Each Customer
                        echo "<tr style='font-weight: bold; border: 1px solid #666;'>
                                <td colspan='10' style='text-align: right;'>Subtotal for {$customerName}</td>
                                <td>{$subtotalDebit}</td>
                                <td>{$subtotalCredit}</td>
                                <td>{$runningBalance}</td>
                              </tr>";

                        $grandTotalDebit += floatval($subtotalDebit);
                        $grandTotalCredit += floatval($subtotalCredit);
                        $grandTotalBalance += floatval($runningBalance);
                    }

                    // Grand Total Row
                    echo "<tr style='font-weight: bold; background-color: #f1f1f1; border: 1px solid #666;'>
                            <td colspan='10' style='text-align: right;'>Grand Total</td>
                            <td>{$grandTotalDebit}</td>
                            <td>{$grandTotalCredit}</td>
                            <td>{$grandTotalBalance}</td>
                          </tr>";
                    ?>
                    </tbody>
                </table>
            </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 () {
        var catname = $('#cat_name').val();
        var customername = "<?=$customer_name?>";
        if(catname != ''){
            load(catname);
            $('#customer_name').each(function(){
                console.log($(this).val());
                if($(this).val() == parseInt(customername)){
                    console.log("Test "+customername);
                    $(this).attr('selected', true);
                }
            });
            $('#customer_name').trigger('contentChanged');
        }
        function load(data){
            $('body.container').block({message: 'Loading...'});
            $.get('getFilterCustomersAll.php?id=' + data, function (data) {
                $("#customer_name").empty();
                $("#customer_name").append(data);
                $('body.container').unblock();
                $('#customer_name').trigger('contentChanged');
            });
        }
        // 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');
//            });
            load($(this).val());
        });
        $("#print").on("click", function (e) {
            var fewSeconds = 2;
            e.preventDefault();
            $('#searchfrm').prop('target', '_blank');
            $('#searchfrm').prop('action', "<?=PROJECT_ADMIN_URL?>report/print/catcustledgcattype_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');
      
      					function load(data, data2){
            $('body.container').block({message: 'Loading...'});
            $.get('getFilterCustomersAll.php?id=' + data + '&cus_id=' + data2, function (data) {
                $("#customer_name").empty();
                $("#customer_name").append(data);
                $('body.container').unblock();
                $('#customer_name').trigger('contentChanged');
            });
        }

        $('#cat_name').on('change', function () {
            load($(this).val(), 0);
        });
        // initialize
        $('#customer_name').material_select();

        // setup listener for custom event to re-initialize on change
        $('#customer_name').on('contentChanged', function () {
            $(this).material_select();
        });

        var catname = $('#cat_name').val();
        var customername = "<?=$customer_name?>";
        if(catname != ''){
            load(catname, customername);
            $('#customer_name').each(function(){
                console.log($(this).val());
                if($(this).val() == parseInt(customername)){
                    console.log("Test "+customername);
                    $(this).attr('selected', true);
                }
            });
            $('#customer_name').trigger('contentChanged');
        }
      
      
    });
</script>
</body>
</html>
