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

$m = new Manager();

$output = '';
$datefrom = "";
$dateto = "";
$customer_name = "";
$cat_name = "All";
$mart_type = "All";

$totalProfitPrevious = 0;
$totalPaymentsPrevious = 0;
$costPriceTotal = 0;
$unitPriceTotal = 0;
$totalDiscount = 0;
$totalProfit = 0;
$productQtyTotal = 0;
$cartonQtyTotal = 0;
$totalPayments = 0;
$openingBalance = 0;

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

extract($_REQUEST);

// ---- Date handling ----
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));

// Default values if not set
if (!isset($customer_name)) {
    $customer_name = 'All';
}

if (!isset($cat_name)) {
    $cat_name = 'All';
}

if (!isset($mart_type)) {
    $mart_type = 'All';
}

/**
 * Build filter for main invoice query
 * - When specific customer: detail mode, one row per invoice
 * - When all customers: summary mode, one row per customer
 * - Mart / Wholesaler filter uses customer_setup.is_mart
 *      All = no filter
 *      Mart = cust.is_mart = 1
 *      Wholesaler = cust.is_mart = 0
 */

$baseWhere = " WHERE DATE_FORMAT(inv.create_date,'%Y-%m-%d') >= '$qryDate'
               AND DATE_FORMAT(inv.create_date,'%Y-%m-%d') <= '$qryTo'
               AND inv.status NOT IN('Draft', 'Cancel') ";

if ($customer_name != '' && $customer_name != 'All') {

    // DETAIL mode: single customer
    $filterReport  = " JOIN " . TABLE_CUSTOMERSETUP . " AS cust 
                          ON inv.customer_id = cust.id ";

    $filterReport .= $baseWhere;

    // Category filter
    if ($cat_name != 'All') {
        $filterReport .= " AND cust.category_id = '$cat_name'";
    }

    // Wholesaler / Mart filter
    if ($mart_type == 'Mart') {
        $filterReport .= " AND cust.is_mart = '1'";
    } elseif ($mart_type == 'Wholesaler') {
        $filterReport .= " AND cust.is_mart = '0'";
    }

    // Specific customer
    $filterReport .= " AND inv.customer_id = '$customer_name'";

    // Group by invoice
    $filterReport .= " GROUP BY inv.id ";

} else {

    // SUMMARY mode: all customers
    $filterReport  = " JOIN " . TABLE_CUSTOMERSETUP . " AS cust 
                          ON inv.customer_id = cust.id ";

    $filterReport .= $baseWhere;

    // Category filter
    if ($cat_name != 'All') {
        $filterReport .= " AND cust.category_id = '$cat_name'";
    }

    // Wholesaler / Mart filter
    if ($mart_type == 'Mart') {
        $filterReport .= " AND cust.is_mart = '1'";
    } elseif ($mart_type == 'Wholesaler') {
        $filterReport .= " AND cust.is_mart = '0'";
    }

    // Group by customer
    $filterReport .= " GROUP BY inv.customer_id ";
}

// Final order
$filterReport .= " ORDER BY cust.name, inv.customer_id, inv.create_date, inv.code ";

//echo $filterReport;
//exit;
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <?php include('../includes/inc_head.php'); ?>
</head>
<body>

<div id="container">
    <?php include('../includes/inc_top.php'); ?>

    <div class="row">
        <div class="col s12 m12">
            <div class="">
                <h3>Monthly Sale 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-lg-4">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-lg-4"> Date To<br>
                            <input type="text" name="dateto" id="datepicker1"
                                   placeholder="Date To"
                                   value="<?= $dateto ?>" class="form-control"/>
                        </td>
                    </tr>

                    <tr>
                        <td class="col-lg-4">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">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-lg-4">Customer Type<br>
                            <select class="form-control" required id="mart_type" name="mart_type">
                                <option value="All" <?php if ($mart_type == 'All') { echo 'selected'; } ?>>All</option>
                                <option value="Wholesaler" <?php if ($mart_type == 'Wholesaler') { echo 'selected'; } ?>>Wholesaler</option>
                                <option value="Mart" <?php if ($mart_type == 'Mart') { echo 'selected'; } ?>>Local Mart</option>
                            </select><br/>
                        </td>
                    </tr>

                    <tr>
                     <!--   <td class="col-lg-4">Customer<br>
                            <?php
                            $customersfilter = " WHERE status = 'active' ";

                            if ($cat_name != 'All') {
                                $customersfilter .= " AND category_id = '$cat_name' ";
                            }

                            if ($mart_type == 'Mart') {
                                $customersfilter .= " AND is_mart = '1' ";
                            } elseif ($mart_type == 'Wholesaler') {
                                $customersfilter .= " AND is_mart = '0' ";
                            }

                            $customersfilter .= " ORDER BY name ";

                            $customers = CustomerSetup::GetCustomerSetupList($customersfilter);
                            ?>

                            <select class="form-control" required id="customer_name" name="customer_name">
                                <option value="All">All</option>
                                <?php
                                if ($customers) {
                                    foreach ($customers AS $customersRow) {
                                        echo '<option value="' . $customersRow->id . '" ';
                                        if ($customersRow->id == $customer_name) {
                                            echo 'selected';
                                        }
                                        echo '>' . $customersRow->name . '</option>';
                                    }
                                }
                                ?>
                            </select><br/>
                        </td> -->

                        <td class="col-lg-4"></td>
                    </tr>

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

                            <?php if (isset($_GET['view'])) { ?>
                                <button type="button"
                                        onclick="exportTableToCSV('monthly-sale-<?= 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'])) {

                // Optional heading: show category name if filtered
                if ($cat_name != 'All') {
                    $catObj = CustomerCategorySetup::GetCustomerCategorySetupById($cat_name);
                    if (!empty($catObj)) {
                        echo '<table style="width: 100%;"><tr><th style="text-align: center;">';
                        echo "<h6 style='text-align: center;'>" . $catObj->name . " - Category</h6>";
                        echo '</th></tr></table>';
                    }
                }

                // Optional heading: show customer type
                if ($mart_type != 'All') {
                    echo '<table style="width: 100%;"><tr><th style="text-align: center;">';
                    echo "<h6 style='text-align: center;'>" . $mart_type . " Customers</h6>";
                    echo '</th></tr></table>';
                }

                // Heading for specific customer
                if ($customer_name != '' && $customer_name != 'All') {
                    $customer = CustomerSetup::GetCustomerSetupById($customer_name);
                    if (!empty($customer)) {
                        echo '<table style="width: 100%;"><tr><th style="text-align: center;">';
                        echo "<h5 style='text-align: center;'>" . $customer->name . "</h5>";
                        echo '</th></tr></table>';
                    }
                }
                ?>

                <div id="floatThead" class="adv-table section">
                    <table class="striped demo1 bordered">
                        <thead>
                        <tr style="border: 1px solid #666;">
                            <th>S.No</th>

                            <?php if ($customer_name == '' || $customer_name == 'All') { ?>
                                <th>Customer</th>
                                <th>No. of Invoice</th>
                                <th>Qty</th>
                                <th>Carton</th>
                            <?php } else { ?>
                                <th>Date</th>
                                <th>Invoice #</th>
                                <th>Qty</th>
                                <th>Carton</th>
                            <?php } ?>

                            <th>Sale Price</th>

                            <?php if ((PROJECT_DISCOUNT == 1 || !empty($discount_price))) { ?>
                                <th>Discount</th>
                            <?php } ?>

                            <th>Total</th>
                        </tr>
                        </thead>

                        <tbody>
                        <?php
                        if ($customer_name != '' && $customer_name != 'All') {

                            // DETAIL: one customer, multiple invoices
                            $qry = Invoice::GetInvoiceCustomerReportListMonthlySale($filterReport);
                            $counter = 0;

                            if ($qry) {
                                foreach ($qry as $qery) {
                                    $counter++;
                                    ?>
                                    <tr style="border: 1px solid #666;">
                                        <td><?= $counter ?></td>
                                        <td><?php echo date('Y-m-d h:i A', strtotime($qery->create_date)); ?></td>
                                        <td><?php echo $qery->code; ?></td>
                                        <td><?php echo number_format($qery->product_qty, 2, '.', ''); ?></td>
                                        <td><?php echo number_format($qery->carton_qty, 2, '.', ''); ?></td>
                                        <td><?php echo number_format(($qery->total_amount + $qery->discount_price), 2, '.', ''); ?></td>

                                        <?php if ((PROJECT_DISCOUNT == 1 || !empty($discount_price))) { ?>
                                            <td><?php echo number_format(($qery->discount_price), 2, '.', ''); ?></td>
                                        <?php } ?>

                                        <td><?php echo number_format($qery->total_amount, 2, '.', ''); ?></td>
                                    </tr>
                                    <?php
                                    $productQtyTotal += $qery->product_qty;
                                    $cartonQtyTotal  += $qery->carton_qty;
                                    $unitPriceTotal  += ($qery->total_amount + $qery->discount_price);
                                    $totalDiscount   += $qery->discount_price;
                                    $totalProfit     += $qery->total_amount;
                                }
                            }

                        } else {

                            // SUMMARY: per customer
                            $qry = Invoice::GetInvoiceCustomerReportListMonthlySaleCustomers($filterReport);
                            $counter = 0;

                            if ($qry) {
                                foreach ($qry as $qery) {
                                    $counter++;
                                    $customer = CustomerSetup::GetCustomerSetupById($qery->customer_id);
                                    ?>
                                    <tr style="border: 1px solid #666;">
                                        <td><?= $counter ?></td>
                                        <td>
                                            <a target="_blank"
                                               href="/sales/admin/report/monthly_sale.php?datefrom=<?= $datefrom ?>&view=&dateto=<?= $dateto ?>&cat_name=<?= $cat_name ?>&mart_type=<?= $mart_type ?>&customer_name=<?= $qery->customer_id ?>">
                                                <?php echo $customer->name; ?>
                                            </a>
                                        </td>
                                        <td><?php echo $qery->total_invoices; ?></td>
                                        <td><?php echo number_format($qery->product_qty, 2, '.', ''); ?></td>
                                        <td><?php echo number_format($qery->carton_qty, 2, '.', ''); ?></td>
                                        <td><?php echo number_format(($qery->total_amount + $qery->discount_price), 2, '.', ''); ?></td>

                                        <?php if ((PROJECT_DISCOUNT == 1 || !empty($discount_price))) { ?>
                                            <td><?php echo number_format(($qery->discount_price), 2, '.', ''); ?></td>
                                        <?php } ?>

                                        <td><?php echo number_format($qery->total_amount, 2, '.', ''); ?></td>
                                    </tr>
                                    <?php
                                    $productQtyTotal += $qery->product_qty;
                                    $cartonQtyTotal  += $qery->carton_qty;
                                    $unitPriceTotal  += ($qery->total_amount + $qery->discount_price);
                                    $totalDiscount   += $qery->discount_price;
                                    $totalProfit     += $qery->total_amount;
                                }
                            }
                        }
                        ?>

                        <tr>
                            <?php
                            if ($customer_name == '' || $customer_name == 'All') {
                                $num = 3;
                            } else {
                                $num = 3;
                            }
                            ?>

                            <th colspan="<?= $num ?>" style="text-align: right; border: 1px solid #000;">
                                Total
                            </th>

                            <th style="border: 1px solid #000;">
                                <?= number_format($productQtyTotal, 2, '.', '') ?>
                            </th>

                            <th style="border: 1px solid #000;">
                                <?= number_format($cartonQtyTotal, 2, '.', '') ?>
                            </th>

                            <th style="border: 1px solid #000;">
                                <?= number_format($unitPriceTotal, 2, '.', '') ?>
                            </th>

                            <?php if ((PROJECT_DISCOUNT == 1 || $discount_price != 0)) { ?>
                                <th style="border: 1px solid #000;">
                                    <?= number_format(($totalDiscount), 2, '.', '') ?>
                                </th>
                            <?php } ?>

                            <th style="border: 1px solid #000;">
                                <?= number_format(($totalProfit), 2, '.', '') ?>
                            </th>
                        </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 () {

$("#print").on("click", function (e) {
    e.preventDefault();

    var customerName = "<?= isset($customer_name) ? $customer_name : 'All' ?>";
    var datefrom = "<?= isset($datefrom) ? $datefrom : '' ?>";
    var dateto = "<?= isset($dateto) ? $dateto : '' ?>";
    var catName = "<?= isset($cat_name) ? $cat_name : 'All' ?>";
    var martType = "<?= isset($mart_type) ? $mart_type : 'All' ?>";

    var printUrl = "";

    if (customerName != "" && customerName != "All") {
        printUrl = "<?= PROJECT_ADMIN_URL ?>report/print/monthly_sale_detail.php"
            + "?datefrom=" + encodeURIComponent(datefrom)
            + "&view="
            + "&dateto=" + encodeURIComponent(dateto)
            + "&cat_name=" + encodeURIComponent(catName)
            + "&mart_type=" + encodeURIComponent(martType)
            + "&customer_name=" + encodeURIComponent(customerName);
    } else {
        printUrl = "<?= PROJECT_ADMIN_URL ?>report/print/monthly_sale.php"
            + "?datefrom=" + encodeURIComponent(datefrom)
            + "&view="
            + "&dateto=" + encodeURIComponent(dateto)
            + "&cat_name=" + encodeURIComponent(catName)
            + "&mart_type=" + encodeURIComponent(martType);
    }

    window.open(printUrl, "_blank");
});

        $('table.demo1').floatThead({
            position: 'fixed',
            scrollingTop: 65
        });

        $('table.demo1 thead').css('background', '#ECEFF1');

        function loadCustomers(catId, selectedCustomer) {
            var martType = $('#mart_type').val();

            $('body.container').block({message: 'Loading...'});

            $.get('getFilterCustomersAll.php?id=' + catId + '&cus_id=' + selectedCustomer + '&mart_type=' + martType, function (data) {
                $("#customer_name").empty().append(data);
                $('body.container').unblock();
                $('#customer_name').trigger('contentChanged');
            });
        }

        $('#customer_name').material_select();
        $('#cat_name').material_select();
        $('#mart_type').material_select();

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

        $('#cat_name').on('change', function () {
            var catId = $(this).val();
            var currentCustomer = 0;

            if (catId !== '') {
                loadCustomers(catId, currentCustomer);
            }
        });

        $('#mart_type').on('change', function () {
            var catId = $('#cat_name').val();
            var currentCustomer = 0;

            if (catId !== '') {
                loadCustomers(catId, currentCustomer);
            }
        });

        var initialCat = '<?= $cat_name ?>';
        var initialCustomer = '<?= $customer_name ?>';

        if (initialCat !== 'All') {
            loadCustomers(initialCat, initialCustomer);
        }
    });
</script>

</body>
</html>