<?php
include("../../classes/manager.class.php");
//ini_set('display_errors', 1);
//error_reporting(E_ALL);
$m = new Manager();
$output = '';
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));
$filterReport = " LEFT JOIN ". TABLE_CUSTOMERSETUP." AS cs ON inv.customer_id = cs.id RIGHT JOIN " . TABLE_INVOICE_PRODUCT . " AS invPr ON inv.id = invPr.invoice_id 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') AND cs.is_mart = 1 ";

if (isset($cat_name) && $cat_name != 'All') {
    $filterReport .= " AND cs.category_id ='$cat_name'";
}
if (isset($customer_name) && $customer_name != 'All') {
    $filterReport .= " AND inv.customer_id ='$customer_name'";
}
if (isset($invoice) && $invoice != 'All') {
    $filterReport .= " AND inv.code ='$invoice'";
}
$filterReport .= " ORDER BY inv.code ";
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <?php include('../includes/inc_head.php'); ?>
    <style>
        .table > thead > tr > th, .table > tbody > tr > th, .table > tfoot > tr > th, .table > thead > tr > td, .table > tbody > tr > td, .table > tfoot > tr > td {
            border: none;
        }
    </style>
</head>
<body>
<section id="container">
    <?php include('../includes/inc_top.php'); ?>
    <section id="main-content">
        <section class="wrapper">
            <div class="panel">
                <div class="panel-body">
                    <div class="">
                        <div class="span12">
                            <div class="">
                                <h2>Mart Report</h2>
                            </div>
                            <script>
                                $(function () {
                                    $("#datepicker").datepicker({dateFormat: 'dd-mm-yy'});
                                    $("#datepicker1").datepicker({dateFormat: 'dd-mm-yy'});
                                });
                            </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 WHERE customer_setup.is_mart = 1 GROUP BY catid ";
                                            $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-lg-4">Customer<br>
                                            <?php
                                            if($cat_name=='All'){
                                                $customersfilter = " WHERE status = 'active' AND is_mart = 1 AND ";
                                            }else{
                                                $customersfilter = " WHERE status = 'active' AND is_mart = 1 AND category_id = '$cat_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-lg-4">Invoice<br>
                                            <?php
                                            $filterInvoice = " WHERE customer_id = '$customer_name'";
                                            $invoices = Invoice::GetInvoiceList($filterInvoice);
                                            ?>
                                            <select class="form-control" required id="invoice"
                                                    name="invoice">
                                                <option>All</option>
                                                <?php
                                                if($invoices){
                                                    foreach ($invoices AS $invoicesRow) {
                                                        echo '<option ';
                                                        if ($invoicesRow->code == $invoice) {
                                                            echo 'selected';
                                                        }
                                                        echo ' value="' . $invoicesRow->code . '" >' . $invoicesRow->code . '</option>';
                                                    }
                                                }
                                                ?>
                                            </select><br/>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td colspan="2" class="col-lg-4">
                                            <button type="submit" class="btn btn-primary btn-large"
                                                    style="float:left;">
                                                Search
                                            </button>
                                            <?php if (isset($_GET['view'])) { ?>
                                                <button
                                                    onclick="exportTableToCSV('mart-<?= date('d-m-Y-h-i-a') ?>.csv')"
                                                    class="btn btn-primary btn-large"
                                                    style="float:left; margin-left: 15px;">
                                                    Download CSV
                                                </button>
                                                <button
                                                    id="print"
                                                    class="btn btn-primary btn-large"
                                                    style="float:left; margin-left: 15px;">
                                                    Print
                                                </button>
                                            <?php } ?>
                                        </td>
                                    </tr>
                                </table>
                            </form>
                            <hr>
                            <?php
                            if (isset($_GET['view'])) {
                                ?>
                                <div class="adv-table">
                                    <?php if ($customer_name != '' || $customer_name != 'All') {
                                        $customer = CustomerSetup::GetCustomerSetupById($customer_name);
                                        echo '<table style="width: 100%;"><tr><th style="text-align: center;">';
                                        echo "<h2>" . $customer->name . "</h2>";
                                        echo '</th></tr></table>';
                                    }
                                    ?>
                                    <table class="display table table-bordered table-striped">
                                        <tbody>
                                        <tr>
                                            <th>S.No</th>
                                            <th>Date</th>
                                            <th>Invoice #</th>
                                            <?php if ($customer_name == '' || $customer_name == 'All') { ?>
                                                <th>Customer</th>
                                            <?php } ?>
                                            <th>Product</th>
                                            <!--                                            <th>Sales Person</th>-->
                                            <th>Status</th>
                                            <th>Qty</th>
                                            <th>Factory Cost Price</th>
                                            <th>Distributor Price</th>
                                            <th>Sale Price</th>
                                            <?php if ((PROJECT_DISCOUNT == 1 || !empty($discount_price))) { ?>
                                                <th>Discount</th>
                                            <?php } ?>
                                            <th>Sub Total</th>
                                            <th>Profit / Loss Distributor</th>
                                            <th>Profit / Loss Factory</th>
                                        </tr>
                                        <?php
                                        $qry = Invoice::GetInvoiceReportList($filterReport);
                                        if ($qry) {
                                            $counter = 0;
                                            $countdown = 0;
                                            $reset = false;
                                            $qty = 0;
                                            $factoryRatePrice = 0;
                                            $distributorRatePrice = 0;
                                            $salesPrice = 0;
                                            $subTotalDiscountPrice = 0;
                                            foreach ($qry as $qery) {
                                                $counter++;
                                                $customer = CustomerSetup::GetCustomerSetupById($qery->customer_id);
                                                $salesPerson = User_setup::GetUserSetupId($qery->sales_person_id);
                                                $discount_price = $qery->discount_price;

                                                $productName = ProductSetup::GetProductSetupById($qery->product_id);
                                                $productQty = $qery->product_qty;
                                                $productQtyTotal += $productQty;
                                                $costPrice = number_format(($qery->product_qty * $qery->unit_cost_price), 2, '.', '');
                                                $costPriceTotal += $costPrice;
                                                $unitPrice = number_format(($qery->product_qty * $qery->unit_sale_price), 2, '.', '');
                                                $unitPriceTotal += $unitPrice;
                                                $distributorPrice = number_format(($qery->product_qty * $qery->unit_distributor_price), 2, '.', '');
                                                $distributorPriceTotal += $distributorPrice;
                                                $subtotal = $unitPrice - $costPrice;


                                                if (PROJECT_DISCOUNT == 1 || $discount_price != 0) {
                                                    $filterProducts = " WHERE invoice_id = '$qery->invoice_id'";
                                                    $productSetup = Invoice::GetInvoiceProducts($filterProducts);
                                                    $count = 0;
                                                    $totalDiscountper = $qery->discount;

                                                    $subTotalDiscount = ($unitPrice * ($totalDiscountper / 100));
                                                    $totalDiscount += $subTotalDiscount;
                                                    $subtotal -= $subTotalDiscount;
                                                }
                                                $totalProfit += $subtotal;

                                                if(isset($qry[$counter]->code)){
                                                    $nextCode = $qry[$counter]->code;
                                                }else{
                                                    $nextCode = 0;
                                                }
                                                if($reset == true){
                                                    $qty = 0;
                                                    $factoryRatePrice = 0;
                                                    $distributorRatePrice = 0;
                                                    $salesPrice = 0;
                                                    $subTotalDiscountPrice = 0;
                                                    $products = "";
                                                    $productsNames = "";
                                                    $reset = false;
                                                }
                                                if($qery->code == $nextCode){
                                                    $qty += $qery->product_qty;
                                                    $factoryRatePrice += $costPrice;
                                                    $distributorRatePrice += $distributorPrice;
                                                    $salesPrice += $unitPrice;
                                                    $subTotalDiscountPrice += $subTotalDiscount;
                                                    $products[] = $productName->name;
                                                    continue;
                                                }else{
                                                    $qty += $qery->product_qty;
                                                    $factoryRatePrice += $costPrice;
                                                    $distributorRatePrice += $distributorPrice;
                                                    $salesPrice += $unitPrice;
                                                    $subTotalDiscountPrice += $subTotalDiscount;
                                                    $products[] = $productName->name;
                                                    $reset = true;
                                                    if(!empty($products)){
                                                        $productsNames = implode(', ', $products);
                                                    }
                                                    //continue;
                                                    //$lastcode = $qery->code;
                                                }
                                                $countdown++;
                                                ?>
                                                <tr>
                                                    <td><?= $countdown ?></td>
                                                    <td><?php echo date('Y-m-d h:i A', strtotime($qery->create_date)); ?></td>
                                                    <?php
                                                    ?>
                                                    <td><?php echo $qery->code; ?></td>
                                                    <?php if ($customer_name == '' || $customer_name == 'All') { ?>
                                                        <td><?php echo $customer->name; ?></td>
                                                    <?php } ?>
                                                    <td><?php echo $productsNames; ?></td>
                                                    <!--                                                        <td>-->
                                                    <?php //echo $salesPerson->username; ?><!--</td>-->
                                                    <td><?php echo $qery->status; ?></td>
                                                    <td><?php echo $qty; ?></td>
                                                    <td><?php echo $factoryRatePrice; ?></td>
                                                    <td><?php echo $distributorRatePrice; ?></td>
                                                    <td><?php echo $salesPrice; ?></td>
                                                    <td><?php echo number_format(($subTotalDiscountPrice), 2, '.', ''); ?></td>
                                                    <td><?php echo number_format(($salesPrice-$subTotalDiscountPrice), 2, '.', ''); ?></td>
                                                    <td><?php echo number_format((($salesPrice-$subTotalDiscountPrice) - $distributorRatePrice), 2, '.', ''); ?></td>
                                                    <td><?php echo number_format(($distributorRatePrice - $factoryRatePrice), 2, '.', ''); ?></td>
                                                </tr>
                                                <?php
                                            }
                                        } ?>
                                        <tr>
                                            <?php if ($customer_name == '' || $customer_name == 'All') {
                                                $num = 6;
                                            } else {
                                                $num = 5;
                                            } ?>
                                            <th colspan="<?= $num ?>"
                                                style="text-align: right; border: 1px solid #000;">
                                                Total
                                            </th>

                                            <th style="border: 1px solid #000;"><?= $productQtyTotal ?></th>
                                            <th style="border: 1px solid #000;"><?= $costPriceTotal ?></th>
                                            <th style="border: 1px solid #000;"><?= $distributorPriceTotal ?></th>
                                            <th style="border: 1px solid #000;"><?= $unitPriceTotal ?></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(($unitPriceTotal - $totalDiscount), 2, '.', '') ?></th>
                                            <th style="border: 1px solid #000;"><?= number_format((($unitPriceTotal - $totalDiscount) - $distributorPriceTotal), 2, '.', '') ?></th>
                                            <th style="border: 1px solid #000;"><?= number_format(($distributorPriceTotal - $costPriceTotal), 2, '.', '') ?></th>
                                        </tr>
                                        <tr>
                                            <th>S.No</th>
                                            <th>Date</th>
                                            <th>Invoice #</th>
                                            <?php if ($customer_name == '' || $customer_name == 'All') { ?>
                                                <th>Customer</th>
                                            <?php } ?>
                                            <th>Product</th>
                                            <!--                                            <th>Sales Person</th>-->
                                            <th>Status</th>
                                            <th>Qty</th>
                                            <th>Factory Cost Price</th>
                                            <th>Distributor Price</th>
                                            <th>Sale Price</th>
                                            <?php if ((PROJECT_DISCOUNT == 1 || !empty($discount_price))) { ?>
                                                <th>Discount</th>
                                            <?php } ?>
                                            <th>Sub Total</th>
                                            <th>Profit / Loss Distributor</th>
                                            <th>Profit / Loss Factory</th>
                                        </tr>
                                        </tbody>
                                    </table>
                                </div>
                                <?php

                            } // close view
                            ?>
                        </div>
                    </div>
                </div>
                <footer>
                    <?php include('../includes/inc_footer.php'); ?>
                </footer>
            </div>
        </section>
        <script type="text/javascript" src="<?= PROJECT_URL ?>js/download.js"></script>
        <?php include('../includes/inc_js.php'); ?>
        <script>
            $('#cat_name').on('change', function () {
                $('body.container').block({message: 'Loading...'});
                $.get('getFilterCustomers.php?id=' + $(this).val(), function (data) {
                    $("#customer_name").empty();
                    $("#customer_name").append(data);
                    $('body.container').unblock();
                });
            });
            $('#customer_name').on('change', function () {
                $('body.container').block({message: 'Loading...'});
                $.get('getFilterInvoices.php?id=' + $(this).val(), function (data) {
                    $("#invoice").empty();
                    $("#invoice").append(data);
                    $('body.container').unblock();
                });
            });
        </script>
        <style>
            @page { size: A4;  margin: 5mm 0mm; }
            @media print
            {
                table { page-break-inside:auto }
                tr    { page-break-inside:avoid; page-break-after:auto }

                #container { page-break-after: always;}

                header, aside, form, footer {
                    display: none;
                }
                .adv-table th, .adv-table td{
                    padding:5px;
                }
                h2{
                    font-size: 18px;
                    text-align: center;
                }
                hr{
                    margin-top: 5px;
                    margin-bottom: 5px;
                }
            }
        </style>
        <script type="application/javascript">
            $("#print").on("click", function (e) {
                var fewSeconds = 2;
                e.preventDefault();
                $('#searchfrm').prop('target', '_blank');
                $('#searchfrm').prop('action', "<?=PROJECT_ADMIN_URL?>report/print/martcat.php?").submit();
                setTimeout(function () {
                    $('#searchfrm').prop('target', "");
                    $('#searchfrm').prop('action', "");
                }, fewSeconds * 1000);
            });
        </script>
</body>
</html>