<?php
include("../../classes/manager.class.php");
//ini_set('display_errors', 1);
//error_reporting(E_ALL);
$m = new Manager();
$output = '';
$datefrom = "";
$dateto = "";
$customer_name = "";
$totalProfitPrevious = 0;
$totalPaymentsPrevious = 0;
$costPriceTotal = 0;
$unitPriceTotal = 0;
$totalDiscount = 0;
$totaladdDiscount = 0;
$totalProfit = 0;
$productQtyTotal = 0;
$totalPayments = 0;
$openingBalance = 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 = " 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') ";

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 .= " UNION SELECT 'payment' AS nameTable, id, description, code , customer_id, '', '', amount, '',
		'', '', create_date, '', datetime, '',
		'', '', '', '', '', payment_type, cheque_bank_name, cheque_number,
		cheque_payee_name, cheque_date, bank_name, bank_account_number,
		party_name, from_bank_name FROM " . TABLE_PAYMENT . " WHERE DATE_FORMAT(create_date,'%Y-%m-%d')>='$qryDate' and DATE_FORMAT(create_date,'%Y-%m-%d')<='$qryTo' AND status <> 'Cancel' ";

if (isset($customer_name) && $customer_name != 'All') {
    $filterReport .= " AND customer_id ='$customer_name'";
}
if (isset($invoice) && $invoice != 'All') {
    $filterReport .= " AND invoice_reference_code ='$invoice'";
}
$filterReport .= " ORDER BY create_date, code ";
//echo $filterReport;
//echo "<br>";
//PreviousRecord
$qryDatePrevious = date('Y-m-d', strtotime('-1 day', strtotime($qryDate)));
$filterReportPrevious = " RIGHT JOIN " . TABLE_INVOICE_PRODUCT . " AS invPr ON inv.id = invPr.invoice_id WHERE DATE_FORMAT(inv.create_date,'%Y-%m-%d')>='2016-01-01' and DATE_FORMAT(inv.create_date,'%Y-%m-%d')<='$qryDatePrevious'  AND inv.status not in('Draft', 'Cancel') ";

if (isset($customer_name) && $customer_name != 'All') {
    $filterReportPrevious .= " AND inv.customer_id ='$customer_name'";
}
if (isset($invoice) && $invoice != 'All') {
    $filterReportPrevious .= " AND inv.code ='$invoice'";
}
$filterReportPrevious .= " UNION SELECT 'payment' AS nameTable, id, description, code , customer_id, '', '', amount, '',
		'', '', create_date, '', datetime, '',
		'', '', '', '', '', payment_type, cheque_bank_name, cheque_number,
		cheque_payee_name, cheque_date, bank_name, bank_account_number,
		party_name, from_bank_name FROM " . TABLE_PAYMENT . " WHERE DATE_FORMAT(create_date,'%Y-%m-%d')>='2016-01-01' and DATE_FORMAT(create_date,'%Y-%m-%d')<='$qryDatePrevious' AND status <> 'Cancel' ";

if (isset($customer_name) && $customer_name != 'All') {
    $filterReportPrevious .= " AND customer_id ='$customer_name'";
}
if (isset($invoice) && $invoice != 'All') {
    $filterReportPrevious .= " AND invoice_reference_code ='$invoice'";
}
$filterReportPrevious .= " ORDER BY create_date, code ";
//Previous Record
//echo "$filterReportPrevious";
//echo "<br>";
?>
<!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>Customer 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" 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' 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-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 waves-effect waves-light"
                                    style="float:left;">
                                Search
                            </button>
                            <?php if (isset($_GET['view'])) { ?>
                                <button type="button"
                                        onclick="exportTableToCSV('customer-<?= 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'])) {
                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 style='text-align: center;'>" . $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>Payment Type</th>
                            <th>Payment Date</th>
                            <th>Description</th>
                            <th>Qty</th>
                            <?php if ($customer_name != '' || $customer_name != 'All') {
                                $customer = CustomerSetup::GetCustomerSetupById($customer_name);
                                if (!empty($customer->name)) {
                                    echo "<th>" . $customer->name . " Rate" . "</th>";
                                } else {
                                    echo "<th>Rate</th>";
                                }
                            } ?>
                            <th>Sale Price</th>
                            <?php if ((PROJECT_DISCOUNT == 1 || !empty($discount_price))) { ?>
                                <th>Discount</th>
                            <?php } ?>
                            <th>Total Recievable</th>
                            <th>Total Payment</th>
                            <th>Balance</th>
                        </tr>
                        </thead>
                        <tbody>
                        <?php
                        $qryPrevious = Invoice::GetInvoiceCustomerReportList($filterReportPrevious);
                        //print_r($qryPrevious);
                        if ($qryPrevious) {
                            foreach ($qryPrevious AS $qryPreviousRow) {
                                if ($qryPreviousRow->nameTable == 'invoice') {
                                    $unitPricePrevious = number_format(($qryPreviousRow->product_qty * $qryPreviousRow->unit_sale_price), 2, '.', '');
                                    $totalDiscountperPrevious = $qryPreviousRow->discount;

                                    $subTotalDiscountPrevious = ($unitPricePrevious * ($totalDiscountperPrevious / 100));

                                    $totalProfitPrevious += ($unitPricePrevious - $subTotalDiscountPrevious);
                                } else if ($qryPreviousRow->nameTable == 'payment') {
                                    $totalPaymentsPrevious += $qryPreviousRow->total_amount;
                                }
                            }
                            $openingBalance = number_format(($totalProfitPrevious - $totalPaymentsPrevious), 2, '.', '');
                        }
                        //exit;
                        $qry = Invoice::GetInvoiceCustomerReportList($filterReport);
                        $customerIds = array();
                        $cToggle = 0;
                        if($qry){
                            foreach ($qry as $qery) {
                                if ($cToggle == 0 && !in_array($qery->customer_id, $customerIds) && $qery->nameTable == 'invoice') {
                                    $customer = CustomerSetup::GetCustomerSetupById($qery->customer_id);
                                    $opbalance += $customer->balance;
                                    $customerIds[] = $qery->customer_id;
                                    $cToggle = 1;
                                }else if ($cToggle == 0 && !in_array($qery->customer_id, $customerIds) && $qery->nameTable == 'payment'){
                                    $customer = CustomerSetup::GetCustomerSetupById($qery->customer_id);
                                    $opbalance += $customer->balance;
                                    $cToggle = 1;
                                }
                            }
                        }else{
                            $customer = CustomerSetup::GetCustomerSetupById($customer_name);
                            $opbalance += $customer->balance;
                            $cToggle = 1;
                        }
                        $openingBalance += $opbalance;
                        $counter = 1;
                        ?>
                        <tr style="border: 1px solid #666;">
                            <td><?= $counter ?></td>
                            <?php if ($customer_name == '' || $customer_name == 'All') { ?>
                                <td colspan="13">Opening</td>
                            <?php } else { ?>
                                <td colspan="12">Opening</td>
                            <?php } ?>

                            <td><?php echo(number_format(($openingBalance), 2, '.', '')); ?></td>
                        </tr>
                        <?php
                        if ($qry) {
                            foreach ($qry as $qery) {
                                $counter++;
                                if ($qery->nameTable == 'invoice') {
                                    ?>
                                    <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;
                                        $add_discount_price = intval($qery->add_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;
                                            if ($productSetup) {
                                                foreach ($productSetup as $productSetupRows) {
                                                    $count++;
                                                }
                                            }
                                            $totalDiscountper = $qery->discount;

                                            $subTotalDiscount = ($unitPrice * ($totalDiscountper / 100));
                                            $totalDiscount += $subTotalDiscount;
                                           $totaladdDiscount += $add_discount_price;
                                            $subtotal -= $subTotalDiscount;
                                         //  $subtotal -= $totaladdDiscount;
                                          
                                        }
                                        $totalProfit += $unitPrice - $subTotalDiscount;
                                        ?>
                                        <td><?php echo $productName->name; ?></td>
                                        <td><?php echo  $add_discount_price; ?>@@-</td>
                                        <td>-</td>
                                        <td><?php echo $qery->description; ?></td>
                                        <td><?php echo $qery->product_qty; ?></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>-</td>
                                        <td><?php echo(number_format(($openingBalance + ($totalProfit - $totalPayments)), 2, '.', '')); ?></td>
                                    </tr>
                                    <?php
                                } else if ($qery->nameTable == 'payment') { ?>
                                    <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;
                                        $bank = BankSetup::GetBankSetupById($qery->bank_name);
                                        $totalPayments += $qery->total_amount;
                                        ?>
                                        <td><?php echo $qery->code; ?></td>
                                        <?php if ($customer_name == '' || $customer_name == 'All') { ?>
                                            <td><?php echo $customer->name; ?></td>
                                        <?php } ?>
                                        <td>-</td>
                                        <td><?php if ($qery->payment_type == 'bank' || $qery->payment_type == 'party') {
                                                echo 'Cheque' . '<br>';
                                                echo $qery->cheque_number . "<br>(" . $qery->cheque_bank_name . " - " . date('d-m-Y', strtotime($qery->cheque_date)) . ")";
                                            } else if ($qery->payment_type == 'online') {
                                                echo ucwords($qery->payment_type) . '<br>';
                                                echo $bank->bank_name;
                                            } else {
                                                echo ucwords($qery->payment_type);
                                            } ?></td>
                                        <td><?php echo date('Y-m-d h:i A', strtotime($qery->create_date)); ?></td>
                                        <td><?php echo $qery->description; ?></td>
                                        <td>-</td>
                                        <td>-</td>
                                        <td>-</td>
                                        <td>-</td>
                                        <td>-</td>
                                        <td><?php echo $qery->total_amount; ?></td>
                                        <td><?php echo(number_format(($openingBalance + ($totalProfit - $totalPayments)), 2, '.', '')); ?></td>
                                    </tr>
                                    <?php
                                }
                            }
                        } ?>
                        <tr>
                            <?php if ($customer_name == '' || $customer_name == 'All') {
                                $num = 8;
                            } else {
                                $num = 7;
                            } ?>
                            <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;"><?= $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>
                            <th style="border: 1px solid #000;"><?= number_format(($totalPayments), 2, '.', '') ?></th>
                            <th style="border: 1px solid #000;"><?= (number_format(($openingBalance + ($totalProfit - $totalPayments)), 2, '.', '')) ?></th>
                        </tr>
                        <tr style="border: 1px solid #666;">
                            <?php if ($customer_name == '' || $customer_name == 'All') {
                                $num = 13;
                            } else {
                                $num = 12;
                            } ?>
                            <th colspan="<?= $num ?>"
                                style="text-align: right; border: 1px solid #000;">
                                Total Opening Balance
                            </th>

                            <th colspan="2"
                                style="border: 1px solid #000;"><?= !empty($openingBalance) ? $openingBalance : 0 ?></th>
                        </tr>
                        <tr style="border: 1px solid #666;">
                            <?php if ($customer_name == '' || $customer_name == 'All') {
                                $num = 13;
                            } else {
                                $num = 12;
                            } ?>
                            <th colspan="<?= $num ?>"
                                style="text-align: right; border: 1px solid #000;">
                                Total Remianing Balance
                            </th>

                            <th colspan="2"
                                style="border: 1px solid #000;"><?= (number_format(($openingBalance + ($totalProfit - $totalPayments)), 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
        $('#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/customer.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>