<?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 = "";
if (!isset($_SESSION['sess_userid'])) {
    header("Location: " . PROJECT_ADMIN_URL);
    exit();
}
extract($_REQUEST);
if ($datefrom == "") {
    $datefrom = date('Y-m-d', strtotime("-180 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));

//$filterReport = " LEFT JOIN " . TABLE_INVOICE_PRODUCT . " AS invPr ON inv.id = invPr.invoice_id INNER JOIN " . TABLE_CUSTOMERSETUP . " AS cs ON inv.customer_id = cs.id WHERE DATE_FORMAT(inv.create_date,'%Y-%m-%d')>='$qryDate' and DATE_FORMAT(inv.create_date,'%Y-%m-%d')<='$qryTo' AND cs.is_mart = 0 ";
$filterReport = " LEFT JOIN " . TABLE_INVOICE_PRODUCT . " AS invPr ON inv.id = invPr.invoice_id INNER JOIN " . TABLE_CUSTOMERSETUP . " AS cs ON inv.customer_id = cs.id WHERE DATE_FORMAT(inv.create_date,'%Y-%m-%d')>='$qryDate' and DATE_FORMAT(inv.create_date,'%Y-%m-%d')<='$qryTo' and inv.status <> 'Cancel' ";

// ================== Apply Cat Type Filter ==================
if (isset($cat_type) && $cat_type != 'All') {
    if ($cat_type == '0') {
        $filterReport .= " AND cs.is_mart = 0 ";  // Wholesaler
    } elseif ($cat_type == '1') {
        $filterReport .= " AND cs.is_mart = 1 ";  // Local Mart
    }
}

// ================== Apply Category Filter ==================
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);
    $filterReport .= " AND inv.customer_id IN ($customers)";
}

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

// ================== Apply Status Filter ==================
if (isset($status) && $status != 'All') {
    $filterReport .= " AND inv.status ='$status'";
}

$filterReport .= " GROUP BY inv.id";
$filterReport .= " ORDER BY inv.id ";

$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 s3">Type<br>
                            <select class="form-control" required id="cat_type"
                                    name="cat_type">
                                <option>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 s3">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 value="All" <?= ($cat_name == 'All') ? 'selected' : '' ?>>All</option>
    <?php
    if ($categories) {
        foreach ($categories AS $categoriesRow) {
            echo '<option value="' . $categoriesRow->catid . '"';
            if ($categoriesRow->catid == $cat_name) {
                echo ' selected';
            }
            echo '>' . $categoriesRow->catname . ' (' . $count . ')</option>';
            $count++; // Increment counter
        }
    }
    ?>
</select>
<br/>
                        </td>
                        <td class="col s3">Customer<br>
                            <?php
                            //$customersfilter = " WHERE status = 'active' AND is_mart = 0";
                            $customersfilter = " WHERE status = 'active'";
                            $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 s3"> 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>Price</th>
                            <?php if ((PROJECT_DISCOUNT == 1 || !empty($discount_price))) { ?>
                                <th>Discount</th>
                                <th>Add. Discount</th>
                            <?php } ?>
                            <th>Sub Total</th>
                            <th>Payments</th>
                            <th>Balance</th>
                          	<th>Days Passed</th> <!-- New Column Added -->
                        </tr>
                        </thead>
                        <tbody>
                        <?php
                        if ($customer_name != 'All' && $customer_name != '') {
                            $customer = CustomerSetup::GetCustomerSetupById($customer_name);
                            echo "<h2 style='text-align: center;'>" . $customer->name . "</h2>";
                        }
              	
                        $qry = Invoice::GetInvoiceReportList($filterReport);
                        if ($qry) {
                            $counter = 1;
                            foreach ($qry as $qery) { 
                          $invoiceDate = strtotime($qery->create_date);
                                $currentDate = strtotime(date('Y-m-d'));
                                $daysPassed = floor(($currentDate - $invoiceDate) / (60 * 60 * 24));
                          ?>
                                <tr style="border: 1px solid #666;">
                                    <td><?= $counter; ?></td>
                                    <td><?php echo date('Y-m-d h:i A', strtotime($qery->create_date)); ?></td>
                                    <?php
                                    $customer = CustomerSetup::GetCustomerSetupById($qery->customer_id);
                                    $salesPerson = User_setup::GetUserSetupId($qery->sales_person_id);
                                    $discount_price = $qery->discount_price;
                                    $add_discount_price = intval($qery->add_discount_price);
                                    ?>
                                    <td><?php echo $qery->code; ?></td>
                                    <td><?php echo $customer->name; ?></td>
                                    <?php
                                    if ($product_id == 'All' || $product_id == '') {
//                                        $productsNames = array();
                                        $productsQtys = 0;
                                        $productsUnitCostPrice = 0;
                                        $productsUnitSalePrice = 0;

                                        $filterProducts = " WHERE invoice_id = '$qery->invoice_id'";
                                        $productSetup = Invoice::GetInvoiceProducts($filterProducts);
                                        if ($productSetup) {
                                            foreach ($productSetup as $productSetupRows) {
                                                //$product = ProductSetup::GetProductSetupById($productSetupRows->product_id);
                                                //$productsNames[] = $product->name;
                                                $productsQtys += $productSetupRows->product_qty;
                                                $productsUnitCostPrice += number_format(($productSetupRows->product_qty * $productSetupRows->unit_cost_price), 2, '.', '');
                                                if ($qery->is_mart == 0) {
                                                    $productsUnitSalePrice += number_format(($productSetupRows->product_qty * $productSetupRows->unit_sale_price), 2, '.', '');
                                                } else {
                                                    $productsUnitSalePrice += number_format(($productSetupRows->product_qty * $productSetupRows->unit_sale_price), 2, '.', '');
                                                }
                                            }
                                        }
                                        $subtotal = $productsUnitSalePrice - $productsUnitCostPrice;
                                        $subtotal -= $discount_price;
                                        $totalDiscount += $discount_price;
                                        $totaladdDiscount += $add_discount_price;

                                        $productQtyTotal += $productsQtys;
                                        $costPriceTotal += $productsUnitCostPrice;
                                        $unitPriceTotal += $productsUnitSalePrice;

                                        $filterPayment = " WHERE invoice_reference_code = '$qery->invoice_id' AND status <> 'Cancel'";
                                        $paymentData = Payment::GetPaymentList($filterPayment);
                                        $pyBalance = 0;
                                        foreach($paymentData AS $paymentDataRow){
                                            $pyBalance += $paymentDataRow->amount;
                                        }
                                        $PayTotal += $pyBalance;
                                        $totBal = ($productsUnitSalePrice - $discount_price - $add_discount_price) - $pyBalance;
                                        $BalTotal += $totBal;
                                        ?>
                                        <td><?php echo ($pyBalance<$qery->total_amount && $pyBalance!=0)?"Partial Paid":$qery->status; ?></td>
                                        <!-- <td><?php //echo $qery->status; ?></td> -->
                                        <td><?php echo number_format(($productsUnitSalePrice), 0, '.', ''); ?></td>
                                        <td><?php echo number_format(($discount_price), 0, '.', ''); ?></td>
                                        <td><?php echo number_format(($add_discount_price), 0, '.', ''); ?></td>
                                        <td><?php echo number_format((($productsUnitSalePrice - $discount_price - $add_discount_price)), 0, '.', ''); ?></td>
                                        <td><?php echo number_format(($pyBalance), 0, '.', ''); ?></td>
                                        <td><?php echo number_format(($totBal), 0, '.', ''); ?></td>
                                  		<td><?php echo $daysPassed; ?></td>
                                    <?php } ?>
                                </tr>
                                <?php
                                $counter++;
                            }
                        }
                        ?>
                        <tr>

                            <th colspan="5" style="text-align: right; border: 1px solid #000;">
                                Total
                            </th>
                            <th style="border: 1px solid #666;"><?= $unitPriceTotal ?></th>
                            <?php if ((PROJECT_DISCOUNT == 1 || $discount_price != 0)) { ?>
                                <th style="border: 1px solid #666;"><?= number_format(($totalDiscount), 0, '.', '') ?></th>
                                <th style="border: 1px solid #666;"><?= number_format(($totaladdDiscount), 0, '.', '') ?></th>
                            <?php } ?>
                            <th style="border: 1px solid #666;"><?= number_format(($unitPriceTotal - $totalDiscount), 0, '.', '') ?></th>
                            <th style="border: 1px solid #666;"><?= number_format($PayTotal, 0, '.', '') ?></th>
                            <th style="border: 1px solid #666;"><?= number_format($BalTotal, 0, '.', '') ?></th>
                          	<th>-</th>
                        </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 () {
        $("#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');

// Load Categories Based on Cat Type
function loadCategories(catType, selectedCategory = null) {
    $('body.container').block({ message: 'Loading...' });

    $.get('getFilterCategories.php?cat_type=' + catType, function (data) {
        $("#cat_name").empty().append(data).trigger('contentChanged');
        
        // Set the correct category AFTER data is loaded
        if (selectedCategory) {
            $('#cat_name').val(selectedCategory).trigger('contentChanged');
        }

        $('body.container').unblock();
    });
}

// Load Customers Based on Both Category and Cat Type
function loadCustomers(categoryId, catType, data2) {
    $('body.container').block({message: 'Loading...'});

    $.get('getFilterCustomersAllCat.php?id=' + categoryId + '&cat_type=' + catType + '&cus_id=' + data2, function (data) {
        $("#customer_name").empty().append(data).trigger('contentChanged');
        $('body.container').unblock();
    });
}

// Trigger Category Load When Cat Type Changes
$('#cat_type').on('change', function () {
    var selectedCatType = $(this).val();
    loadCategories(selectedCatType); // Refresh categories when cat type changes
});

// Trigger Customer Load When Category or Cat Type Changes
$('#cat_name, #cat_type').on('change', function () {
    var selectedCatType = $('#cat_type').val();
    var selectedCat = $('#cat_name').val();
    loadCustomers(selectedCat, selectedCatType, 0);
});

// Initialize Material Select After Data Load
$('#cat_name, #customer_name').on('contentChanged', function () {
    $(this).material_select();
});

// Initial Load for Selected Category and Customer
var selectedCatType = $('#cat_type').val();
var selectedCat = "<?= $cat_name ?>"; // Correct value now included
var customername = "<?= $customer_name ?>";

// Load categories with selected category retained
if (selectedCatType !== '') {
    loadCategories(selectedCatType, selectedCat);  // Load categories with correct selected value
}

if (selectedCat !== '') {
    loadCustomers(selectedCat, selectedCatType, customername); // Load customers on page load
}


    });
  
</script>
</body>
</html>