<?php
error_reporting(E_ERROR | E_STRICT);
//error_reporting('E_ALL');
ini_set('display_errors', '1');
try {

    if (!isset($_REQUEST['datefrom'])) {
        //header('location: ../invoice.php');
        exit;
    } else {
        //$id = $_GET['print'];
    }
    $product_id = $_GET['product_id'];
    $customer_name = $_GET['customer_name'];

    include_once('../../../classes/manager.class.php');
    include_once('../../../classes/PHPMailer/PHPMailerAutoload.php');
    include_once('../../../fpdf/fpdf1.php');


    $m = new Manager();
    extract($_REQUEST);
    $param_data = ControlConfifguration::GetConfiguration();
    define('PROJECT_NAME', $param_data->name);
    define('PROJECT_ADDRESS', $param_data->address);
    define('PROJECT_TEL', $param_data->contact);
    define('PROJECT_EMAIL', $param_data->email);
    define('PROJECT_WEBSITE', $param_data->website);
    define('PROJECT_COLOR', $param_data->color);
    define('PROJECT_DISCOUNT', $param_data->is_discount);
    define('PROJECT_TAX', $param_data->is_tax);

    $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 .= " 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


    $invoiceW = Invoice::GetInvoiceReportList($filterReportW);
    $invoice = Invoice::GetInvoiceReportList($filterReport);
    $invoiceLocalGT = Invoice::GetInvoiceReportList($filterReportLGT);
    $invoiceLocal = Invoice::GetInvoiceReportList($filterReportL);

    //Expense and Salary
    $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";
    $qryExpense = ExpenseSetup::GetExpenseSetupList($filterExpenseReport);

    $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";
    $qryExpenseMart = ExpenseMartSetup::GetExpenseMartSetupList($filterExpenseReportMart);

    $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);
    $qryExpense2 = [];
    $qrySalary2 = [];
    if ($_SESSION['clone'] == 1 && $customer_name == 'All') {
        global $db;
        $db = new Database(DB_SERVER, DB_USER, DB_PASS, DB_DATABASE);
        $db->connect();

        $qryExpense2 = ExpenseSetup::GetExpenseSetupList($filterExpenseReport);
        $qryExpense2Mart = ExpenseMartSetup::GetExpenseMartSetupList($filterExpenseReportMart);
        $qrySalary2 = SalarySetup::GetSalarySetupList($filterSalaryReport);

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

    if (!empty($invoice)) {

        $font = 10;
        $picx = 100;
        $setx = 5;
        $multi = 210;
        $picsetx = 150;
        $w = array(50, 80, 50, 80);
        $path = "../../../";

        $pdf = new FPDFWithOutWaterMark('P', 'mm', 'A4');
        //exit;
        $pdf->SetMargins(0, 0, 0);

        $pdf->SetTitle('Cumulative Profit Loss Report');
        $pdf->AddPage();
        $pdf->Ln();
        $pdf->SetFont('Arial', 'B', 16);
        $pdf->Cell(0, 8, PROJECT_NAME, 0, 0, 'C');
        $pdf->SetX($setx);
        $pdf->SetFont('Arial', '', 8);
        $pdf->Cell(0, 8, 'Printed Date: ' . date('d-m-Y h:i A'), 0, 0, 'L');
        $pdf->Ln();
        $pdf->SetFont('Arial', '', 14);
        $pdf->Cell(0, 6, 'Cumulative Profit Loss Report', 0, 0, 'C');

        if ($customer_name != 'All') {
            $customer = CustomerSetup::GetCustomerSetupById($customer_name);
            $pdf->Ln();
            $pdf->SetFont('Arial', '', 14);
            $pdf->Cell(0, 6, $customer->name, 0, 0, 'C');
        }

        $pdf->Ln();
        $pdf->SetFont('Arial', '', 7);
        $pdf->Cell(0, 4, 'For the period of: ' . date('d-m-Y', strtotime($datefrom)) . ' - ' . date('d-m-Y', strtotime($dateto)), 0, 0, 'C');

        $pdf->Ln();
        $pdf->Ln();
        $pdf->SetX($setx);
        if ($customer_name == '' || $customer_name == 'All') {
            $header = array('S.No', 'Customer', 'Opening Balance', 'Total Balance', 'Sub Total', 'Profit Fact.');
        } else {
            $customer = CustomerSetup::GetCustomerSetupById($customer_name);
            $header = array('S.No', 'Customer', 'Opening Balance', 'Total Balance', 'Sub Total', 'Profit Fact.');
        }
        //$header = array('S.No', 'Date', 'Invoice', 'Customer', 'Product', 'Status', 'Qty', 'Factory Rate', 'Factory Price', 'Dist. Rate', 'Net Pay.', 'Rate', 'Sale Price', 'Discount', 'Profit/Loss Dist.', 'Profit/Loss Fact.');

//        $filterProductInvoice = " WHERE invoice_id = '$invoice_id'";
//        $productData = Invoice::GetInvoiceProducts($filterProductInvoice);

        function FancyTable($header, $dataW, $data, $dataL, $product_id, $customer_name, $setx, $qryDate, $qryTo, $filterReportW = '', $filterReport = '', $qryExpense = '', $qrySalary = '', $qryExpense2 = '', $qrySalary2 = '', $qryExpenseMart = '', $qryExpense2Mart = '')
        {
            global $pdf;

            $totalDiscount = 0;
            $productQtyTotal = 0;
            $costPriceTotal = 0;
            $unitPriceTotal = 0;
            $totalProfit = 0;
            $costPriceTotalLocal = 0;
            $costPriceTotalLocalGT = 0;
            $unitPriceTotalLocal = 0;
            $unitPriceTotalLocalGT = 0;
            $distributorPriceTotalLocal = 0;
            $distributorPriceTotalLocalGT = 0;
            $totalDiscountLocal = 0;
            $totalDiscountLocalGT = 0;

            // Colors, line width and bold font
            $pdf->SetFillColor(224, 235, 255);
            $pdf->SetTextColor(0);
            $pdf->SetDrawColor(128, 0, 0);
            $pdf->SetLineWidth(.1);
            $pdf->SetFont('Arial', '', 7.5);
            // Header
            if ($customer_name == '' || $customer_name == 'All') {
                $wr = array(7, 73, 22, 32, 32, 34);
            } else {
                $wr = array(7, 73, 22, 32, 32, 34);
            }
            
            $pdf->SetX($setx);
            $pdf->SetFont('Arial', '', 14);
            //$pdf->Cell(200, 7, 'Wholesaler', '', 0, 'C', false);
            // $pdf->Ln();
            // $pdf->SetX($setx);
            // $pdf->SetFont('Arial', '', 7);
            // for ($i = 0; $i < count($header); $i++)
            //     $pdf->Cell($wr[$i], 7, $header[$i], 1, 0, 'C', true);
            // $pdf->Ln();
            // // Color and font restoration
            // $pdf->SetFillColor(224, 235, 255);
            // $pdf->SetTextColor(0);
            // $pdf->SetFont('');
            // Data
            $fill = false;

            $counter = 0;
            $counter_pagebreak = 1;
            $totalAmount = 0;
            $distributorPriceTotal = 0;
            $totalReturn = 0;
            $withholdingTax = 0;
            $salesTax = 0;
            if($dataW){
                $counter = 0;
                $countdown = 0;
                $reset = false;
                $qty = 0;
                $factoryRatePrice = 0;
                $salesPrice = 0;
                $subTotalDiscountPrice = 0;
                $totalBalance = 0;
                $costPriceSubTotal = 0;
                foreach ($dataW AS $row) {
//                    $filterReturn = " WHERE invoice_reference_code = '$row->id' AND status <> 'Cancel' ";
//                    $returnAmount = Refund::GetRefundList($filterReturn);
//                    if(isset($returnAmount)){
//                        foreach($returnAmount AS $returnAmountRow){
//                            $totalReturn += $returnAmountRow->amount;
//                        }
//                    }
                    $counter++;
                    $customer = CustomerSetup::GetCustomerSetupById($row->custid);
                    $salesPerson = User_setup::GetUserSetupId($row->sales_person_id);
                    $discount_price = $row->discount_price;

                    $productQty = $row->product_qty;
                    $costPrice = number_format(($row->product_qty * $row->unit_cost_price), 2, '.', '');
                    $costPriceTotal += $costPrice;
                    $unitPrice = number_format(($row->product_qty * $row->unit_sale_price), 2, '.', '');
                    $unitPriceTotal += $unitPrice;
                    $subtotal = $unitPrice - $costPrice;


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

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

                    if(isset($dataW[$counter]->custid)){
                        $nextCode = $dataW[$counter]->custid;
                    }else{
                        $nextCode = 0;
                    }
                    if($reset == true){
                        $qty = 0;
                        $factoryRatePrice = 0;
                        $distributorRatePrice = 0;
                        $salesPrice = 0;
                        $subTotalDiscountPrice = 0;
                        $reset = false;
                    }
                    if($row->custid == $nextCode){
                        $qty += $row->product_qty;
                        $factoryRatePrice += $costPrice;
                        $salesPrice += $unitPrice;
                        $subTotalDiscountPrice += $subTotalDiscount;
                        continue;
                    }else{
                        $qty += $row->product_qty;
                        $factoryRatePrice += $costPrice;
                        $salesPrice += $unitPrice;
                        $subTotalDiscountPrice += $subTotalDiscount;
                        $reset = true;
                    }

                    //echo $qery->customer_id."<br>";
                    $filterpay = " WHERE pay.customer_id = " . $row->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 ='$row->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 = '$row->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));

                                $totalProfitPrevious += ($unitPricePrevious - $subTotalDiscountPrevious);
                            } 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;

                    $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) {
                    //     $pdf->SetX($setx);
                    //     $pdf->SetFont('Arial', '', 7);
                    //     $countdown++;
                    //     $pdf->Cell($wr[0], 6, $countdown, 'LRBT', 0, 'C', $fill);
                    //     if ($customer_name == '' || $customer_name == 'All') {
                    //         $pdf->SetFont('Arial', '', 6);
                    //         $pdf->Cell($wr[1], 6, strlen($customer->name) > 55 ? substr($customer->name, 0, 55) . "..." : $customer->name, 'LRBT', 0, 'L', $fill);
                    //         $pdf->SetFont('Arial', '', 7);
                    //         $pdf->Cell($wr[2], 6, $openingBalanceAmount, 'LRBT', 0, 'R', $fill);
                    //         $pdf->Cell($wr[3], 6, $totalBalanceAmount, 'LRBT', 0, 'R', $fill);
                    //         $pdf->Cell($wr[4], 6, $SubTotalAmount, 'LRBT', 0, 'R', $fill);
                    //         $pdf->Cell($wr[5], 6, $pfAmount, 'LRBT', 0, 'R', $fill);
                    //     } else {
                    //         $pdf->Cell($wr[1], 6, strlen($customer->name) > 55 ? substr($customer->name, 0, 55) . "..." : $customer->name, 'LRBT', 0, 'L', $fill);
                    //         $pdf->Cell($wr[2], 6, $openingBalanceAmount, 'LRBT', 0, 'R', $fill);
                    //         $pdf->Cell($wr[3], 6, $totalBalanceAmount, 'LRBT', 0, 'R', $fill);
                    //         $pdf->Cell($wr[4], 6, $SubTotalAmount, 'LRBT', 0, 'R', $fill);
                    //         $pdf->Cell($wr[5], 6, $pfAmount, 'LRBT', 0, 'R', $fill);
                    //     }
                    //     $pdf->Ln();
                    // }

                    // if ($counter_pagebreak == 36 || ($counter_pagebreak != 36 && ($counter_pagebreak) % 40 == 0)) {
                    //     $counter_pagebreak = 1;
                    //     $pdf->AddPage();
                    //     $pdf->SetX($setx);
                    //     $pdf->SetFont('Arial', '', 7);
                    //     for ($i = 0; $i < count($header); $i++)
                    //         $pdf->Cell($wr[$i], 7, $header[$i], 1, 0, 'C', true);
                    // }


                }
                $openingWholesale = number_format($totalBalance, 2, '.', '');
                $subTotalWholesale = number_format(($unitPriceTotal - $totalDiscount), 2, '.', '');
                $factoryWholesale = $costPriceSubTotal;

                //$pdf->Ln();
                // $pdf->SetX($setx);
                // $pdf->SetFont('Arial', '', 7);
                // $pdf->Cell($wr[0], 6, '', 'LBT', 0, 'L');
                // $pdf->Cell($wr[1], 6, "", 'BT', 0, 'R');

                // $pdf->Cell($wr[2], 6, "Wholesaler Total", 'RBT', 0, 'R');
                // $pdf->Cell($wr[3], 6, $openingWholesale, 'LRBT', 0, 'R', "");
                // $pdf->Cell($wr[4], 6, $subTotalWholesale, 'LRBT', 0, 'R', "");
                // $pdf->Cell($wr[5], 6, $factoryWholesale, 'LRBT', 0, 'R', "");

                // $pdf->Ln();
                // $pdf->Ln();
                // $fill = !$fill;
                // $counter_pagebreak++;
            }
            if($dataL){

                // $pdf->AddPage();
                // $pdf->SetX($setx);
                // $pdf->SetFont('Arial', '', 14);
                // $pdf->Cell(200, 7, 'Local Mart', '', 0, 'C', false);
                // $pdf->Ln();
                // $pdf->SetFont('Arial', '', 7);
                // $pdf->SetX($setx);
                // for ($i = 0; $i < count($header); $i++)
                //     $pdf->Cell($wr[$i], 7, $header[$i], 1, 0, 'C', true);
                // $pdf->Ln();
                // // Color and font restoration
                // $pdf->SetFillColor(224, 235, 255);
                // $pdf->SetTextColor(0);
                // $pdf->SetFont('');
                // // Data
                // $fill = false;

                $counter = 0;
                $countdown = 1;
                $reset = false;
                $qty = 0;
                $factoryRatePrice = 0;
                $distributorRatePrice = 0;
                $salesPrice = 0;
                $subTotalDiscountPrice = 0;
                $totalBalanceLocal = 0;
                foreach ($dataL AS $row) {
//                    $filterReturn = " WHERE invoice_reference_code = '$row->id' AND status <> 'Cancel' ";
//                    $returnAmount = Refund::GetRefundList($filterReturn);
//                    if(isset($returnAmount)){
//                        foreach($returnAmount AS $returnAmountRow){
//                            $totalReturn += $returnAmountRow->amount;
//                        }
//                    }
                    $counter++;
                    $customer = CustomerSetup::GetCustomerSetupById($row->custid);
                    $salesPerson = User_setup::GetUserSetupId($row->sales_person_id);
                    $discount_price = $row->discount_price;

                    $productQty = $row->product_qty;
                    $productQtyTotal += $productQty;
                    $costPrice = number_format(($row->product_qty * $row->unit_cost_price), 2, '.', '');
                    $costPriceTotal += $costPrice;
                    $costPriceTotalLocal += $costPrice;
                    $unitPrice = number_format(($row->product_qty * $row->unit_sale_price), 2, '.', '');
                    $unitPriceTotal += $unitPrice;
                    $unitPriceTotalLocal += $unitPrice;
                    $distributorPrice = number_format(($row->product_qty * $row->unit_distributor_price), 2, '.', '');
                    $distributorPriceTotal += $distributorPrice;
                    $distributorPriceTotalLocal += $distributorPrice;
                    $subtotal = $unitPrice - $costPrice;
                    if (PROJECT_DISCOUNT == 1 || $discount_price != 0) {
                        $count = 0;
                        $totalDiscountper = $row->discount;

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

                    if(isset($dataL[$counter]->custid)){
                        $nextCode = $dataL[$counter]->custid;
                    }else{
                        $nextCode = 0;
                    }
                    if($reset == true){
                        $qty = 0;
                        $factoryRatePrice = 0;
                        $distributorRatePrice = 0;
                        $salesPrice = 0;
                        $subTotalDiscountPrice = 0;
                        $reset = false;
                    }
                    if($row->custid == $nextCode){
                        $qty += $row->product_qty;
                        $factoryRatePrice += $costPrice;
                        $distributorRatePrice += $distributorPrice;
                        $salesPrice += $unitPrice;
                        $subTotalDiscountPrice += $subTotalDiscount;
                        continue;
                    }else{
                        $qty += $row->product_qty;
                        $factoryRatePrice += $costPrice;
                        $distributorRatePrice += $distributorPrice;
                        $salesPrice += $unitPrice;
                        $subTotalDiscountPrice += $subTotalDiscount;
                        $reset = true;
                    }

                    //echo $qery->customer_id."<br>";
                    $filterpay = " WHERE pay.customer_id = " . $row->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 ='$row->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 = '$row->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));

                                $totalProfitPrevious += ($unitPricePrevious - $subTotalDiscountPrevious);
                            } 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;

                    $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) {
                        // $pdf->SetX($setx);
                        // $pdf->SetFont('Arial', '', 7);
                        // $pdf->Cell($wr[0], 6, $countdown, 'LRBT', 0, 'C', $fill);
                        $countdown++;
                        // if ($customer_name == '' || $customer_name == 'All') {
                        //     $pdf->SetFont('Arial', '', 6);
                        //     $pdf->Cell($wr[1], 6, strlen($customer->name) > 55 ? substr($customer->name, 0, 55) . "..." : $customer->name, 'LRBT', 0, 'L', $fill);
                        //     $pdf->SetFont('Arial', '', 7);
                        //     $pdf->Cell($wr[2], 6, $openingBalanceAmountLocal, 'LRBT', 0, 'R', $fill);
                        //     $pdf->Cell($wr[3], 6, $totalBalanceAmountLocal, 'LRBT', 0, 'R', $fill);
                        //     $pdf->Cell($wr[4], 6, $SubTotalAmountLocal, 'LRBT', 0, 'R', $fill);
                        //     $pdf->Cell($wr[5], 6, $factoryProfitLossLocal, 'LRBT', 0, 'R', $fill);
                        // } else {
                        //     $pdf->Cell($wr[1], 6, strlen($customer->name) > 55 ? substr($customer->name, 0, 55) . "..." : $customer->name, 'LRBT', 0, 'L', $fill);
                        //     $pdf->Cell($wr[2], 6, $openingBalanceAmountLocal, 'LRBT', 0, 'R', $fill);
                        //     $pdf->Cell($wr[3], 6, $totalBalanceAmountLocal, 'LRBT', 0, 'R', $fill);
                        //     $pdf->Cell($wr[4], 6, $SubTotalAmountLocal, 'LRBT', 0, 'R', $fill);
                        //     $pdf->Cell($wr[5], 6, $factoryProfitLossLocal, 'LRBT', 0, 'R', $fill);
                        // }
                        // $pdf->Ln();
                    }


                    if ($counter_pagebreak == 36 || ($counter_pagebreak != 36 && ($counter_pagebreak) % 40 == 0)) {
                        // $counter_pagebreak = 1;
                        // $pdf->AddPage();
                        // $pdf->SetX($setx);
                        // $pdf->SetFont('Arial', '', 7);
                        // for ($i = 0; $i < count($header); $i++)
                        //     $pdf->Cell($wr[$i], 7, $header[$i], 1, 0, 'C', true);
                    }
                }
                $costPriceSubTotal += number_format((($unitPriceTotalLocal - $totalDiscountLocal) - $costPriceTotalLocal), 2, '.', '');

                //$pdf->Ln();
                // $pdf->SetX($setx);
                // $pdf->SetFont('Arial', '', 7);
                // $pdf->Cell($wr[0], 6, '', 'LBT', 0, 'L');
                // $pdf->Cell($wr[1], 6, "", 'BT', 0, 'R');

                // $pdf->Cell($wr[2], 6, "Local Mart Total", 'RBT', 0, 'R');
                // $pdf->Cell($wr[3], 6, number_format($totalBalanceLocal, 2, '.', ''), 'LRBT', 0, 'R', "");
                // $pdf->Cell($wr[4], 6, number_format(($unitPriceTotalLocal - $totalDiscountLocal), 2, '.', ''), 'LRBT', 0, 'R', "");
                // $pdf->Cell($wr[5], 6, number_format((($unitPriceTotalLocal - $totalDiscountLocal) - $costPriceTotalLocal), 2, '.', ''), 'LRBT', 0, 'R', "");

                // $pdf->Ln();
                // $pdf->Ln();
                // $fill = !$fill;
                // $counter_pagebreak++;
            }
            if($_SESSION['clone'] == 1){
                global $db;
                $db = new Database(DB_SERVER, DB_USER, DB_PASS, DB_DATABASE);
                $db->connect();

                $invoice_new = Invoice::GetInvoiceReportList($filterReport);
//                echo '<pre>';
//                print_r($filterReport);
//                echo '</pre>';
                $counter = 0;
                $costPriceTotalMart = 0;
                $unitPriceTotalMart = 0;
                $distributorPriceTotalMart = 0;
                $totalDiscountMart = 0;
                $totalBalanceMart = 0;

                $counter_pagebreak = 1;

                if($invoice_new){

                    // $pdf->AddPage();
                    // $pdf->SetX($setx);
                    // $pdf->SetFont('Arial', '', 14);
                    // $pdf->Cell(200, 7, 'Imtiaz Super Mart', '', 0, 'C', false);
                    // $pdf->Ln();
                    // $pdf->SetFont('Arial', '', 7);
                    // $pdf->SetX($setx);
                    // for ($i = 0; $i < count($header); $i++)
                    //     $pdf->Cell($wr[$i], 7, $header[$i], 1, 0, 'C', true);
                    // $pdf->Ln();
                    // // Color and font restoration
                    // $pdf->SetFillColor(224, 235, 255);
                    // $pdf->SetTextColor(0);
                    // $pdf->SetFont('');
                    // // Data
                    // $fill = false;

                    $countdown = 1;
                    $reset = false;
                    $qty = 0;
                    $factoryRatePrice = 0;
                    $distributorRatePrice = 0;
                    $salesPrice = 0;
                    $subTotalDiscountPrice = 0;
                    foreach ($invoice_new AS $row) {
//                        $filterReturn = " WHERE invoice_reference_code = '$row->id' AND status <> 'Cancel' ";
//                        $returnAmount = Refund::GetRefundList($filterReturn);
//                        if(isset($returnAmount)){
//                            foreach($returnAmount AS $returnAmountRow){
//                                $totalReturn += $returnAmountRow->amount;
//                            }
//                        }
                        $counter++;
                        $customer = CustomerSetup::GetCustomerSetupById($row->custid);
                        $salesPerson = User_setup::GetUserSetupId($row->sales_person_id);
                        $discount_price = $row->discount_price;

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


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

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

                        if(isset($invoice_new[$counter]->custid)){
                            $nextCode = $invoice_new[$counter]->custid;
                        }else{
                            $nextCode = 0;
                        }
                        if($reset == true){
                            $qty = 0;
                            $factoryRatePrice = 0;
                            $distributorRatePrice = 0;
                            $salesPrice = 0;
                            $subTotalDiscountPrice = 0;
                            $reset = false;
                        }
                        if($row->custid == $nextCode){
                            $qty += $row->product_qty;
                            $factoryRatePrice += $costPrice;
                            $distributorRatePrice += $distributorPrice;
                            $salesPrice += $unitPrice;
                            $subTotalDiscountPrice += $subTotalDiscount;
                            continue;
                        }else{
                            $qty += $row->product_qty;
                            $factoryRatePrice += $costPrice;
                            $distributorRatePrice += $distributorPrice;
                            $salesPrice += $unitPrice;
                            $subTotalDiscountPrice += $subTotalDiscount;
                            $reset = true;
                        }

                        //echo $qery->customer_id."<br>";
                        $filterpay = " WHERE pay.customer_id = " . $row->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 ='$row->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 = '$row->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));

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

                        $withholdingTax += $totalPayment->withholding_tax;
                        $salesTax += $totalPayment->sales_tax;
                        $totalReturn += $totalPayment->goods_return;

                        // $pdf->SetX($setx);
                        // $pdf->SetFont('Arial', '', 7);
                        // $pdf->Cell($wr[0], 6, $countdown, 'LRBT', 0, 'C', $fill);

                        $totalBalance += (($salesPrice - $subTotalDiscountPrice) - $totalPayment->amount) + $openingBalance;
                        $totalBalanceMart += (($salesPrice - $subTotalDiscountPrice) - $totalPayment->amount) + $openingBalance;

                        // if ($customer_name == '' || $customer_name == 'All') {
                        //     $pdf->SetFont('Arial', '', 6);
                        //     $pdf->Cell($wr[1], 6, strlen($customer->name) > 55 ? substr($customer->name, 0, 55) . "..." : $customer->name, 'LRBT', 0, 'L', $fill);
                        //     $pdf->SetFont('Arial', '', 7);
                        //     $pdf->Cell($wr[2], 6, number_format($openingBalance, 2, '.', ''), 'LRBT', 0, 'R', $fill);
                        //     $pdf->Cell($wr[3], 6, number_format(((($salesPrice - $subTotalDiscountPrice) - $totalPayment->amount) + $openingBalance), 2, '.', ''), 'LRBT', 0, 'R', $fill);
                        //     $pdf->Cell($wr[4], 6, number_format(($salesPrice-$subTotalDiscountPrice), 2, '.', ''), 'LRBT', 0, 'R', $fill);
                        //     $pdf->Cell($wr[5], 6, number_format((($salesPrice-$subTotalDiscountPrice) - $factoryRatePrice), 2, '.', ''), 'LRBT', 0, 'R', $fill);
                        // }else{
                        //     $pdf->Cell($wr[1], 6, strlen($customer->name) > 55 ? substr($customer->name, 0, 55) . "..." : $customer->name, 'LRBT', 0, 'L', $fill);
                        //     $pdf->Cell($wr[2], 6, number_format($openingBalance, 2, '.', ''), 'LRBT', 0, 'R', $fill);
                        //     $pdf->Cell($wr[3], 6, number_format(((($salesPrice - $subTotalDiscountPrice) - $totalPayment->amount) + $openingBalance), 2, '.', ''), 'LRBT', 0, 'R', $fill);
                        //     $pdf->Cell($wr[4], 6, number_format(($salesPrice-$subTotalDiscountPrice), 2, '.', ''), 'LRBT', 0, 'R', $fill);
                        //     $pdf->Cell($wr[5], 6, number_format((($salesPrice-$subTotalDiscountPrice) - $factoryRatePrice), 2, '.', ''), 'LRBT', 0, 'R', $fill);
                        // }


                        // if ($counter_pagebreak == 36 || ($counter_pagebreak != 36 && ($counter_pagebreak) % 40 == 0)) {
                        //     $counter_pagebreak = 1;
                        //     $pdf->AddPage();
                        //     $pdf->SetX($setx);
                        //     $pdf->SetFont('Arial', '', 7);
                        //     for ($i = 0; $i < count($header); $i++)
                        //         $pdf->Cell($wr[$i], 7, $header[$i], 1, 0, 'C', true);
                        // }


                        // $pdf->Ln();
                        // $counter_pagebreak++;
                    }
                }
                global $db;
                $db = new Database(DB_SERVERS, DB_USERS, DB_PASS, DB_DATABASES);
                $db->connect();
            }



            //$pdf->SetFillColor(255, 204, 0);
            // $pdf->SetX($setx);
            // $pdf->SetFont('Arial', '', 7);
            // $pdf->Cell($wr[0], 6, '', 'LBT', 0, 'L');
            // $pdf->Cell($wr[1], 6, "", 'BT', 0, 'R');
            $costPriceSubTotal += number_format((($unitPriceTotalMart - $totalDiscountMart) - $costPriceTotalMart), 2, '.', '');


            // $pdf->Cell($wr[2], 6, "Mart Total", 'RBT', 0, 'R');
            // $pdf->Cell($wr[3], 6, number_format($totalBalanceMart, 2, '.', ''), 'LRBT', 0, 'R', "");
            // $pdf->Cell($wr[4], 6, number_format(($unitPriceTotalMart - $totalDiscountMart), 2, '.', ''), 'LRBT', 0, 'R', "");
            // $pdf->Cell($wr[5], 6, number_format((($unitPriceTotalMart - $totalDiscountMart) - $costPriceTotalMart), 2, '.', ''), 'LRBT', 0, 'R', "");

            // $pdf->AddPage();
            // $pdf->Ln();
            $pdf->SetX($setx);
            $pdf->SetFont('Arial', 'B', 10);
            $pdf->Cell($wr[0], 6, "", 'LBT', 0, 'L', $fill);
            $pdf->Cell($wr[1], 6, "Grand Total", 'BT', 0, 'C', $fill);
            $pdf->Cell($wr[2], 6, "", 'RBT', 0, 'L', $fill);
            $pdf->Cell($wr[3], 6, "Balance", 'LRBT', 0, 'C', "");
            $pdf->Cell($wr[4], 6, "Sub Total", 'LRBT', 0, 'C', "");
            $pdf->Cell($wr[5], 6, "Profit/Loss", 'LRBT', 0, 'C', "");
            // $pdf->Cell(200, 7, 'Grand Total', 'LRBT', 0, 'C', $fill);

            $pdf->Ln();
            $pdf->SetX($setx);
            $pdf->SetFont('Arial', '', 10);
            $pdf->Cell($wr[0], 6, '', 'LBT', 0, 'L');
            $pdf->Cell($wr[1], 6, "", 'BT', 0, 'R');
            $pdf->Cell($wr[2], 6, "Wholesaler Total", 'RBT', 0, 'R');
            $pdf->Cell($wr[3], 6, $openingWholesale, 'LRBT', 0, 'R', "");
            $pdf->Cell($wr[4], 6, $subTotalWholesale, 'LRBT', 0, 'R', "");
            $pdf->Cell($wr[5], 6, $factoryWholesale, 'LRBT', 0, 'R', "");

            $pdf->Ln();
            $pdf->SetX($setx);
            $pdf->SetFont('Arial', '', 10);
            $pdf->Cell($wr[0], 6, '', 'LBT', 0, 'L');
            $pdf->Cell($wr[1], 6, "", 'BT', 0, 'R');
            $pdf->Cell($wr[2], 6, "Local Mart Total", 'RBT', 0, 'R');
            $pdf->Cell($wr[3], 6, number_format($totalBalanceLocal, 2, '.', ''), 'LRBT', 0, 'R', "");
            $pdf->Cell($wr[4], 6, number_format(($unitPriceTotalLocal - $totalDiscountLocal), 2, '.', ''), 'LRBT', 0, 'R', "");
            $pdf->Cell($wr[5], 6, number_format((($unitPriceTotalLocal - $totalDiscountLocal) - $costPriceTotalLocal), 2, '.', ''), 'LRBT', 0, 'R', "");

            $pdf->Ln();
            $pdf->SetX($setx);
            $pdf->SetFont('Arial', '', 10);
            $pdf->Cell($wr[0], 6, '', 'LBT', 0, 'L');
            $pdf->Cell($wr[1], 6, "", 'BT', 0, 'R');
            $pdf->Cell($wr[2], 6, "Imtiaz Super Mart Total", 'RBT', 0, 'R');
            $pdf->Cell($wr[3], 6, number_format($totalBalanceMart, 2, '.', ''), 'LRBT', 0, 'R', "");
            $pdf->Cell($wr[4], 6, number_format(($unitPriceTotalMart - $totalDiscountMart), 2, '.', ''), 'LRBT', 0, 'R', "");
            $pdf->Cell($wr[5], 6, number_format((($unitPriceTotalMart - $totalDiscountMart) - $costPriceTotalMart), 2, '.', ''), 'LRBT', 0, 'R', "");

            $pdf->Ln();
            $pdf->SetX($setx);
            $pdf->SetFont('Arial', '', 10);
            $pdf->Cell($wr[0], 6, '', 'LBT', 0, 'L');
            $pdf->Cell($wr[1], 6, "", 'BT', 0, 'R');
            $pdf->Cell($wr[2], 6, "Total", 'RBT', 0, 'R');
            $pdf->Cell($wr[3], 6, number_format($totalBalance, 2, '.', ''), 'LRBT', 0, 'R', "");
            $pdf->Cell($wr[4], 6, number_format(($unitPriceTotal - $totalDiscount), 2, '.', ''), 'LRBT', 0, 'R', "");
            $pdf->Cell($wr[5], 6, $costPriceSubTotal, 'LRBT', 0, 'R', "");

            $Income = $costPriceSubTotal;

            if($customer_name == 'All') {
                $pdf->Ln();
                $pdf->Ln();
                $pdf->SetX($setx);
                $pdf->SetFont('Arial', 'B', 10);
                $wr = array(135, 65);
                $pdf->Cell(200, 7, 'Factory Expense', 'LRBT', 0, 'C', $fill);

                $counter = 0;
                $counterSerial = 0;
                $amountTotal = 0;
                $amountSubTotal = 0;
                $mainCat = '';
                $catName = '';

                if($qryExpense){
                    foreach ($qryExpense as $qery) {
                        $exPCategory = ExpenseCategorySetup::GetExpenseCategorySetupById($qery->parent_id);
                        $counter++;
                        if ($exPCategory->name != $mainCat && $counter != 1) {
                            $pdf->Cell($wr[1], 7, $amountSubTotal, '', 0, 'R', '');
                        }
                        if ($catName != $exPCategory->name) {
                            $amountSubTotal = 0;
                            $counterSerial = 0;
                            $pdf->Ln();
                            $pdf->SetX($setx);
                            $pdf->SetFont('Arial', '', 10);
                            $pdf->Cell($wr[0], 7, $exPCategory->name, 'LRBT', 0, 'L', '');


                            //$fill = !$fill;
                            $counter++;
                            $counter_pagebreak++;
                        }
                        $counterSerial++;
                        $amountSubTotal += $qery->amount;
                        $amountTotal += $qery->amount;
                        $catName = $exPCategory->name;
                        $mainCat = $exPCategory->name;

                    }
                }
                if($qryExpense2){
                    global $db;
                    $db = new Database(DB_SERVER, DB_USER, DB_PASS, DB_DATABASE);
                    $db->connect();
                    foreach ($qryExpense2 as $qery) {
                        $exPCategory = ExpenseCategorySetup::GetExpenseCategorySetupById($qery->parent_id);
                        $counter++;
                        if ($exPCategory->name != $mainCat && $counter != 1) {
                            $pdf->Cell($wr[1], 7, $amountSubTotal, 'LRBT', 0, 'R', '');
                        }
                        if ($catName != $exPCategory->name) {
                            $amountSubTotal = 0;
                            $counterSerial = 0;
                            $pdf->Ln();
                            $pdf->SetX($setx);
                            $pdf->SetFont('Arial', '', 10);
                            $pdf->Cell($wr[0], 7, $exPCategory->name, 'LRBT', 0, 'L', '');


                            //$fill = !$fill;
                            $counter++;
                            $counter_pagebreak++;
                        }
                        $counterSerial++;
                        $amountSubTotal += $qery->amount;
                        $amountTotal += $qery->amount;
                        $catName = $exPCategory->name;
                        $mainCat = $exPCategory->name;

                    }

                    $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();
                }
                $pdf->Cell($wr[1], 7, $amountSubTotal, 'LRBT', 0, 'R', '');

                //Salary
                $totalSalary = 0;
                if ($qrySalary) {
                    foreach ($qrySalary as $qery) {
                        $totalSalary += $qery->amount;
                    }

                    $pdf->Ln();
                    $pdf->SetX($setx);
                    $pdf->SetFont('Arial', '', 10);
                    $pdf->Cell($wr[0], 7, 'Factory Salary', 'LRBT', 0, 'L', true);
                    $pdf->Cell($wr[1], 7, $totalSalary, 'LRBT', 0, 'R', true);
                }
                if ($qrySalary2) {
                    foreach ($qrySalary2 as $qery) {
                        $totalSalary += $qery->amount;
                    }

                    $pdf->Ln();
                    $pdf->SetX($setx);
                    $pdf->SetFont('Arial', '', 10);
                    $pdf->Cell($wr[0], 7, 'Factory Salary', 'LRBT', 0, 'L', true);
                    $pdf->Cell($wr[1], 7, $totalSalary, 'LRBT', 0, 'R', true);
                }
                
                $amountTotal += $totalSalary;

                $pdf->Ln();
                $pdf->SetX($setx);
                $pdf->SetFont('Arial', '', 10);
                $pdf->Cell($wr[0], 7, 'Factory Loan', 'LRBT', 0, 'L', true);
                $pdf->Cell($wr[1], 7, $loan, 'LRBT', 0, 'R', true);

                $pdf->Ln();
                $pdf->SetX($setx);
                $pdf->SetFont('Arial', '', 10);
                $pdf->Cell($wr[0], 7, 'Total', 'LRBT', 0, 'L', true);
                $pdf->Cell($wr[1], 7, $amountTotal, 'LRBT', 0, 'R', true);
                $pdf->Ln();


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



                $pdf->Ln();
                $pdf->SetX($setx);
                $pdf->SetFont('Arial', 'B', 10);
                $wr = array(135, 65);
                $pdf->Cell(200, 7, 'Mart Expense', 'LRBT', 0, 'C', $fill);
                
                if($qryExpenseMart){
                    foreach ($qryExpenseMart as $qery) {
                        $exPCategoryMart = ExpenseMartCategorySetup::GetExpenseMartCategorySetupById($qery->parent_id);
                        $counterMart++;
                        if ($exPCategoryMart->name != $mainCatMart && $counterMart != 1) {
                            $pdf->Cell($wr[1], 7, $amountSubTotalMart, '', 0, 'R', '');
                        }
                        if ($catNameMart != $exPCategoryMart->name) {
                            $amountSubTotalMart = 0;
                            $counterSerialMart = 0;
                            $pdf->Ln();
                            $pdf->SetX($setx);
                            $pdf->SetFont('Arial', '', 14);
                            $pdf->Cell($wr[0], 7, $exPCategoryMart->name, 'LRBT', 0, 'L', '');


                            //$fill = !$fill;
                            $counterMart++;
                            $counter_pagebreak++;
                        }
                        $counterSerialMart++;
                        $amountSubTotalMart += $qery->amount;
                        $amountTotal += $qery->amount;
                        $amountTotalMart += $qery->amount;
                        $catNameMart = $exPCategoryMart->name;
                        $mainCatMart = $exPCategoryMart->name;

                    }
                }
                if($qryExpense2Mart){
                    global $db;
                    $db = new Database(DB_SERVER, DB_USER, DB_PASS, DB_DATABASE);
                    $db->connect();
                    $counterMart = 0;
                    foreach ($qryExpense2Mart as $qery) {
                        $exPCategoryMart = ExpenseMartCategorySetup::GetExpenseMartCategorySetupById($qery->parent_id);
                        $counterMart++;
                        if ($exPCategoryMart->name != $mainCatMart && $counterMart != 1) {
                            $pdf->Cell($wr[1], 7, $amountSubTotalMart, 'LRBT', 0, 'R', '');
                        }
                        if ($catNameMart != $exPCategoryMart->name) {
                            $amountSubTotalMart = 0;
                            $counterSerialMart = 0;
                            $pdf->Ln();
                            $pdf->SetX($setx);
                            $pdf->SetFont('Arial', '', 10);
                            $pdf->Cell($wr[0], 7, $exPCategoryMart->name, 'LRBT', 0, 'L', '');


                            //$fill = !$fill;
                            $counterMart++;
                            $counter_pagebreak++;
                        }
                        $counterSerialMart++;
                        $amountSubTotalMart += $qery->amount;
                        $amountTotal += $qery->amount;
                        $amountTotalMart += $qery->amount;
                        $catNameMart = $exPCategoryMart->name;
                        $mainCatMart = $exPCategoryMart->name;
                    }
                    $pdf->Cell($wr[1], 7, $amountSubTotalMart, 'LRBT', 0, 'R', '');

                    $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();
                }







                if($qryExpense2){
                    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;
                    $amountTotalMart += $martLoan;

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

                $pdf->Ln();
                $pdf->SetX($setx);
                $pdf->SetFont('Arial', '', 10);
                $pdf->Cell($wr[0], 7, 'Total Withholding Tax - (4.5%)', 'LRBT', 0, 'L', true);
                $pdf->Cell($wr[1], 7, $withholdingTax, 'LRBT', 0, 'R', true);

                $pdf->Ln();
                $pdf->SetX($setx);
                $pdf->SetFont('Arial', '', 10);
                $pdf->Cell($wr[0], 7, 'Total Sales Tax - (17%)', 'LRBT', 0, 'L', true);
                $pdf->Cell($wr[1], 7, $salesTax, 'LRBT', 0, 'R', true);

                $pdf->Ln();
                $pdf->SetX($setx);
                $pdf->SetFont('Arial', '', 10);
                $pdf->Cell($wr[0], 7, 'Total Goods Return', 'LRBT', 0, 'L', true);
                $pdf->Cell($wr[1], 7, $totalReturn, 'LRBT', 0, 'R', true);

                if($qryExpense2){
                    global $db;
                    $db = new Database(DB_SERVER, DB_USER, DB_PASS, DB_DATABASE);
                    $db->connect();

                    //Mart Salary
                    $amountTotalMartSalary = 0;

                    $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;

                    $pdf->Ln();
                    $pdf->SetX($setx);
                    $pdf->SetFont('Arial', '', 10);
                    $pdf->Cell($wr[0], 7, 'Mart Salary', 'LRBT', 0, 'L', true);
                    $pdf->Cell($wr[1], 7, $amountTotalMartSalary, 'LRBT', 0, 'R', true);

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

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

                $pdf->Ln();
                $pdf->SetX($setx);
                $pdf->SetFont('Arial', '', 10);
                $pdf->Cell($wr[0], 7, 'Mart Loan', 'LRBT', 0, 'L', true);
                $pdf->Cell($wr[1], 7, $martLoan, 'LRBT', 0, 'R', true);

                $pdf->Ln();
                $pdf->SetX($setx);
                $pdf->SetFont('Arial', '', 10);
                $pdf->Cell($wr[0], 7, 'Total', 'LRBT', 0, 'L', true);
                $pdf->Cell($wr[1], 7, $amountTotalMart, 'LRBT', 0, 'R', true);
                $pdf->Ln();
                //Expense End

                

                $costPriceSubTotal -= $amountTotal;
                // $costPriceSubTotal -= $totalSalary;
//                $costPriceSubTotal -= $totalReturn;
                //Salary End

//                $pdf->Ln();
//                $pdf->SetX($setx);
//                $pdf->SetFont('Arial', '', 12);
//                $pdf->Cell($wr[0], 7, 'Total Return', 'LRBT', 0, 'L', true);
//                $pdf->Cell($wr[1], 7, $totalReturn, 'LRBT', 0, 'R', true);

                $pdf->Ln();
                $pdf->SetX($setx);
                $pdf->SetFont('Arial', 'B', 10);
                $wr = array(135, 65);
                $pdf->Cell(200, 7, 'Total Profit', 'LRBT', 0, 'C', $fill);

                $pdf->Ln();
                $pdf->SetX($setx);
                $pdf->SetFont('Arial', '', 10);
                $pdf->Cell($wr[0], 7, 'Grand Total', 'LRBT', 0, 'L', true);
                $pdf->Cell($wr[1], 7, number_format($Income, 2, '.', ''), 'LRBT', 0, 'R', true);

                $pdf->Ln();
                $pdf->SetX($setx);
                $pdf->SetFont('Arial', '', 10);
                $pdf->Cell($wr[0], 7, 'Grand Expenses', 'LRBT', 0, 'L', true);
                $pdf->Cell($wr[1], 7, number_format($amountTotal, 2, '.', ''), 'LRBT', 0, 'R', true);

                $pdf->Ln();
                $pdf->SetX($setx);
                $pdf->SetFont('Arial', '', 10);
                $pdf->Cell($wr[0], 7, 'Net Profit', 'LRBT', 0, 'L', true);
                $pdf->Cell($wr[1], 7, $costPriceSubTotal, 'LRBT', 0, 'R', true);
            }

            $director = DirectorSetup::GetDirectorSetupList();
            $totalShare = 0;
            // $pdf->Ln();
            foreach($director AS $directorRow){
                $share = $costPriceSubTotal*(intval($directorRow->share)/100);
                $totalShare += $share;
                $pdf->Ln();
                $pdf->SetX($setx);
                $pdf->SetFont('Arial', '', 10);
                $pdf->Cell($wr[0], 7, $directorRow->name.' - '.$directorRow->share.'% - '.$directorRow->designation, 'LRBT', 0, 'L', true);
                $pdf->Cell($wr[1], 7, number_format($share, 2, '.', ''), 'LRBT', 0, 'R', true);
            }
            $remainingAmount = $costPriceSubTotal-$totalShare;
            if($remainingAmount >0){
                $pdf->Ln();
                $pdf->SetX($setx);
                $pdf->SetFont('Arial', '', 10);
                $pdf->Cell($wr[0], 7, 'Remaining Amount', 'LRBT', 0, 'L', true);
                $pdf->Cell($wr[1], 7, number_format($remainingAmount, 2, '.', ''), 'LRBT', 0, 'R', true);
            }

        }

        FancyTable($header, $invoiceW, $invoice, $invoiceLocal, $product_id, $customer_name, $setx, $qryDate, $qryTo, $filterReportW, $filterReport, $qryExpense, $qrySalary, $qryExpense2, $qrySalary2, $qryExpenseMart, $qryExpense2Mart);
    } else {
        header('location: ' . PROJECT_ADMIN_URL);
        exit;
    }

    $pdf->Output();
    ob_end_flush();
    exit;
} catch (Exception $e) {
    echo $e->getMessage();
}
?>