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

$m = new Manager();

$output = '';
$datefrom = "";
$dateto = "";
$cat_name = array("All");
$mart_type = "All";

$totalDiscount = 0;
$productQtyTotal = 0;
$cartonQtyTotal = 0;
$unitPriceTotal = 0;
$totalProfit = 0;
$totalInvoiceCount = 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 / normalize multiple category values ----
if (!isset($cat_name) || $cat_name == '') {
    $cat_name = array("All");
}

if (!is_array($cat_name)) {
    $cat_name = array($cat_name);
}

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

// ---- Build category query string for print link/form if needed ----
$catQueryString = '';
if (is_array($cat_name)) {
    foreach ($cat_name as $selectedCat) {
        $catQueryString .= '&cat_name[]=' . urlencode($selectedCat);
    }
}

// ---- Build base filter ----
$filterReport = "
    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')
";

// ---- Multiple category filter ----
if (!in_array('All', $cat_name)) {
    $catIds = array();

    foreach ($cat_name as $catId) {
        $catId = intval($catId);
        if ($catId > 0) {
            $catIds[] = $catId;
        }
    }

    if (!empty($catIds)) {
        $filterReport .= " AND cust.category_id IN (" . implode(",", $catIds) . ") ";
    }
}

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

// ---- Group and order ----
$filterReport .= "
    GROUP BY inv.customer_id
    ORDER BY cust.name ASC
";

//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>Multi Category 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" value="" 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">Categories<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" multiple id="cat_name" name="cat_name[]">
                                <option value="All" <?php if (in_array('All', $cat_name)) { echo 'selected'; } ?>>All</option>
                                <?php
                                if ($categories) {
                                    foreach ($categories AS $categoriesRow) {
                                        echo '<option ';
                                        if (in_array($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 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('multi-category-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'])) {

                // ---- Category heading ----
                if (!in_array('All', $cat_name)) {
                    $catNames = array();

                    foreach ($cat_name as $catId) {
                        $catObj = CustomerCategorySetup::GetCustomerCategorySetupById($catId);
                        if (!empty($catObj)) {
                            $catNames[] = $catObj->name;
                        }
                    }

                    if (!empty($catNames)) {
                        echo '<table style="width: 100%;"><tr><th style="text-align: center;">';
                        echo "<h6 style='text-align: center;'>" . implode(", ", $catNames) . " - Categories</h6>";
                        echo '</th></tr></table>';
                    }
                } else {
                    echo '<table style="width: 100%;"><tr><th style="text-align: center;">';
                    echo "<h6 style='text-align: center;'>All Categories</h6>";
                    echo '</th></tr></table>';
                }

                // ---- Customer type heading ----
                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>';
                }
                ?>

                <div id="floatThead" class="adv-table section">
                    <table class="striped demo1 bordered">
                        <thead>
                        <tr style="border: 1px solid #666;">
                            <th>S.No</th>
                            <th>Customer</th>
                            <th>Category</th>
                            <th>No. of Invoice</th>
                            <th>Qty</th>
                            <th>Carton</th>
                            <th>Sale Price</th>

                            <?php if (PROJECT_DISCOUNT == 1) { ?>
                                <th>Discount</th>
                            <?php } ?>

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

                        <tbody>
                        <?php
                        $qry = Invoice::GetInvoiceCustomerReportListMonthlySaleMultiCategory($filterReport);
                        $counter = 0;

                        if ($qry) {
                            foreach ($qry as $qery) {
                                $counter++;

                                $salePrice = $qery->sale_price;
                                $discountAmount = $qery->total_discount;
                                $netTotal = $qery->total_amount;
                                ?>
                                <tr style="border: 1px solid #666;">
                                    <td><?= $counter ?></td>

                                    <td>
                                        <?php echo $qery->customer_name; ?>
                                    </td>

                                    <td>
                                        <?php echo $qery->category_name; ?>
                                    </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($salePrice, 2, '.', ''); ?>
                                    </td>

                                    <?php if (PROJECT_DISCOUNT == 1) { ?>
                                        <td>
                                            <?php echo number_format($discountAmount, 2, '.', ''); ?>
                                        </td>
                                    <?php } ?>

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

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

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

            $('#searchfrm').prop('target', '_blank');
            $('#searchfrm').prop('action', "<?=PROJECT_ADMIN_URL?>report/print/monthly_sale_multi_category.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');

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

        // If user selects All with other categories, remove All automatically
        $('#cat_name').on('change', function () {
            var selected = $(this).val();

            if (selected && selected.length > 1 && selected.indexOf('All') !== -1) {
                selected = selected.filter(function (value) {
                    return value !== 'All';
                });

                $(this).val(selected);
                $(this).material_select();
            }
        });
    });
</script>

</body>
</html>