<?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 = " RIGHT 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 not in('Draft', 'Cancel') AND cs.is_mart = 0 ";

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>Product 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">Customer<br>
                                            <?php
                                            $customersfilter = " WHERE status = 'active' AND is_mart = 0";
                                            $customers = CustomerSetup::GetCustomerSetupList($customersfilter);
                                            ?>
                                            <select class="form-control" required id="customer_name"
                                                    name="customer_name">
                                                <option>All</option>
                                                <?php
                                                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
                                                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('product-<?= date('d-m-Y-h-i-a') ?>.csv')"
                                                    class="btn btn-primary btn-large"
                                                    style="float:left; margin-left: 15px;">
                                                    Export CSV
                                                </button>
                                                <button
                                                    onClick="window.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 Rate</th>
                                            <th>Net Payable</th>
                                            <?php if ($customer_name != '' || $customer_name != 'All') {
                                                $customer = CustomerSetup::GetCustomerSetupById($customer_name);
                                                echo "<th>" . $customer->name . " Rate" . "</th>";
                                            } ?>
                                            <th>Sale Price</th>
                                            <?php if ((PROJECT_DISCOUNT == 1 || !empty($discount_price))) { ?>
                                                <th>Discount</th>
                                            <?php } ?>
                                            <th>Profit / Loss</th>
                                        </tr>
                                        <?php
                                        $qry = Invoice::GetInvoiceReportList($filterReport);
                                        if ($qry) {
                                            $counter = 0;
                                            foreach ($qry as $qery) {
                                                $counter++; ?>
                                                <tr>
                                                    <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;
                                                    $subtotal = $unitPrice - $costPrice;
                                                    if (PROJECT_DISCOUNT == 1 || $discount_price != 0) {
                                                        $filterProducts = " WHERE invoice_id = '$qery->invoice_id'";
                                                        $productSetup = Invoice::GetInvoiceProducts($filterProducts);
                                                        $count = 0;
                                                        foreach ($productSetup as $productSetupRows) {
                                                            $count++;
                                                        }
                                                        $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_sale_price; ?></td>
                                                    <td><?php echo $unitPrice; ?></td>
                                                    <td><?php echo number_format(($subTotalDiscount), 2, '.', ''); ?></td>
                                                    <td><?php echo number_format(($subtotal), 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;"></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;"><?= $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(($totalProfit), 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 Rate</th>
                                            <th>Net Payable</th>
                                            <?php if ($customer_name != '' || $customer_name != 'All') {
                                                $customer = CustomerSetup::GetCustomerSetupById($customer_name);
                                                echo "<th>" . $customer->name . " Rate" . "</th>";
                                            } ?>
                                            <th>Sale Price</th>
                                            <?php if ((PROJECT_DISCOUNT == 1 || !empty($discount_price))) { ?>
                                                <th>Discount</th>
                                            <?php } ?>
                                            <th>Profit / Loss</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>
            $('#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>
</body>
</html>