<?php
include("../../classes/manager.class.php");
//ini_set('display_errors', 1);
//error_reporting(E_ALL);
$m = new Manager();
$output = '';
$datefrom = "";
$dateto = "";
$cat_name = "";
$customer_name = "";
$product_id = "";
$productsQtys = "";
$productsUnitCostPrice = 0;
$totalDiscount = 0;
$productQtyTotal = 0;
$costPriceTotal = 0;
$unitPriceTotal = 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_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' ";

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($product_id) && $product_id != 'All') {
    $filterReport .= " AND invPr.product_id ='$product_id'";
} else {
    $filterReport .= " GROUP BY inv.id";
}
$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>Category Invoice Profit/Loss 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 s4">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 s4"> Date To<br>
                            <input type="text" name="dateto" id="datepicker1"
                                   placeholder="Date To"
                                   value="<?= $dateto ?>" class="form-control"/>
                        </td>
                    </tr>
                    <tr>
                        <td class="col s4">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>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 s4">Customer<br>
                            <?php
                            //$customersfilter = " WHERE status = 'active' AND is_mart = 0";
                            $customersfilter = " WHERE status = 'active' WHERE 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 s4"> Product<br>
                            <?php
                            $filter = " where status = 'active' ORDER BY name";
                            $qry = ProductSetup::GetProductSetupList($filter, $pageno = "null", $pagesize = "null");
                            if ($qry) {
                                echo '<select id="product_id" name="product_id" class="form-control"><option>All</option>';
                                foreach ($qry as $qery) {
                                    echo '<option ';
                                    if ($qery->id == $product_id) {
                                        echo 'selected';
                                    }
                                    echo ' value=' . $qery->id . '>' . $qery->name . '</option>';
                                }
                                echo '</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>Date</th>
                            <th>Invoice #</th>
                            <th>Customer</th>
                            <th>Product</th>
                            <th>Sales Person</th>
                            <th>Status</th>
                            <th>Qty</th>
                            <th>Cost Price</th>
                            <th>Sale Price</th>
                            <?php if ((PROJECT_DISCOUNT == 1 || !empty($discount_price))) { ?>
                                <th>Discount</th>
                            <?php } ?>
                            <th>Profit / Loss</th>
                        </tr>
                        </thead>
                        <tbody>
                        <?php if ($customer_name != '' && $customer_name != 'All') {
                            $customer = CustomerSetup::GetCustomerSetupById($customer_name);
                            echo "<h2 style='text-align: center;'>" . $customer->name . "</h2>";
                        }
                        $qry = Invoice::GetInvoiceReportList($filterReport);
                        if ($qry) {
                            foreach ($qry as $qery) { ?>
                                <tr style="border: 1px solid #666;">
                                    <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>
                                    <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_distributor_price), 2, '.', '');
                                                }
                                            }
                                        }
                                        $subtotal = $productsUnitSalePrice - $productsUnitCostPrice;
                                        if ($qery->is_mart == 0) {
                                            if (PROJECT_DISCOUNT == 1 || !empty($discount_price) && ($product_id == '' || $product_id == 'All')) {

                                                $subtotal -= $discount_price;
                                                $totalDiscount += $discount_price;
                                            }
                                        }
                                        $productsName = implode(', ', $productsNames);
                                        $productQtyTotal += $productsQtys;
                                        $costPriceTotal += $productsUnitCostPrice;
                                        $unitPriceTotal += $productsUnitSalePrice;
                                        $totalProfit += $subtotal;
                                        ?>
                                        <td style="font-size: 12px;"><?php echo $productsName; ?></td>
                                        <td><?php echo $salesPerson->username; ?></td>
                                        <td><?php echo $qery->status; ?></td>
                                        <td><?php echo $productsQtys; ?></td>
                                        <td><?php echo $productsUnitCostPrice; ?></td>
                                        <td><?php echo $productsUnitSalePrice; ?></td>
                                        <?php
                                        if ($qery->is_mart == 0) {
                                            if (PROJECT_DISCOUNT == 1 || !empty($discount_price)) {
                                                ?>
                                                <td><?php echo $discount_price; ?></td>
                                            <?php }
                                        } else {
                                            ?>
                                            <td>0</td>
                                            <?php
                                        } ?>
                                        <td><?php echo number_format(($subtotal), 2, '.', ''); ?></td>
                                    <?php } else {
                                        $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;
                                        if ($qery->is_mart == 0) {
                                            $unitPrice = number_format(($qery->product_qty * $qery->unit_sale_price), 2, '.', '');
                                            $unitPriceTotal += $unitPrice;
                                            $subtotal = $unitPrice - $costPrice;
                                            if (PROJECT_DISCOUNT == 1 || $discount_price != 0) {
                                                $filterProducts = " WHERE invoice_id = '$qery->invoice_id'";
                                                $productSetup = Invoice::GetInvoiceProducts($filterProducts);
                                                $count = 0;
                                                if ($productSetup) {
                                                    foreach ($productSetup as $productSetupRows) {
                                                        $count++;
                                                    }
                                                }
                                                $totalDiscountper = $qery->discount;

                                                $subTotalDiscount = ($unitPrice * ($totalDiscountper / 100));
                                                $totalDiscount += $subTotalDiscount;
                                                $subtotal -= $subTotalDiscount;
                                            }
                                            $totalProfit += $subtotal;
                                        } else {
                                            $unitPrice = number_format(($qery->product_qty * $qery->unit_distributor_price), 2, '.', '');
                                            $unitPriceTotal += $unitPrice;
                                            $subtotal = $unitPrice - $costPrice;
                                            $totalProfit += $subtotal;
                                        }
                                        ?>
                                        <td style="font-size: 12px;"><?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 $costPrice; ?></td>
                                        <td><?php echo $unitPrice; ?></td>
                                        <?php if ($qery->is_mart == 0) { ?>
                                            <td><?php echo number_format(($subTotalDiscount), 2, '.', ''); ?></td>
                                        <?php } else { ?>
                                            <td>0</td>
                                        <?php } ?>
                                        <td><?php echo number_format(($subtotal), 2, '.', ''); ?></td>
                                    <?php } ?>
                                </tr>
                                <?php
                            }
                        } ?>
                        <tr>

                            <th colspan="6"  style="text-align:right; border: 1px solid #666;">
                                Total
                            </th>
                            <th style="border: 1px solid #666;"><?= $productQtyTotal ?></th>
                            <th style="border: 1px solid #666;"><?= $costPriceTotal ?></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), 2, '.', '') ?></th>
                            <?php } ?>
                            <th style="border: 1px solid #666;"><?= number_format(($totalProfit), 2, '.', '') ?></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 () {
        // initialize
        $('#customer_name').material_select();

        // setup listener for custom event to re-initialize on change
        $('#customer_name').on('contentChanged', function () {
            $(this).material_select();
        });
        $('#cat_name').on('change', function () {
            $('body.container').block({message: 'Loading...'});
            $.get('getFilterCustomersAll.php?id=' + $(this).val(), function (data) {
                $("#customer_name").empty();
                $("#customer_name").append(data);
                $('body.container').unblock();
                $('#customer_name').trigger('contentChanged');
            });
        });
        $("#print").on("click", function (e) {
            var fewSeconds = 2;
            e.preventDefault();
            $('#searchfrm').prop('target', '_blank');
            $('#searchfrm').prop('action', "<?=PROJECT_ADMIN_URL?>report/print/invoicecat.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>