<?php
include("../../classes/manager.class.php");
//ini_set('display_errors', 1);
//error_reporting(E_ALL);
$m = new Manager();
$output = '';
$datefrom = "";
$dateto = "";
$customer_name = "";
$product_id = "";
$totalDiscount = 0;
$totaladdDiscount = 0;
$productQtyTotal = 0;
$costPriceTotal = 0;
$unitPriceTotal = 0;
$PayTotal = 0;
$BalTotal = 0;
$mainCat = "";
$catName = "";
$filterReportOpening = "";

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

extract($_REQUEST);

// Default dates
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));
}

// Keep display format dd-mm-YYYY
$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));

// Base filter (per invoice)
$filterReport = "
    WHERE DATE_FORMAT(inv.create_date,'%Y-%m-%d') >= '$qryDate'
      AND DATE_FORMAT(inv.create_date,'%Y-%m-%d') <= '$qryTo'
      AND LOWER(TRIM(inv.status)) <> 'cancel'
";

// Category & customer filter
if (isset($cat_name) && $cat_name != 'All') {
    if (isset($customer_name) && $customer_name != 'All') {
        $filterReport .= " AND inv.customer_id ='$customer_name'";
    } else {
        $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);
            $filterReport .= " AND inv.customer_id IN (".$customers.")";
        }
    }
}

if (isset($customer_name) && $customer_name != 'All') {
    $filterReport .= " AND inv.customer_id ='$customer_name'";
}

if (isset($cat_name) && $cat_name != 'All') {
    if (isset($customer_name) && $customer_name != 'All') {
        $filterReportOpening .= " AND inv.customer_id ='$customer_name'";
    } else {
        if (!empty($customers)) {
            $filterReportOpening .= " AND inv.customer_id IN (".$customers.")";
        }
    }
}

// Status filter
if (isset($status) && $status != 'All') {

    if ($status == 'Pending') {
        // Pending dropdown should include both Pending and Partial Paid
        // LOWER(TRIM()) handles values like Pending, pending, Partial Paid, partial paid
        $filterReport .= " AND LOWER(TRIM(inv.status)) IN ('pending', 'partial paid')";
    } elseif ($status == 'Paid') {
        // Paid should only include paid invoices
        $filterReport .= " AND LOWER(TRIM(inv.status)) = 'paid'";
    } else {
        $filterReport .= " AND LOWER(TRIM(inv.status)) = '" . strtolower(trim($status)) . "'";
    }

    $filterReport .= " GROUP BY inv.id";
} else {
    $filterReport .= " GROUP BY inv.id";
}
$filterReport .= " ORDER BY inv.id ";

// Expense filter (seems unused here but keeping original line)
$filterExpenseReport = " AS ex RIGHT JOIN " . TABLE_EXPENSECATEGORYSETUP . " AS exCat ON ex.category_id = exCat.id WHERE DATE_FORMAT(lastupdated,'%Y-%m-%d')>='$qryDate' and DATE_FORMAT(lastupdated,'%Y-%m-%d')<='$qryTo' ";
$filterExpenseReport .= " ORDER BY exCat.parent_id";
?>
<!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>Invoice Status 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">
                <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"/>
                            <input type="hidden" name="view" id="view" 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">Category<br>
                            <?php
                            $catFilter = " JOIN customer_setup ON customer_category.id = customer_setup.category_id GROUP BY catid ORDER BY customer_category.name";
                            $categories = CustomerCategorySetup::GetCustomerCategorySetupList($catFilter);
                            ?>
                            <select class="form-control" required id="cat_name" name="cat_name">
                                <option>All</option>
                                <?php
                                if ($categories) {
                                    foreach ($categories AS $categoriesRow) {
                                        echo '<option ';
                                        if ($categoriesRow->catid == $cat_name) {
                                            echo 'selected';
                                        }
                                        echo ' value="' . $categoriesRow->catid . '" >' . $categoriesRow->catname . '</option>';
                                    }
                                }
                                ?>
                            </select><br/>
                        </td>
                        <td class="col s4">Customer<br>
                            <?php
                            $customersfilter = " WHERE status = 'active' ORDER BY name";
                            $customers = CustomerSetup::GetCustomerSetupList($customersfilter);
                            ?>
                            <select class="form-control" required id="customer_name" name="customer_name">
                                <option>All</option>
                                <?php
                                if ($customers) {
                                    foreach ($customers AS $customersRow) {
                                        echo '<option ';
                                        if ($customersRow->id == $customer_name) {
                                            echo 'selected';
                                        }
                                        echo ' value="' . $customersRow->id . '" >' . $customersRow->name . '</option>';
                                    }
                                }
                                ?>
                            </select><br/>
                        </td>
                        <td class="col s4"> Status<br>
                            <select id="status" name="status" class="form-control">
                                <option>All</option>
                                <option <?php if ($status == "Paid") { echo 'selected'; } ?> value="Paid">Paid</option>
                                <option <?php if ($status == "Pending") { echo 'selected'; } ?> value="Pending">Pending / Partial Paid</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
                                    onclick="exportTableToCSV('invoice-<?= 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 (isset($_GET['view'])) {
                ?>
                <div id="floatThead" class="section">
                    <table class="striped demo1 bordered">
                        <thead>
                        <tr style="border: 1px solid #666;">
                            <th>S.No</th>
                            <th>Date</th>
                            <th>Invoice #</th>
                            <th>Customer</th>
                            <th>Status</th>
                            <th>Total Amount</th>
                            <!-- If you ever want to show discount columns again, you can add them back here -->
                            <th>Payments</th>
                            <th>Balance</th>
                        </tr>
                        </thead>
                        <tbody>
                        <?php
                        $qry = Invoice::GetInvoiceReportList($filterReport);
                        if ($qry) {
                            $counter           = 1;
                            $totalAmountSum    = 0;
                            $totalPaymentSum   = 0;
                            $totalBalanceSum   = 0;

                            foreach ($qry as $qery) {

                                // Net invoice total (already includes discounts, tax, advance tax)
                                $invoiceNetTotal = $qery->invoice_total_amount;

                                // Total payments against THIS invoice (non-cancelled)
                                $pyBalance = $qery->payment_received;

                                // Per-invoice balance / overpayment (no carry-forward)
                                $totBal = $invoiceNetTotal - $pyBalance;

                                // Totals
                                $totalAmountSum  += $invoiceNetTotal;
                                $totalPaymentSum += $pyBalance;
                                $totalBalanceSum += $totBal;
                                ?>
                                <tr style="border: 1px solid #666;">
                                    <td><?= $counter++; ?></td>
                                    <td><?= date('Y-m-d h:i A', strtotime($qery->create_date)); ?></td>
                                    <td><?= $qery->code; ?></td>
                                    <td><?= $qery->customer_name; ?></td>
                                    <td>
                                        <?= ($pyBalance > 0 && $pyBalance < $invoiceNetTotal)
                                            ? "Partial Paid"
                                            : $qery->invoice_status; ?>
                                    </td>
                                    <td><?= number_format($invoiceNetTotal, 2); ?></td>
                                    <td><?= number_format($pyBalance, 2); ?></td>
                                    <td><?= number_format($totBal, 2); ?></td>
                                </tr>
                                <?php
                            }
                            ?>
                            <tr>
                                <th colspan="5" style="text-align: right; border: 1px solid #000;">Total</th>
                                <th style="border: 1px solid #666;"><?= number_format($totalAmountSum, 2); ?></th>
                                <th style="border: 1px solid #666;"><?= number_format($totalPaymentSum, 2); ?></th>
                                <th style="border: 1px solid #666;"><?= number_format($totalBalanceSum, 2); ?></th>
                            </tr>
                            <?php
                        }
                        ?>
                        </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 () {
        $("#print").on("click", function (e) {
            var fewSeconds = 2;
            e.preventDefault();
            $('#searchfrm').prop('target', '_blank');
            $('#searchfrm').prop('action', "<?=PROJECT_ADMIN_URL?>report/print/invoice_status.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);
        });
        $('#customer_name').material_select();
        $('#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(){
                if($(this).val() == parseInt(customername)){
                    $(this).attr('selected', true);
                }
            });
            $('#customer_name').trigger('contentChanged');
        }
    });
</script>
</body>
</html>
