<?php
include("../../classes/manager.class.php");
//ini_set('display_errors', 1);
//error_reporting(E_ALL);
$m = new Manager();
$output = '';
$datefrom = "";
$dateto = "";
$cat_name = array();
$costPriceTotal = 0;
$unitPriceTotal = 0;
$distributorPriceTotal = 0;
$totalDiscount = 0;
$totalProfit = 0;
if (!isset($_SESSION['sess_userid'])) {
    header("Location: " . PROJECT_ADMIN_URL);
    exit();
}
extract($_REQUEST);
if ($_REQUEST) {
    //print_r($_REQUEST);
    //exit;
}
$cat_nameString = "";
if (!empty($cat_name) && (isset($cat_name[1]) || $cat_name[0] != "All")) {
    if (in_array("All", $cat_name)) {
        $catKey = array_search('All', $cat_name);
        unset($cat_name[$catKey]);
    }
    $cat_nameString = implode("','", $cat_name);
}
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));
//WholeSeller
$filterReportW = " INNER JOIN " . TABLE_INVOICE_PRODUCT . " AS invPr ON inv.id = invPr.invoice_id RIGHT 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 <> 1 AND cs.status = 'active' ";

if (isset($customer_name) && $customer_name != 'All') {
    $filterReportW .= " AND inv.customer_id ='$customer_name'";
}
if (isset($cat_name) && (isset($cat_name[1]) || $cat_name[0] != "All")) {
    $filterReportW .= " AND cs.category_id IN ('$cat_nameString')";
    //$filterReport .= " ORDER BY cs.id ";
} else {
    //$filterReport .= " ORDER BY cs.category_id, cs.id";
}

$filterReportW .= " UNION SELECT *, cs.category_id AS cscategory_id, inv.code AS code, cs.id AS custid, inv.status AS status from " . TABLE_INVOICE . " AS inv
INNER JOIN " . TABLE_INVOICE_PRODUCT . " AS invPr ON inv.id = invPr.invoice_id
AND 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')";

$filterReportW .= " RIGHT JOIN " . TABLE_CUSTOMERSETUP . " AS cs ON inv.customer_id = cs.id
WHERE cs.is_mart <> 1 AND inv.code IS NULL AND cs.status = 'active'";
if (isset($customer_name) && $customer_name != 'All') {
    $filterReportW .= " AND inv.customer_id ='$customer_name'";
}
if (isset($cat_name) && (isset($cat_name[1]) || $cat_name[0] != "All")) {
    $filterReportW .= " AND cs.category_id IN ('$cat_nameString')";
    $filterReportW .= " ORDER BY custid";
} else {
    $filterReportW .= " ORDER BY cscategory_id, custid";
}
//WholeSeller

//Imtiaz Super Mart
$filterReport = " INNER JOIN " . TABLE_INVOICE_PRODUCT . " AS invPr ON inv.id = invPr.invoice_id RIGHT 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.status = 'active' ";

if (isset($customer_name) && $customer_name != 'All') {
    $filterReport .= " AND inv.customer_id ='$customer_name'";
}
if (isset($cat_name) && (isset($cat_name[1]) || $cat_name[0] != "All")) {
    $filterReport .= " AND cs.category_id IN ('$cat_nameString')";
    //$filterReport .= " ORDER BY cs.id ";
} else {
    //$filterReport .= " ORDER BY cs.category_id, cs.id";
}

$filterReport .= " UNION SELECT *, cs.category_id AS cscategory_id, inv.code AS code, cs.id AS custid, inv.status AS status from " . TABLE_INVOICE . " AS inv
INNER JOIN " . TABLE_INVOICE_PRODUCT . " AS invPr ON inv.id = invPr.invoice_id
AND 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')";

$filterReport .= " RIGHT JOIN " . TABLE_CUSTOMERSETUP . " AS cs ON inv.customer_id = cs.id
WHERE inv.code IS NULL AND cs.status = 'active'";
if (isset($customer_name) && $customer_name != 'All') {
    $filterReport .= " AND inv.customer_id ='$customer_name'";
}
if (isset($cat_name) && (isset($cat_name[1]) || $cat_name[0] != "All")) {
    $filterReport .= " AND cs.category_id IN ('$cat_nameString')";
    $filterReport .= " ORDER BY custid";
} else {
    $filterReport .= " ORDER BY cscategory_id, custid";
}
//Imtiaz Super Mart

//Local Mart
$filterReportL = " INNER JOIN " . TABLE_INVOICE_PRODUCT . " AS invPr ON inv.id = invPr.invoice_id RIGHT 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 = 1 AND cs.status = 'active' ";

if (isset($customer_name) && $customer_name != 'All') {
    $filterReportL .= " AND inv.customer_id ='$customer_name'";
}
if (isset($cat_name) && (isset($cat_name[1]) || $cat_name[0] != "All")) {
    $filterReportL .= " AND cs.category_id IN ('$cat_nameString')";
} else {
    $filterReportL .= " AND cs.category_id <> '117'";
}

$filterReportL .= " UNION SELECT *, cs.category_id AS cscategory_id, inv.code AS code, cs.id AS custid, inv.status AS status from " . TABLE_INVOICE . " AS inv
INNER JOIN " . TABLE_INVOICE_PRODUCT . " AS invPr ON inv.id = invPr.invoice_id
AND 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')";

$filterReportL .= " RIGHT JOIN " . TABLE_CUSTOMERSETUP . " AS cs ON inv.customer_id = cs.id
WHERE cs.is_mart = 1 AND inv.code IS NULL AND cs.status = 'active'";
if (isset($customer_name) && $customer_name != 'All') {
    $filterReportL .= " AND inv.customer_id ='$customer_name'";
}
if (isset($cat_name) && (isset($cat_name[1]) || $cat_name[0] != "All")) {
    $filterReportL .= " AND cs.category_id IN ('$cat_nameString')";
    $filterReportL .= " ORDER BY custid";
} else {
    $filterReportL .= " AND cs.category_id <> '117'";
    $filterReportL .= " ORDER BY cscategory_id, custid";
}
//Local Mart

//Local Mart GT
$filterReportLGT = " INNER JOIN " . TABLE_INVOICE_PRODUCT . " AS invPr ON inv.id = invPr.invoice_id RIGHT 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 = 1 AND cs.status = 'active' ";

if (isset($customer_name) && $customer_name != 'All') {
    $filterReportLGT .= " AND inv.customer_id ='$customer_name'";
}
if (isset($cat_name) && (isset($cat_name[1]) || $cat_name[0] != "All")) {
    $filterReportLGT .= " AND cs.category_id IN ('$cat_nameString')";
} else {
    $filterReportLGT .= " AND cs.category_id = '117'";
}

$filterReportLGT .= " UNION SELECT *, cs.category_id AS cscategory_id, inv.code AS code, cs.id AS custid, inv.status AS status from " . TABLE_INVOICE . " AS inv
INNER JOIN " . TABLE_INVOICE_PRODUCT . " AS invPr ON inv.id = invPr.invoice_id
AND 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')";

$filterReportLGT .= " RIGHT JOIN " . TABLE_CUSTOMERSETUP . " AS cs ON inv.customer_id = cs.id
WHERE cs.is_mart = 1 AND inv.code IS NULL AND cs.status = 'active'";
if (isset($customer_name) && $customer_name != 'All') {
    $filterReportLGT .= " AND inv.customer_id ='$customer_name'";
}
if (isset($cat_name) && (isset($cat_name[1]) || $cat_name[0] != "All")) {
    $filterReportLGT .= " AND cs.category_id IN ('$cat_nameString')";
    $filterReportLGT .= " ORDER BY custid";
} else {
    $filterReportLGT .= " AND cs.category_id = '117'";
    $filterReportLGT .= " ORDER BY cscategory_id, custid";
}
//Local Mart GT
?>
<!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="`"></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>Cumulative 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 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"/>
                            <input type="hidden" name="cat_name[]" value="All"/>
                            <input type="hidden" name="customer_name" value="All"/>
                        </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'])) {
                ?>
                <div class="row">
                    <div class="col s12">
                        <section class="panel">
                            <div class="panel-body">
                                <div class="chartJS">
                                    <canvas id="myChart" height="500" width="1024"></canvas>
                                </div>
                            </div>
                        </section>
                    </div>
                </div>
                <hr>
                <?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">
                    <h2 class="center">Wholesaler</h2>
                    <table class="striped demo1 bordered">
                        <thead>
                        <tr style="font-size: 18px; border: 1px solid #666;">
                            <th>S.No</th>
                            <?php if ($customer_name == '' || $customer_name == 'All') { ?>
                                <th>Customer</th>
                            <?php } ?>
                            <th>Opening Balance</th>
                            <th>Total Balance</th>
                            <th>Sub Total</th>
                            <!--                            <th>Profit / Loss Distributor</th>-->
                            <th>Profit / Loss Factory</th>
                        </tr>
                        </thead>
                        <tbody>
                        <?php
                        $totalReturn = 0;
                        $withholdingTax = 0;
                        $salesTax = 0;
                        $shelfRent = 0;
                        $builtyCharges = 0;
                        $otherExpense = 0;
                        $qry = Invoice::GetInvoiceReportList($filterReportW);
                        if ($qry) {
                            $counter = 0;
                            $countdown = 0;
                            $reset = false;
                            $qty = 0;
                            $factoryRatePrice = 0;
                            $salesPrice = 0;
                            $subTotalDiscountPrice = 0;
                            foreach ($qry as $qery) {
//                                $filterReturn = " WHERE invoice_reference_code = '$qery->id' AND status <> 'Cancel' ";
//                                $returnAmount = Refund::GetRefundList($filterReturn);
//                                if(isset($returnAmount)){
//                                    foreach($returnAmount AS $returnAmountRow){
//                                        $totalReturn += $returnAmountRow->amount;
//                                    }
//                                }
                                $counter++;
                                $customer = CustomerSetup::GetCustomerSetupById($qery->custid);
                                $discount_price = $qery->discount_price;

                                $productQty = $qery->product_qty;
                                $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) {
                                    $count = 0;
                                    $totalDiscountper = $qery->discount;

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

                                    $subtotalAmountFull = $unitPrice - $subTotalDiscount;
                                    if($qery->add_discount > 0){
                                        $totalDiscountperAdd = $qery->add_discount;
                                        $subTotalDiscountAdd = ($subtotalAmountFull * ($totalDiscountperAdd / 100));

                                        $subTotalDiscount +=$subTotalDiscountAdd;
                                        $totalDiscount += $subTotalDiscountAdd;
                                        $subtotal -= $subTotalDiscountAdd;
                                    }

                                }
                                $totalProfit += $subtotal;

                                if (isset($qry[$counter]->custid)) {
                                    $nextCode = $qry[$counter]->custid;
                                } else {
                                    $nextCode = 0;
                                }
                                if ($reset == true) {
                                    $qty = 0;
                                    $factoryRatePrice = 0;
                                    $salesPrice = 0;
                                    $subTotalDiscountPrice = 0;
                                    $reset = false;
                                }
                                if ($qery->custid == $nextCode) {
                                    $qty += $qery->product_qty;
                                    $factoryRatePrice += $costPrice;
                                    $salesPrice += $unitPrice;
                                    $subTotalDiscountPrice += $subTotalDiscount;
                                    continue;
                                } else {
                                    $qty += $qery->product_qty;
                                    $factoryRatePrice += $costPrice;
                                    $salesPrice += $unitPrice;
                                    $subTotalDiscountPrice += $subTotalDiscount;
                                    $reset = true;
                                    //continue;
                                    //$lastcode = $qery->code;
                                }
                                //echo $qery->customer_id."<br>";
                                $filterpay = " WHERE pay.customer_id = " . $qery->custid . "
                                                AND DATE_FORMAT(pay.create_date,'%Y-%m-%d')>='$qryDate'
                                                AND DATE_FORMAT(pay.create_date,'%Y-%m-%d')<='$qryTo'
                                                AND pay.status <> 'Cancel'
                                                GROUP BY pay.customer_id
                                                ORDER BY cus.name ";
                                $totalPayment = Payment::GetTotalPaymentLists($filterpay);
                                //print_r($totalPayment);


                                //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') ";
                                $filterReportPrevious .= " AND inv.customer_id ='$qery->custid'";
                                $filterReportPrevious .= " UNION SELECT 'payment' AS nameTable, id, '' AS 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' ";
                                $filterReportPrevious .= " AND customer_id = '$qery->custid'";
                                $filterReportPrevious .= " ORDER BY create_date, code ";

                                $qryPrevious = Invoice::GetInvoiceCustomerReportList($filterReportPrevious);
                                $unitPricePrevious = 0;
                                $totalDiscountperPrevious = 0;
                                $subTotalDiscountPrevious = 0;
                                $totalProfitPrevious = 0;
                                $totalPaymentsPrevious = 0;
                                $openingBalance = 0;
                                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));
                                            $discountedPriceSubTotal = 0;
                                            $discountedPriceSubTotal = $unitPricePrevious - $subTotalDiscountPrevious;

                                            if($qryPreviousRow->add_discount > 0){
                                                $subTotalDiscountPreviousAdd = ($discountedPriceSubTotal * ($qryPreviousRow->add_discount / 100));
                                                $discountedPriceSubTotal = $discountedPriceSubTotal - $subTotalDiscountPreviousAdd;
                                            }
                                            $totalProfitPrevious += ($discountedPriceSubTotal);
                                        } else if ($qryPreviousRow->nameTable == 'payment') {
                                            $totalPaymentsPrevious += $qryPreviousRow->total_amount;
                                        }
                                    }
                                    $openingBalance = number_format(($totalProfitPrevious - $totalPaymentsPrevious), 2, '.', '');
                                }

                                $openingBalance += $customer->balance;
                                $withholdingTax += $totalPayment->withholding_tax;
                                $salesTax += $totalPayment->sales_tax;
                                $totalReturn += $totalPayment->goods_return;
                                $shelfRent += $totalPayment->shelf_rent;
                                $builtyCharges += $totalPayment->builty_charges;
                                $otherExpense += $totalPayment->other_expense;

                                $totalBalance += (($salesPrice - $subTotalDiscountPrice) - $totalPayment->amount) + $openingBalance;
                                $openingBalanceAmount = number_format($openingBalance, 2, '.', '');
                                $totalBalanceAmount = number_format(((($salesPrice - $subTotalDiscountPrice) - $totalPayment->amount) + $openingBalance), 2, '.', '');
                                $SubTotalAmount = number_format(($salesPrice - $subTotalDiscountPrice), 2, '.', '');
                                $factoryProfitChart[] = number_format(($SubTotalAmount - $factoryRatePrice), 0, '.', '');
                                $pfAmount = number_format(($SubTotalAmount - $factoryRatePrice), 2, '.', '');
                                $costPriceSubTotal += number_format(($pfAmount), 2, '.', '');
                                if (floor($openingBalanceAmount) != 0 || floor($totalBalanceAmount) != 0 || floor($SubTotalAmount) != 0 || floor($pfAmount) != 0) {
                                    $countdown++;
                                    ?>
                                    <tr style="font-size: 18px;border: 1px solid #666;">
                                        <td><?= $countdown ?></td>
                                        <?php if ($customer_name == '' || $customer_name == 'All') {
                                            if (!empty($customer->short_code)) {
                                                $cusChart[] = $customer->short_code;
                                            } else {
                                                $cusChart[] = $customer->name;
                                            }
                                            ?>
                                            <td><?php echo $customer->name; ?></td>
                                        <?php }

                                        ?>
                                        <td><?php echo $openingBalanceAmount; ?></td>
                                        <td><?php echo $totalBalanceAmount; ?></td>
                                        <td><?php echo $SubTotalAmount; ?></td>
                                        <!--                                    <td>0</td>-->
                                        <td><?php echo $pfAmount ?></td>
                                    </tr>
                                    <?php
                                }
                            }
                        }
                        ?>
                        <tr>
                            <?php if ($customer_name == '' || $customer_name == 'All') {
                                $num = 3;
                            } else {
                                $num = 2;
                            }
                            $openingWholesale = number_format($totalBalance, 2, '.', '');
                            $subTotalWholesale = number_format(($unitPriceTotal - $totalDiscount), 2, '.', '');
                            $factoryWholesale = $costPriceSubTotal;
                            ?>
                            <th colspan="<?= $num ?>"
                                style="font-size: 18px; text-align: right; border: 1px solid #000;">
                                Total
                            </th>
                            <th style="font-size: 18px; border: 1px solid #000;"><?= $openingWholesale ?></th>
                            <th style="font-size: 18px; border: 1px solid #000;"><?= $subTotalWholesale ?></th>
                            <!--                            <th style="border: 1px solid #000;">0</th>-->
                            <th style="font-size: 18px; border: 1px solid #000;"><?= $factoryWholesale; ?></th>
                        </tr>
                        </tbody>
                    </table>
                    <h2 class="center">Local Mart</h2>
                    <table class="striped demo1 bordered">
                        <thead>
                        <tr style="border: 1px solid #666;">
                            <th>S.No</th>
                            <?php if ($customer_name == '' || $customer_name == 'All') { ?>
                                <th>Customer</th>
                            <?php } ?>
                            <th>Opening Balance</th>
                            <th>Total Balance</th>
                            <th>Sub Total</th>
                            <!--                            <th>Profit / Loss Distributor</th>-->
                            <th>Profit / Loss Factory</th>
                        </tr>
                        </thead>
                        <tbody>
                        <?php
                        $qry = Invoice::GetInvoiceReportList($filterReportL);
                        if ($qry) {
                            $counter = 0;
                            $countdown = 0;
                            $reset = false;
                            $qty = 0;
                            $factoryRatePrice = 0;
                            $distributorRatePrice = 0;
                            $salesPrice = 0;
                            $subTotalDiscountPrice = 0;
                            foreach ($qry as $qery) {
//                                $filterReturn = " WHERE invoice_reference_code = '$qery->id' AND status <> 'Cancel' ";
//                                $returnAmount = Refund::GetRefundList($filterReturn);
//                                if(isset($returnAmount)){
//                                    foreach($returnAmount AS $returnAmountRow){
//                                        $totalReturn += $returnAmountRow->amount;
//                                    }
//                                }
                                $counter++;
                                $customer = CustomerSetup::GetCustomerSetupById($qery->custid);
                                $discount_price = $qery->discount_price;

                                $productQty = $qery->product_qty;
                                $costPrice = number_format(($qery->product_qty * $qery->unit_cost_price), 2, '.', '');
                                $costPriceTotal += $costPrice;
                                $costPriceTotalLocal += $costPrice;
                                $unitPrice = number_format(($qery->product_qty * $qery->unit_sale_price), 2, '.', '');
                                $unitPriceTotal += $unitPrice;
                                $unitPriceTotalLocal += $unitPrice;
                                $distributorPrice = number_format(($qery->product_qty * $qery->unit_distributor_price), 2, '.', '');
                                $distributorPriceTotal += $distributorPrice;
                                $distributorPriceTotalLocal += $distributorPrice;
                                $subtotal = $unitPrice - $costPrice;


                                if (PROJECT_DISCOUNT == 1 || $discount_price != 0) {
                                    $count = 0;
                                    $totalDiscountper = $qery->discount;

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

                                    $subtotalAmountFull = $unitPrice - $subTotalDiscount;
                                    if($qery->add_discount > 0){
                                        $totalDiscountperAdd = $qery->add_discount;
                                        $subTotalDiscountAdd = ($subtotalAmountFull * ($totalDiscountperAdd / 100));

                                        $subTotalDiscount +=$subTotalDiscountAdd;
                                        $totalDiscount += $subTotalDiscountAdd;
                                        $totalDiscountLocal += $subTotalDiscountAdd;
                                        $subtotal -= $subTotalDiscountAdd;
                                    }
                                }
                                $totalProfit += $subtotal;

                                if (isset($qry[$counter]->custid)) {
                                    $nextCode = $qry[$counter]->custid;
                                } else {
                                    $nextCode = 0;
                                }
                                if ($reset == true) {
                                    $qty = 0;
                                    $factoryRatePrice = 0;
                                    $distributorRatePrice = 0;
                                    $salesPrice = 0;
                                    $subTotalDiscountPrice = 0;
                                    $reset = false;
                                }
                                if ($qery->custid == $nextCode) {
                                    $qty += $qery->product_qty;
                                    $factoryRatePrice += $costPrice;
                                    $distributorRatePrice += $distributorPrice;
                                    $salesPrice += $unitPrice;
                                    $subTotalDiscountPrice += $subTotalDiscount;
                                    continue;
                                } else {
                                    $qty += $qery->product_qty;
                                    $factoryRatePrice += $costPrice;
                                    $distributorRatePrice += $distributorPrice;
                                    $salesPrice += $unitPrice;
                                    $subTotalDiscountPrice += $subTotalDiscount;
                                    $reset = true;
                                    //continue;
                                    //$lastcode = $qery->code;
                                }
                                //echo $qery->customer_id."<br>";
                                $filterpay = " WHERE pay.customer_id = " . $qery->custid . "
                                                AND DATE_FORMAT(pay.create_date,'%Y-%m-%d')>='$qryDate'
                                                AND DATE_FORMAT(pay.create_date,'%Y-%m-%d')<='$qryTo'
                                                AND pay.status <> 'Cancel'
                                                GROUP BY pay.customer_id
                                                ORDER BY cus.name ";
                                $totalPayment = Payment::GetTotalPaymentLists($filterpay);
                                //print_r($totalPayment);


                                //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') ";
                                $filterReportPrevious .= " AND inv.customer_id ='$qery->custid'";
                                $filterReportPrevious .= " UNION SELECT 'payment' AS nameTable, id, '' AS 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' ";
                                $filterReportPrevious .= " AND customer_id = '$qery->custid'";
                                $filterReportPrevious .= " ORDER BY create_date, code ";

                                $qryPrevious = Invoice::GetInvoiceCustomerReportList($filterReportPrevious);
                                $unitPricePrevious = 0;
                                $totalDiscountperPrevious = 0;
                                $subTotalDiscountPrevious = 0;
                                $totalProfitPrevious = 0;
                                $totalPaymentsPrevious = 0;
                                $openingBalance = 0;
                                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));
                                            $discountedPriceSubTotal = 0;
                                            $discountedPriceSubTotal = $unitPricePrevious - $subTotalDiscountPrevious;

                                            if($qryPreviousRow->add_discount > 0){
                                                $subTotalDiscountPreviousAdd = ($discountedPriceSubTotal * ($qryPreviousRow->add_discount / 100));
                                                $discountedPriceSubTotal = $discountedPriceSubTotal - $subTotalDiscountPreviousAdd;
                                            }

                                            $totalProfitPrevious += ($discountedPriceSubTotal);
                                        } else if ($qryPreviousRow->nameTable == 'payment') {
                                            $totalPaymentsPrevious += $qryPreviousRow->total_amount;
                                        }
                                    }
                                    $openingBalance = number_format(($totalProfitPrevious - $totalPaymentsPrevious), 2, '.', '');
                                }

                                $openingBalance += $customer->balance;
                                $withholdingTax += $totalPayment->withholding_tax;
                                $salesTax += $totalPayment->sales_tax;
                                $totalReturn += $totalPayment->goods_return;
                                $shelfRent += $totalPayment->shelf_rent;
                                $builtyCharges += $totalPayment->builty_charges;
                                $otherExpense += $totalPayment->other_expense;

                                $totalBalance += (($salesPrice - $subTotalDiscountPrice) - $totalPayment->amount) + $openingBalance;
                                $totalBalanceLocal += (($salesPrice - $subTotalDiscountPrice) - $totalPayment->amount) + $openingBalance;
                                $openingBalanceAmountLocal = number_format($openingBalance, 2, '.', '');
                                $totalBalanceAmountLocal = number_format(((($salesPrice - $subTotalDiscountPrice) - $totalPayment->amount) + $openingBalance), 2, '.', '');
                                $SubTotalAmountLocal = number_format(($salesPrice - $subTotalDiscountPrice), 2, '.', '');
                                $distributorProfitLossLocal = number_format((($salesPrice - $subTotalDiscountPrice) - $distributorRatePrice), 2, '.', '');
                                $distributorProfitChart[] = $distributorProfitLossLocal;

                                $factoryProfitLossLocal = number_format((($salesPrice - $subTotalDiscountPrice) - $factoryRatePrice), 2, '.', '');
                                $factoryProfitChart[] = $factoryProfitLossLocal;

                                if (floor($openingBalanceAmountLocal) != 0 || floor($totalBalanceAmountLocal) != 0 || floor($SubTotalAmountLocal) != 0 || floor($distributorProfitLossLocal) != 0 || floor($factoryProfitLossLocal) != 0) {
                                    $countdown++;
                                    ?>
                                    <tr style="font-size: 18px;border: 1px solid #666;">
                                        <td><?= $countdown ?></td>
                                        <?php if ($customer_name == '' || $customer_name == 'All') {
                                            if (!empty($customer->short_code)) {
                                                $cusChart[] = $customer->short_code;
                                            } else {
                                                $cusChart[] = $customer->name;
                                            }
                                            ?>
                                            <td><?php echo $customer->name; ?></td>
                                        <?php } ?>
                                        <td><?php echo $openingBalanceAmountLocal; ?></td>
                                        <td><?php echo $totalBalanceAmountLocal; ?></td>
                                        <td><?php echo $SubTotalAmountLocal; ?></td>
                                        <!--                                        <td>-->
                                        <?php //echo $distributorProfitLossLocal; ?><!--</td>-->
                                        <td><?php echo $factoryProfitLossLocal; ?></td>
                                    </tr>
                                    <?php
                                }
                            }
                        }
                        ?>
                        <tr>
                            <?php if ($customer_name == '' || $customer_name == 'All') {
                                $num = 3;
                            } else {
                                $num = 2;
                            }
                            $distributorPriceSubTotal += number_format((($unitPriceTotalLocal - $totalDiscountLocal) - $distributorPriceTotalLocal), 2, '.', '');
                            $costPriceSubTotal += number_format((($unitPriceTotalLocal - $totalDiscountLocal) - $costPriceTotalLocal), 2, '.', '');
                            ?>
                            <th colspan="<?= $num ?>"
                                style="font-size: 18px;text-align: right; border: 1px solid #000;">
                                Total
                            </th>
                            <th style="font-size: 18px;border: 1px solid #000;"><?= number_format($totalBalanceLocal, 2, '.', '') ?></th>
                            <th style="font-size: 18px;border: 1px solid #000;"><?= number_format(($unitPriceTotalLocal - $totalDiscountLocal), 2, '.', '') ?></th>
                            <!--                            <th style="border: 1px solid #000;">-->
                            <? //= number_format((($unitPriceTotalLocal - $totalDiscountLocal) - $distributorPriceTotalLocal), 2, '.', '') ?><!--</th>-->
                            <th style="font-size: 18px;border: 1px solid #000;"><?= number_format((($unitPriceTotalLocal - $totalDiscountLocal) - $costPriceTotalLocal), 2, '.', '') ?></th>
                        </tr>
                        </tbody>
                    </table>
                    <h2 class="center">Imtiaz Super Mart</h2>
                    <table class="striped demo1 bordered">
                        <thead>
                        <tr style="font-size: 18px;border: 1px solid #666;">
                            <th>S.No</th>
                            <?php if ($customer_name == '' || $customer_name == 'All') { ?>
                                <th>Customer</th>
                            <?php } ?>
                            <th>Opening Balance</th>
                            <th>Total Balance</th>
                            <th>Sub Total</th>
                            <!--                            <th>Profit / Loss Distributor</th>-->
                            <th>Profit / Loss Factory</th>
                        </tr>
                        </thead>
                        <tbody>
                        <?php
                        if ($_SESSION['clone'] == 1) {
                            global $db;
                            $db = new Database(DB_SERVER, DB_USER, DB_PASS, DB_DATABASE);
                            $db->connect();
                            $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) {
//                                    $filterReturn = " WHERE invoice_reference_code = '$qery->id' AND status <> 'Cancel' ";
//                                    $returnAmount = Refund::GetRefundList($filterReturn);
//                                    if(isset($returnAmount)){
//                                        foreach($returnAmount AS $returnAmountRow){
//                                            $totalReturn += $returnAmountRow->amount;
//                                        }
//                                    }
                                    $counter++;
                                    $customer = CustomerSetup::GetCustomerSetupById($qery->custid);
                                    $discount_price = $qery->discount_price;

                                    $productQty = $qery->product_qty;
                                    $costPrice = number_format(($qery->product_qty * $qery->unit_cost_price), 2, '.', '');
                                    $costPriceTotal += $costPrice;
                                    $costPriceTotalMart += $costPrice;
                                    $unitPrice = number_format(($qery->product_qty * $qery->unit_sale_price), 2, '.', '');
                                    $unitPriceTotal += $unitPrice;
                                    $unitPriceTotalMart += $unitPrice;
                                    $distributorPrice = number_format(($qery->product_qty * $qery->unit_distributor_price), 2, '.', '');
                                    $distributorPriceTotal += $distributorPrice;
                                    $distributorPriceTotalMart += $distributorPrice;
                                    $subtotal = $unitPrice - $costPrice;


                                    if (PROJECT_DISCOUNT == 1 || $discount_price != 0) {
                                        $count = 0;
                                        $totalDiscountper = $qery->discount;

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

                                        $subtotalAmountFull = $unitPrice - $subTotalDiscount;
                                        if($qery->add_discount > 0){
                                            $totalDiscountperAdd = $qery->add_discount;
                                            $subTotalDiscountAdd = ($subtotalAmountFull * ($totalDiscountperAdd / 100));
    
                                            $subTotalDiscount +=$subTotalDiscountAdd;
                                            $totalDiscount += $subTotalDiscountAdd;
                                            $totalDiscountMart += $subTotalDiscountAdd;
                                            $subtotal -= $subTotalDiscountAdd;
                                        }
                                    }
                                    $totalProfit += $subtotal;

                                    if (isset($qry[$counter]->custid)) {
                                        $nextCode = $qry[$counter]->custid;
                                    } else {
                                        $nextCode = 0;
                                    }
                                    if ($reset == true) {
                                        $qty = 0;
                                        $factoryRatePrice = 0;
                                        $distributorRatePrice = 0;
                                        $salesPrice = 0;
                                        $subTotalDiscountPrice = 0;
                                        $reset = false;
                                    }
                                    if ($qery->custid == $nextCode) {
                                        $qty += $qery->product_qty;
                                        $factoryRatePrice += $costPrice;
                                        $distributorRatePrice += $distributorPrice;
                                        $salesPrice += $unitPrice;
                                        $subTotalDiscountPrice += $subTotalDiscount;
                                        continue;
                                    } else {
                                        $qty += $qery->product_qty;
                                        $factoryRatePrice += $costPrice;
                                        $distributorRatePrice += $distributorPrice;
                                        $salesPrice += $unitPrice;
                                        $subTotalDiscountPrice += $subTotalDiscount;
                                        $reset = true;
                                        //continue;
                                        //$lastcode = $qery->code;
                                    }
                                    $countdown++;
                                    //echo $qery->customer_id."<br>";
                                    $filterpay = " WHERE pay.customer_id = " . $qery->custid . "
                                                AND DATE_FORMAT(pay.create_date,'%Y-%m-%d')>='$qryDate'
                                                AND DATE_FORMAT(pay.create_date,'%Y-%m-%d')<='$qryTo'
                                                AND pay.status <> 'Cancel'
                                                GROUP BY pay.customer_id
                                                ORDER BY cus.name ";
                                    $totalPayment = Payment::GetTotalPaymentLists($filterpay);
                                    //print_r($totalPayment);


                                    //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') ";
                                    $filterReportPrevious .= " AND inv.customer_id ='$qery->custid'";
                                    $filterReportPrevious .= " UNION SELECT 'payment' AS nameTable, id, '' AS 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' ";
                                    $filterReportPrevious .= " AND customer_id = '$qery->custid'";
                                    $filterReportPrevious .= " ORDER BY create_date, code ";

                                    $qryPrevious = Invoice::GetInvoiceCustomerReportList($filterReportPrevious);
                                    $unitPricePrevious = 0;
                                    $totalDiscountperPrevious = 0;
                                    $subTotalDiscountPrevious = 0;
                                    $totalProfitPrevious = 0;
                                    $totalPaymentsPrevious = 0;
                                    $openingBalance = 0;
                                    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));

                                                $discountedPriceSubTotal = 0;
                                                $discountedPriceSubTotal = $unitPricePrevious - $subTotalDiscountPrevious;

                                                if($qryPreviousRow->add_discount > 0){
                                                    $subTotalDiscountPreviousAdd = ($discountedPriceSubTotal * ($qryPreviousRow->add_discount / 100));
                                                    $discountedPriceSubTotal = $discountedPriceSubTotal - $subTotalDiscountPreviousAdd;
                                                }

                                                $totalProfitPrevious += ($discountedPriceSubTotal);
                                            } else if ($qryPreviousRow->nameTable == 'payment') {
                                                $totalPaymentsPrevious += $qryPreviousRow->total_amount;
                                            }
                                        }
                                        $openingBalance = number_format(($totalProfitPrevious - $totalPaymentsPrevious), 2, '.', '');
                                    }
                                    ?>
                                    <tr style="font-size: 18px;border: 1px solid #666;">
                                        <td><?= $countdown ?></td>
                                        <?php if ($customer_name == '' || $customer_name == 'All') {
                                            if (!empty($customer->short_code)) {
                                                $cusChart[] = $customer->short_code;
                                            } else {
                                                $cusChart[] = $customer->name;
                                            }
                                            ?>
                                            <td><?php echo $customer->name; ?></td>
                                        <?php }

                                        $withholdingTax += $totalPayment->withholding_tax;
                                        $salesTax += $totalPayment->sales_tax;
                                        $totalReturn += $totalPayment->goods_return;
                                        $shelfRent += $totalPayment->shelf_rent;
                                        $builtyCharges += $totalPayment->builty_charges;
                                        $otherExpense += $totalPayment->other_expense;

                                        $totalBalance += (($salesPrice - $subTotalDiscountPrice) - $totalPayment->amount) + $openingBalance;
                                        $totalBalanceMart += (($salesPrice - $subTotalDiscountPrice) - $totalPayment->amount) + $openingBalance;
                                        ?>
                                        <td><?php echo number_format($openingBalance, 2, '.', ''); ?></td>
                                        <td><?php echo number_format(((($salesPrice - $subTotalDiscountPrice) - $totalPayment->amount) + $openingBalance), 2, '.', ''); ?></td>
                                        <td><?php echo number_format(($salesPrice - $subTotalDiscountPrice), 2, '.', ''); ?></td>
                                        <!--                                        <td>--><?php
                                        //                                            $distributorProfitChart[] = number_format((($salesPrice - $subTotalDiscountPrice) - $distributorRatePrice), 0, '.', '');
                                        //                                            echo number_format((($salesPrice - $subTotalDiscountPrice) - $distributorRatePrice), 2, '.', ''); ?><!--</td>-->
                                        <td><?php
                                            $factoryProfitChart[] = number_format((($salesPrice - $subTotalDiscountPrice) - $factoryRatePrice), 0, '.', '');
                                            echo number_format((($salesPrice - $subTotalDiscountPrice) - $factoryRatePrice), 2, '.', ''); ?></td>
                                    </tr>
                                    <?php
                                }
                            }
                            global $db;
                            $db = new Database(DB_SERVERS, DB_USERS, DB_PASS, DB_DATABASES);
                            $db->connect();
                        }
                        ?>
                        <tr>
                            <?php if ($customer_name == '' || $customer_name == 'All') {
                                $num = 3;
                            } else {
                                $num = 2;
                            }
                            $distributorPriceSubTotal += number_format((($unitPriceTotalMart - $totalDiscountMart) - $distributorPriceTotalMart), 2, '.', '');
                            $costPriceSubTotal += number_format((($unitPriceTotalMart - $totalDiscountMart) - $costPriceTotalMart), 2, '.', '');
                            ?>
                            <th colspan="<?= $num ?>"
                                style="font-size: 18px;text-align: right; border: 1px solid #000;">
                                Total
                            </th>
                            <th style="font-size: 18px;border: 1px solid #000;"><?= number_format($totalBalanceMart, 2, '.', '') ?></th>
                            <th style="font-size: 18px;border: 1px solid #000;"><?= number_format(($unitPriceTotalMart - $totalDiscountMart), 2, '.', '') ?></th>
                            <!--                            <th style="border: 1px solid #000;">-->
                            <? //= number_format((($unitPriceTotalMart - $totalDiscountMart) - $distributorPriceTotalMart), 2, '.', '') ?><!--</th>-->
                            <th style="font-size: 18px;border: 1px solid #000;"><?= number_format((($unitPriceTotalMart - $totalDiscountMart) - $costPriceTotalMart), 2, '.', '') ?></th>
                        </tr>
                        <tr>
                            <th colspan="8"><h2 class="center">Grand Total</h2></th>
                        </tr>
                        <tr>
                            <?php if ($customer_name == '' || $customer_name == 'All') {
                                $num = 3;
                            } else {
                                $num = 2;
                            } ?>
                            <th colspan="<?= $num ?>"
                                style="font-size: 18px;text-align: right; border: 1px solid #000;">
                                Wholesaler Total
                            </th>
                            <th style="font-size: 18px;border: 1px solid #000;"><?= $openingWholesale ?></th>
                            <th style="font-size: 18px;border: 1px solid #000;"><?= $subTotalWholesale ?></th>
                            <!--                            <th style="border: 1px solid #000;">0</th>-->
                            <th style="font-size: 18px;border: 1px solid #000;"><?= $factoryWholesale; ?></th>
                        </tr>
                        <tr>
                            <?php if ($customer_name == '' || $customer_name == 'All') {
                                $num = 3;
                            } else {
                                $num = 2;
                            } ?>
                            <th colspan="<?= $num ?>"
                                style="font-size: 18px;text-align: right; border: 1px solid #000;">
                                Local Mart Total
                            </th>
                            <th style="font-size: 18px;border: 1px solid #000;"><?= number_format($totalBalanceLocal, 2, '.', '') ?></th>
                            <th style="font-size: 18px;border: 1px solid #000;"><?= number_format(($unitPriceTotalLocal - $totalDiscountLocal), 2, '.', '') ?></th>
                            <!--                            <th style="border: 1px solid #000;">-->
                            <? //= number_format((($unitPriceTotalLocal - $totalDiscountLocal) - $distributorPriceTotalLocal), 2, '.', '') ?><!--</th>-->
                            <th style="font-size: 18px;border: 1px solid #000;"><?= number_format((($unitPriceTotalLocal - $totalDiscountLocal) - $costPriceTotalLocal), 2, '.', '') ?></th>
                        </tr>
                        <tr>
                            <?php if ($customer_name == '' || $customer_name == 'All') {
                                $num = 3;
                            } else {
                                $num = 2;
                            } ?>
                            <th colspan="<?= $num ?>"
                                style="font-size: 18px;text-align: right; border: 1px solid #000;">
                                Imtiaz Super Mart Total
                            </th>
                            <th style="font-size: 18px;border: 1px solid #000;"><?= number_format($totalBalanceMart, 2, '.', '') ?></th>
                            <th style="font-size: 18px;border: 1px solid #000;"><?= number_format(($unitPriceTotalMart - $totalDiscountMart), 2, '.', '') ?></th>
                            <!--                            <th style="border: 1px solid #000;">-->
                            <? //= number_format((($unitPriceTotalMart - $totalDiscountMart) - $distributorPriceTotalMart), 2, '.', '') ?><!--</th>-->
                            <th style="font-size: 18px;border: 1px solid #000;"><?= number_format((($unitPriceTotalMart - $totalDiscountMart) - $costPriceTotalMart), 2, '.', '') ?></th>
                        </tr>
                        <tr>
                            <?php if ($customer_name == '' || $customer_name == 'All') {
                                $num = 3;
                            } else {
                                $num = 2;
                            } ?>
                            <th colspan="<?= $num ?>"
                                style="font-size: 18px;text-align: right; border: 1px solid #000;">
                                Total
                            </th>
                            <th style="font-size: 18px;border: 1px solid #000;"><?= number_format($totalBalance, 2, '.', '') ?></th>
                            <th style="font-size: 18px;border: 1px solid #000;"><?= number_format(($unitPriceTotal - $totalDiscount), 2, '.', '') ?></th>
                            <!--                            <th style="border: 1px solid #000;">-->
                            <? //= $distributorPriceSubTotal; ?><!--</th>-->
                            <th style="font-size: 18px;border: 1px solid #000;"><?= $costPriceSubTotal; ?></th>
                        </tr>
                        </tbody>
                    </table>
                </div>
                <table>
                        <tr><td><h2 class="center">Factory Expense</h2></td></tr>
                </table>
                <?php
                $Income = $costPriceSubTotal;
                if ($customer_name == 'All') {
                    $filterExpenseReport = " AS ex RIGHT JOIN " . TABLE_EXPENSECATEGORYSETUP . " AS exCat ON ex.category_id = exCat.id WHERE DATE_FORMAT(lastupdated,'%Y-%m-%d')>='$qryDate' and DATE_FORMAT(lastupdated,'%Y-%m-%d')<='$qryTo' ";
                    $filterExpenseReport .= " ORDER BY exCat.parent_id";
                    echo '<table class="display bordered table striped">';
                    $qryExpense = ExpenseSetup::GetExpenseSetupList($filterExpenseReport);
                    if ($qryExpense) {
                        $counter = 0;
                        $counterSerial = 0;
                        $amountTotal = 0;
                        $amountSubTotal = 0;
                        foreach ($qryExpense as $qery) {
                            $exPCategory = ExpenseCategorySetup::GetExpenseCategorySetupById($qery->parent_id);
                            $counter++;
                            if ($exPCategory->name != $mainCat && $counter != 1) {
                                echo '<span class="right">' . $amountSubTotal . '</span></th></tr>';
                            }
                            if ($catName != $exPCategory->name) {
                                $amountSubTotal = 0;
                                $counterSerial = 0;
                                echo '
    <tr><th colspan="4" style="font-size: 18px;border: 1px solid #000;"><span class="left">' . $exPCategory->name . '</span>';
                            }
                            $counterSerial++;
                            $amountSubTotal += $qery->amount;
                            $amountTotal += $qery->amount;
                            $catName = $exPCategory->name;
                            $mainCat = $exPCategory->name;
                        }
                        echo '<span class="right">' . $amountSubTotal . '</span></th></tr>';
                    }
                    if ($_SESSION['clone'] == 1 && $customer_name == 'All') {
                        global $db;
                        $db = new Database(DB_SERVER, DB_USER, DB_PASS, DB_DATABASE);
                        $db->connect();
                        $qryExpense = ExpenseSetup::GetExpenseSetupList($filterExpenseReport);
                        if ($qryExpense) {
                            $counter = 0;
                            $counterSerial = 0;
                            $amountTotal = 0;
                            $amountSubTotal = 0;
                            foreach ($qryExpense as $qery) {
                                $exPCategory = ExpenseCategorySetup::GetExpenseCategorySetupById($qery->parent_id);
                                $counter++;
                                if ($exPCategory->name != $mainCat && $counter != 1) {
                                    echo '<span class="right">' . $amountSubTotal . '</span></th></tr>';
                                }
                                if ($catName != $exPCategory->name) {
                                    $amountSubTotal = 0;
                                    $counterSerial = 0;
                                    echo '
    <tr><th colspan="4" style="font-size: 18px;border: 1px solid #666;"><span class="left">' . $exPCategory->name . '</span>';
                                }
                                $counterSerial++;
                                $amountSubTotal += $qery->amount;
                                $amountTotal += $qery->amount;
                                $catName = $exPCategory->name;
                                $mainCat = $exPCategory->name;
                            }
                            echo '<span class="right">' . $amountSubTotal . '</span></th></tr>';
                        }

                        $filterLoan = " WHERE DATE_FORMAT(create_date,'%Y-%m-%d')>='$qryDate' and DATE_FORMAT(create_date,'%Y-%m-%d')<='$qryTo' and status = 'active' ";
                        $qryLoan = LoanSetup::GetLoanList($filterLoan);
                        $loan = 0;
                        if ($qryLoan){
                            foreach($qryLoan AS $qryLoanRow){
                                $loan += $qryLoanRow->amount;
                            }
                        }

                        $amountTotal += $loan;
                    
                        global $db;
                        $db = new Database(DB_SERVERS, DB_USERS, DB_PASS, DB_DATABASES);
                        $db->connect();
                    }


                    //Salary
                    $filterSalaryReport = " WHERE DATE_FORMAT(date_time,'%Y-%m-%d')>='$qryDate' and DATE_FORMAT(date_time,'%Y-%m-%d')<='$qryTo' ";
                    $filterSalaryReport .= " ORDER BY employee_id";
                    $qrySalary = SalarySetup::GetSalarySetupList($filterSalaryReport);
                    if ($qrySalary) {
                        $totalSalary = 0;
                        foreach ($qrySalary as $qery) {
                            $totalSalary += $qery->amount;
                        }
                        //                                    if($qery->advance == 1){
                        //                                        echo '<table class="display table table-bordered table-striped">
                        //<tr><th colspan="4"><span class="left">'.$empId->name.' + (advance)'.'</span>';
                        //                                    }else{
                        //                                        echo '<table class="display table table-bordered table-striped">
                        //<tr><th colspan="4"><span class="left">'.$empId->name.'</span>';
                        //                                    }

                        echo '<table class="display bordered table striped">
    <tr><th colspan="4" style="font-size: 18px;border: 1px solid #666; border-top:none; border-bottom: none;"><span class="left">Factory Salary</span>';
                        echo '<span class="right">' . $totalSalary . '</span></th></tr></table>';
                    }
                    if ($_SESSION['clone'] == 1 && $customer_name == 'All') {
                        global $db;
                        $db = new Database(DB_SERVER, DB_USER, DB_PASS, DB_DATABASE);
                        $db->connect();

                        $filterSalaryReport = " WHERE DATE_FORMAT(date_time,'%Y-%m-%d')>='$qryDate' and DATE_FORMAT(date_time,'%Y-%m-%d')<='$qryTo' ";
                        $filterSalaryReport .= " ORDER BY employee_id";
                        $qrySalary = SalarySetup::GetSalarySetupList($filterSalaryReport);
                        if ($qrySalary) {
                            $totalSalary = 0;
                            foreach ($qrySalary as $qery) {
                                $totalSalary += $qery->amount;
                            }
                            //                                    if($qery->advance == 1){
                            //                                        echo '<table class="display table table-bordered table-striped">
                            //<tr><th colspan="4"><span class="left">'.$empId->name.' + (advance)'.'</span>';
                            //                                    }else{
                            //                                        echo '<table class="display table table-bordered table-striped">
                            //<tr><th colspan="4"><span class="left">'.$empId->name.'</span>';
                            //                                    }

                            echo '<table class="display bordered table striped">
    <tr><th colspan="4" style="font-size: 18px;border: 1px solid #666; border-top:none; border-bottom: none;"><span class="left">FACTORY SALARY</span>';
                            echo '<span class="right">' . $totalSalary . '</span></th></tr></table>';
                        }
                        $amountTotal += $totalSalary;
                        global $db;
                        $db = new Database(DB_SERVERS, DB_USERS, DB_PASS, DB_DATABASES);
                        $db->connect();
                    }

                    echo '</table>
    <table class="display bordered table striped">
    <tr><th colspan="4" style="font-size: 18px;border: 1px solid #666; border-top:none;"><span class="left">FACTORY LOAN</span>';
                    echo '<span class="right">' . $loan . '</span></th></tr>';
                    echo '</table>';

                    echo '</table>
    <table class="display bordered table striped">
    <tr><th colspan="4" style="font-size: 24px;background: #ffb3b3;border: 1px solid #666;"><span class="left">Total</span>';
                    echo '<span class="right">' . $amountTotal . '</span></th></tr>';
                    echo '</table><br>';

                    echo '<table>
                                <tr><td><h2 class="center">Mart Expense</h2></td></tr>
                        </table>';

                    if ($_SESSION['clone'] == 1 && $customer_name == 'All') {
                        global $db;
                        $db = new Database(DB_SERVER, DB_USER, DB_PASS, DB_DATABASE);
                        $db->connect();
                        $filterMartLoan = " WHERE DATE_FORMAT(create_date,'%Y-%m-%d')>='$qryDate' and DATE_FORMAT(create_date,'%Y-%m-%d')<='$qryTo' and status = 'active' ";
                        $qryMartLoan = LoanSetupMart::GetLoanList($filterMartLoan);
                        $martLoan = 0;
                        if ($qryMartLoan){
                            foreach($qryMartLoan AS $qryMartLoanRow){
                                $martLoan += $qryMartLoanRow->amount;
                            }
                        }
                        $amountTotal += $martLoan;

                        $filterExpenseReportMart = " AS ex RIGHT JOIN " . TABLE_EXPENSEMARTCATEGORYSETUP . " AS exCat ON ex.category_id = exCat.id WHERE DATE_FORMAT(lastupdated,'%Y-%m-%d')>='$qryDate' and DATE_FORMAT(lastupdated,'%Y-%m-%d')<='$qryTo' ";
                        $filterExpenseReportMart .= " ORDER BY exCat.parent_id";
                        echo '<table class="display bordered table striped">';
                        $qryMartExpense = ExpenseMartSetup::GetExpenseMartSetupList($filterExpenseReportMart);
                        if ($qryMartExpense) {
                            $counterMart = 0;
                            $counterSerialMart = 0;
                            $amountTotalMart = 0;
                            $amountSubTotalMart = 0;
                            foreach ($qryMartExpense as $qery) {
                                $exPCategoryMart = ExpenseMartCategorySetup::GetExpenseMartCategorySetupById($qery->parent_id);
                                $counterMart++;
                                if ($exPCategoryMart->name != $mainCatMart && $counterMart != 1) {
                                    echo '<span class="right">' . $amountSubTotalMart . '</span></th></tr>';
                                }
                                if ($catNameMart != $exPCategoryMart->name) {
                                    $amountSubTotalMart = 0;
                                    $counterSerialMart = 0;
                                    echo '
    <tr><th colspan="4" style="font-size: 18px;border: 1px solid #666;"><span class="left">' . $exPCategoryMart->name . '</span>';
                                }
                                $counterSerialMart++;
                                $amountSubTotalMart += $qery->amount;
                                $amountTotal += $qery->amount;
                                $amountTotalMart += $qery->amount;
                                $catNameMart = $exPCategoryMart->name;
                                $mainCatMart = $exPCategoryMart->name;
                            }
                            echo '<span class="right">' . $amountSubTotalMart . '</span></th></tr>';
                        }

                        $filterLoan = " WHERE DATE_FORMAT(create_date,'%Y-%m-%d')>='$qryDate' and DATE_FORMAT(create_date,'%Y-%m-%d')<='$qryTo' and status = 'active' ";
                        $qryLoan = LoanSetup::GetLoanList($filterLoan);
                        $loan = 0;
                        if ($qryLoan){
                            foreach($qryLoan AS $qryLoanRow){
                                $loan += $qryLoanRow->amount;
                            }
                        }

                        $amountTotal += $loan;
                        $amountTotalMart += $loan;
                    
                        global $db;
                        $db = new Database(DB_SERVERS, DB_USERS, DB_PASS, DB_DATABASES);
                        $db->connect();
                    }

                    
                    $amountTotal += $withholdingTax;
                    $amountTotal += $salesTax;
                    $amountTotal += $totalReturn;

                    $amountTotal += $shelfRent;
                    $amountTotal += $builtyCharges;
                    $amountTotal += $otherExpense;

                    $amountTotalMart += $withholdingTax;
                    $amountTotalMart += $salesTax;
                    $amountTotalMart += $totalReturn;

                    $amountTotalMart += $shelfRent;
                    $amountTotalMart += $builtyCharges;
                    $amountTotalMart += $otherExpense;
                    echo '</table>
    <table class="display bordered table striped">
    <tr><th colspan="4" style="font-size: 18px;border: 1px solid #666; border-top:none;"><span class="left">Total Withholding Tax - (4.5%)</span>';
                    echo '<span class="right">' . $withholdingTax . '</span></th></tr>';
                    echo '</table>';

                    echo '</table>
    <table class="display bordered table striped">
    <tr><th colspan="4" style="font-size: 18px;border: 1px solid #666; border-top:none;"><span class="left">Total Sales Tax - (17%)</span>';
                    echo '<span class="right">' . $salesTax . '</span></th></tr>';
                    echo '</table>';

                    echo '</table>
    <table class="display bordered table striped">
    <tr><th colspan="4" style="font-size: 18px;border: 1px solid #666; border-top:none;"><span class="left">Total Goods Return</span>';
                    echo '<span class="right">' . $totalReturn . '</span></th></tr>';
                    echo '</table>';

                    echo '</table>
    <table class="display bordered table striped">
    <tr><th colspan="4" style="font-size: 18px;border: 1px solid #666; border-top:none;"><span class="left">Total Shelf Rent</span>';
                    echo '<span class="right">' . $shelfRent . '</span></th></tr>';
                    echo '</table>';

                    echo '</table>
    <table class="display bordered table striped">
    <tr><th colspan="4" style="font-size: 18px;border: 1px solid #666; border-top:none;"><span class="left">Total Builty Charges</span>';
                    echo '<span class="right">' . $builtyCharges . '</span></th></tr>';
                    echo '</table>';

                    echo '</table>
    <table class="display bordered table striped">
    <tr><th colspan="4" style="font-size: 18px;border: 1px solid #666; border-top:none;"><span class="left">Total Other Expense</span>';
                    echo '<span class="right">' . $otherExpense . '</span></th></tr>';
                    echo '</table>';

    //                 echo '</table>
    // <table class="display bordered table striped">
    // <tr><th colspan="4" style="font-size: 18px;border: 1px solid #666; border-top:none;"><span class="left">Total Factory Expense</span>';
    //                 echo '<span class="right">' . $amountTotal . '</span></th></tr>';
    //                 echo '</table>';

                    if ($_SESSION['clone'] == 1 && $customer_name == 'All') {
                        global $db;
                        $db = new Database(DB_SERVER, DB_USER, DB_PASS, DB_DATABASE);
                        $db->connect();
                                    
                        $filterMartSalary = " WHERE DATE_FORMAT(date_time,'%Y-%m-%d')>='$qryDate' and DATE_FORMAT(date_time,'%Y-%m-%d')<='$qryTo' ";
                        $qryMartSalary = SalarySetupMart::GetSalarySetupList($filterMartSalary);
                        $martSalary = 0;
                        if ($qryMartSalary){
                            foreach($qryMartSalary AS $qryMartSalaryRow){
                                $martSalary += $qryMartSalaryRow->amount;
                            }
                        }
                        $amountTotalMartSalary += $martSalary;

                        echo '<table class="display bordered table striped">
                <tr><th colspan="4" style="font-size: 18px;border: 1px solid #666; border-top:none; border-bottom: none;"><span class="left">Mart Salary</span>';
                        echo '<span class="right">' . $amountTotalMartSalary . '</span></th></tr></table>';

                        $amountTotal += $amountTotalMartSalary;
                        $amountTotalMart += $amountTotalMartSalary;

                        global $db;
                        $db = new Database(DB_SERVERS, DB_USERS, DB_PASS, DB_DATABASES);
                        $db->connect();
                    }

                    $costPriceSubTotal -= $amountTotal;
                    // $costPriceSubTotal -= $totalSalary;
//                    $costPriceSubTotal -= $amountTotalMartSalary;
//                    $costPriceSubTotal -= $totalReturn;
                    
                    echo '</table>
                        <table class="display bordered table striped">
                        <tr><th colspan="4" style="font-size: 18px;border: 1px solid #666; border-top:none;"><span class="left">Mart Loan</span>';
                    echo '<span class="right">' . $martLoan . '</span></th></tr>';
                    echo '</table>';


                    echo '<table class="display bordered table striped">
                        <tr><th colspan="4" style="font-size: 24px;background: #ffb3b3;border: 1px solid #666;"><span class="left">Total</span>';
                    echo '<span class="right">' . $amountTotalMart  . '</span></th></tr></table><br>';

                    echo '<table>
                                <tr><td><h2 class="center">Total Profit</h2></td></tr>
                        </table>';

                    echo '<table class="display bordered table striped">
                        <tr><th colspan="4" style="font-size: 24px;background: #e6ffcc;border: 1px solid #666;"><span class="left">Grand Total</span>';
                    echo '<span class="right">' . $Income . '</span></th></tr></table>';

                    echo '<table class="display bordered table striped">
                        <tr><th colspan="4" style="font-size: 24px;background: #ffb3b3;border: 1px solid #666;"><span class="left">Grand Expense</span>';
                    echo '<span class="right">' . number_format($amountTotal, 2, '.', '')  . '</span></th></tr></table>';

                        echo '<table class="display bordered table striped">
    <tr><th colspan="4" style="font-size: 24px;background: #e6ffcc;border: 1px solid #666;"><span class="left">Net Profit</span>';
                    echo '<span class="right">' . $costPriceSubTotal . '</span></th></tr></table>';
                }
                $director = DirectorSetup::GetDirectorSetupList();
                $totalShare = 0;
                foreach($director AS $directorRow){
                    $share = $costPriceSubTotal*(intval($directorRow->share)/100);
                    $totalShare += $share;
                    echo '<table class="display bordered table striped">
    <tr><th colspan="4" style="font-size: 18px;border: 1px solid #666; border-top:none; border-bottom: none;"><span class="left">'.$directorRow->name.' - '.$directorRow->share.'% - '.$directorRow->designation.'</span>';
                    echo '<span class="right">' . number_format($share, 2, '.', '') . '</span></th></tr></table>';
                }
                $remainingAmount = $costPriceSubTotal-$totalShare;
                if($remainingAmount >0){
                    echo '<table class="display bordered table striped">
    <tr><th colspan="4" style="font-size: 18px;border: 1px solid #666; border-top:none; border-bottom: none;"><span class="left">Remaining Amount</span>';
                    echo '<span class="right">' . number_format($remainingAmount, 2, '.', '') . '</span></th></tr></table>';
                }
            } // 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();
        });

        $("#print").on("click", function (e) {
            var fewSeconds = 2;
            e.preventDefault();
            $('#searchfrm').prop('target', '_blank');
            $('#searchfrm').prop('action', "<?=PROJECT_ADMIN_URL?>report/print/cumartcatNew.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');
        <?php if(!empty($cat_name)){ ?>
        var ctx = document.getElementById("myChart").getContext('2d');
        var myChart = new Chart(ctx, {
            type: 'bar',
            data: {
                labels: [<?php
                    if($cusChart){
                    $countingChart = 0;
                        foreach($cusChart AS $cusChartRow){
                            $countingChart++;
                            //if($countingChart <= 10){
                            $labelName = (strlen($cusChartRow) > 10 ? substr($cusChartRow, 0, 10) : $cusChartRow);
                                echo '"'.$labelName.'",';
                            //}
                        }
                    }
                    ?>],
                datasets: [
                    {
                        label: "Profit / Loss Distributor",
                        fillColor: "#E67A77",
                        strokeColor: "#E67A77",
                        backgroundColor: "#428bca",
                        data: [<?php
                            if($distributorProfitChart){
                                $countingChart=0;
                                foreach($distributorProfitChart AS $distributorProfitChartRow){
                                    $countingChart++;
                                    //if($countingChart <= 10){
                                        echo ''.$distributorProfitChartRow.',';
                                    //}
                                }
                            }
                            ?>],
                    },
                    {
                        label: "Profit / Loss Factory",
                        fillColor: "#79D1CF",
                        strokeColor: "#79D1CF",
                        backgroundColor: "#0B8703",
                        data: [<?php
                            if($factoryProfitChart){
                                $countingChart=0;
                                foreach($factoryProfitChart AS $factoryProfitChartRow){
                                $countingChart++;
                                //if($countingChart <= 10){
                                        echo ''.$factoryProfitChartRow.',';
                                    //}
                                }
                            }
                            ?>]
                    }
                ],
            },
            options: {
                scales: {
                    yAxes: [{
                        ticks: {
                            beginAtZero: true
                        }
                    }]
                }
            }
        });
        <?php } ?>
    });
</script>
</body>
</html>