<?php
include("../../classes/manager.class.php");
//ini_set('display_errors', 1);
//error_reporting(E_ALL);
$m = new Manager();
$output = '';
$datefrom = "";
$dateto = "";
$customer_name = "";
$productQtyTotal = 0;
$costPriceTotal = 0;
$unitPriceTotal = 0;
$distributorPriceTotal = 0;
$totalDiscount = 0;
$totalProfit = 0;
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($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'); ?>
</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>Mart Report</h3>
            </div>
            <script>
                $(function () {
                    $('#datepicker').pickadate({
                        format: 'dd-mm-yyyy',
                        selectMonths: true,
                    });
                    $('#datepicker1').pickadate({
                        format: 'dd-mm-yyyy',
                        selectMonths: 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 s6">Customer<br>
                            <?php
                            $customersfilter = " WHERE status = 'active' AND is_mart = 1 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 s6">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 s12">
                            <button type="submit" class="btn waves-effect waves-light"
                                    style="float:left;">
                                Search
                            </button>
                            <?php if (isset($_GET['view'])) { ?>
                                <button
                                    onclick="exportTableToCSV('mart-<?= date('d-m-Y-h-i-a') ?>.csv')"
                                    class="btn waves-effect waves-light"
                                    style="float:left; margin-left: 15px;">
                                    Download 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'])) {
                ?>
                <?php 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 "<h2>" . $customer->name . "</h2>";
                        echo '</th></tr></table>';
                    }
                }
                ?>
                <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>
                            <?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 Rate</th>
                            <th>Factory Cost Price</th>
                            <th>Distributor Rate</th>
                            <th>Net Payable</th>
                            <?php if ($customer_name != '' || $customer_name != 'All') {
                                $customer = CustomerSetup::GetCustomerSetupById($customer_name);
                                if(!empty($customer)){
                                    echo "<th>" . $customer->name . " Rate" . "</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>
                        </thead>
                        <?php
                        $qry = Invoice::GetInvoiceReportList($filterReport);
                        if ($qry) {
                            $counter = 0;
                            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>
                                    <?php
                                    $customer = CustomerSetup::GetCustomerSetupById($qery->customer_id);
                                    $salesPerson = User_setup::GetUserSetupId($qery->sales_person_id);
                                    $discount_price = $qery->discount_price;
                                    ?>
                                    <td><?php echo $qery->code; ?></td>
                                    <?php if ($customer_name == '' || $customer_name == 'All') { ?>
                                        <td><?php echo $customer->name; ?></td>
                                    <?php } ?>
                                    <?php
                                    $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;
                                    ?>
                                    <td><?php echo $productName->name; ?></td>
                                    <!--                                                        <td>-->
                                    <?php //echo $salesPerson->username; ?><!--</td>-->
                                    <td><?php echo $qery->status; ?></td>
                                    <td><?php echo $qery->product_qty; ?></td>
                                    <td><?php echo $qery->unit_cost_price; ?></td>
                                    <td><?php echo $costPrice; ?></td>
                                    <td><?php echo $qery->unit_distributor_price; ?></td>
                                    <td><?php echo $distributorPrice; ?></td>
                                    <td><?php echo $qery->unit_sale_price; ?></td>
                                    <td><?php echo $unitPrice; ?></td>
                                    <td><?php echo number_format(($subTotalDiscount), 2, '.', ''); ?></td>
                                    <td><?php echo number_format(($unitPrice - $subTotalDiscount), 2, '.', ''); ?></td>
                                    <td><?php echo number_format((($unitPrice - $subTotalDiscount) - $distributorPrice), 2, '.', ''); ?></td>
                                    <td><?php echo number_format(($distributorPrice - $costPrice), 2, '.', ''); ?></td>
                                </tr>
                                <?php
                            }
                        } ?>
                        <tr style="border: 1px solid #666;">
                            <?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;"></th>
                            <th style="border: 1px solid #000;"><?= $costPriceTotal ?></th>
                            <?php if ($customer_name != '' || $customer_name != 'All') { ?>
                                <th style="border: 1px solid #000;"></th>
                            <?php } ?>
                            <th style="border: 1px solid #000;"><?= $distributorPriceTotal ?></th>
                            <th style="border: 1px solid #000;"></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>
                    </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 () {
        // initialize
        $('#invoice').material_select();

        // setup listener for custom event to re-initialize on change
        $('#invoice').on('contentChanged', function () {
            $(this).material_select();
        });

        $('#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();
                $('#invoice').trigger('contentChanged');
            });
        });

        $("#print").on("click", function (e) {
            var fewSeconds = 2;
            e.preventDefault();
            $('#searchfrm').prop('target', '_blank');
            $('#searchfrm').prop('action', "<?=PROJECT_ADMIN_URL?>report/print/mart.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');
    });
</script>
</body>
</html>