<?php
error_reporting(E_ALL);
ini_set('display_errors', '0');
try {

    if (!isset($_REQUEST['datefrom'])) {
        header('location: ../customer.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);

    if ($datefrom == "") {
        $datefrom = date('Y-m-d', strtotime("-30 days"));
    } else {
        $datefrom = date("Y-m-d", strtotime($datefrom));
    }
    if ($dateto == "") {
        $dateto = date('Y-m-d');
    } else {
        $dateto = date("Y-m-d", strtotime($dateto));
    }
    $datefrom = date("d-m-Y", strtotime($datefrom));
    $dateto = date("d-m-Y", strtotime($dateto));

    $qryDate = date("Y-m-d", strtotime($datefrom));
    $qryTo = date("Y-m-d", strtotime($dateto));
    $filterReport = " JOIN customer_setup AS cs ON cs.id = inv.customer_id RIGHT JOIN " . TABLE_INVOICE_PRODUCT . " AS invPr ON inv.id = invPr.invoice_id 
    WHERE DATE_FORMAT(inv.create_date,'%Y-%m-%d')>='$qryDate' and DATE_FORMAT(inv.create_date,'%Y-%m-%d')<='$qryTo' AND inv.status not in('Draft', 'Cancel') ";

    if (isset($customer_name) && $customer_name != 'All') {
        $filterReport .= " AND inv.customer_id ='$customer_name'";
    }
    if (isset($invoice) && $invoice != 'All') {
        $filterReport .= " AND inv.code ='$invoice'";
    }
    $filterReport .= " AND cs.status ='active'";

    $filterReport .= " UNION SELECT 'payment' AS nameTable, payment.id, description, payment.code , customer_id, '', '', '', '', amount, '',
		'', '', create_date, '', payment.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 . " 
        JOIN customer_setup AS cs ON cs.id = customer_id
        WHERE DATE_FORMAT(create_date,'%Y-%m-%d')>='$qryDate' and DATE_FORMAT(create_date,'%Y-%m-%d')<='$qryTo' AND payment.status <> 'Cancel' ";

    if (isset($customer_name) && $customer_name != 'All') {
        $filterReport .= " AND customer_id ='$customer_name'";
    }
    if (isset($invoice) && $invoice != 'All') {
        $filterReport .= " AND invoice_reference_code ='$invoice'";
    }
    $filterReport .= " AND cs.status ='active'";
    $filterReport .= " ORDER BY create_date, code ";

    //PreviousRecord
    $qryDatePrevious = date('Y-m-d', strtotime('-1 day', strtotime($qryDate)));
    $filterReportPrevious = " JOIN customer_setup AS cs ON cs.id = inv.customer_id RIGHT JOIN " . TABLE_INVOICE_PRODUCT . " AS invPr ON inv.id = invPr.invoice_id 
    WHERE DATE_FORMAT(inv.create_date,'%Y-%m-%d')>='2016-01-01' and DATE_FORMAT(inv.create_date,'%Y-%m-%d')<='$qryDatePrevious'  AND inv.status not in('Draft', 'Cancel') ";

    if (isset($customer_name) && $customer_name != 'All') {
        $filterReportPrevious .= " AND inv.customer_id ='$customer_name'";
    }
    if (isset($invoice) && $invoice != 'All') {
        $filterReportPrevious .= " AND inv.code ='$invoice'";
    }
    $filterReportPrevious .= " AND cs.status ='active'";

    $filterReportPrevious .= " UNION SELECT 'payment' AS nameTable, payment.id, description, payment.code , customer_id, '', '', '', '', amount, '',
		'', '', create_date, '', payment.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 . " 
        JOIN customer_setup AS cs ON cs.id = customer_id
        WHERE DATE_FORMAT(create_date,'%Y-%m-%d')>='2016-01-01' and DATE_FORMAT(create_date,'%Y-%m-%d')<='$qryDatePrevious' AND payment.status <> 'Cancel' ";

    if (isset($customer_name) && $customer_name != 'All') {
        $filterReportPrevious .= " AND customer_id ='$customer_name'";
    }
    if (isset($invoice) && $invoice != 'All') {
        $filterReportPrevious .= " AND invoice_reference_code ='$invoice'";
    }
    $filterReportPrevious .= " AND cs.status ='active'";
    $filterReportPrevious .= " ORDER BY create_date, code ";
//Previous Record

    $qryPrevious = Invoice::GetInvoiceCustomerReportList123($filterReportPrevious);
    //print_r($qryPrevious);
    $customerIds = array();
    $opBalance = 0;
    if($qryPrevious){
        foreach($qryPrevious AS $qryPreviousRow){
            if ($qryPreviousRow->nameTable == 'invoice') {
                $unitPricePrevious = ($qryPreviousRow->product_qty * $qryPreviousRow->unit_sale_price);
                $totalDiscountperPrevious = $qryPreviousRow->discount;

                $subTotalDiscountPrevious = round(($unitPricePrevious * ($totalDiscountperPrevious / 100)));
                $sunTotalUnitPricePrevious = $unitPricePrevious - $subTotalDiscountPrevious;

                if($qryPreviousRow->add_discount > 0){
                    $subTotalDiscountPreviousAdd = round(($sunTotalUnitPricePrevious * ($qryPreviousRow->add_discount / 100)));
                    $subTotalDiscountPrevious = $subTotalDiscountPrevious + $subTotalDiscountPreviousAdd;
                    $sunTotalUnitPricePrevious = $sunTotalUnitPricePrevious - $subTotalDiscountPreviousAdd;
                }

                $totalProfitPrevious += number_format(($sunTotalUnitPricePrevious), 0, '.', '');
            } else if($qryPreviousRow->nameTable == 'payment') {
                $totalPaymentsPrevious += $qryPreviousRow->total_amount;
            }
            if (!in_array($qryPreviousRow->customer_id, $customerIds)) {
                $customer = CustomerSetup::GetCustomerSetupById($qryPreviousRow->customer_id);
                $opBalance += $customer->balance;
                $customerIds[] = $qryPreviousRow->customer_id;
            }
        }
        $openingBalance = number_format(($totalProfitPrevious - $totalPaymentsPrevious), 0, '.', '');
    }
    
    $invoice = Invoice::GetInvoiceCustomerReportList123($filterReport);
    $cToggle = 0;
    if(isset($invoice) && !empty($invoice)){
        foreach ($invoice as $qery) {
            if ($cToggle == 0 && !in_array($qery->customer_id, $customerIds) && $qery->nameTable == 'invoice') {
                $customer = CustomerSetup::GetCustomerSetupById($qery->customer_id);
                $opBalance += $customer->balance;
                $customerIds[] = $qery->customer_id;
                $cToggle = 1;
            }else if ($cToggle == 0 && !in_array($qery->customer_id, $customerIds) && $qery->nameTable == 'payment'){
                $customer = CustomerSetup::GetCustomerSetupById($qery->customer_id);
                $opBalance += $customer->balance;
                $cToggle = 1;
            }
        }
    }
    // else{
    //     $customer = CustomerSetup::GetCustomerSetupById($customer_name);
    //     $opBalance += $customer->balance;
    //     $cToggle = 1;
    // }
    $openingBalance += $opBalance;
    if (!empty($invoice) || !empty($openingBalance)) {

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

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

        $pdf->SetTitle('Customer 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, 'Customer 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', '', 8);
        $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', 'Date', 'Invoice', 'Customer', 'Product', 'Pay Type', 'Pay Date', 'Desc', 'Qty', 'Rate', 'Sale Price', 'Disc.', 'Receivable', 'Payment', 'Balance');
        }else{
            $customer = CustomerSetup::GetCustomerSetupById($customer_name);
            $header = array('S.No', 'Date', 'Invoice', 'Product', 'Pay Type', 'Pay Date', 'Desc', 'Qty', ' Rate', 'Sale Price', 'Discount', 'Receivable', 'Payment', 'Balance');
        }
//        $filterProductInvoice = " WHERE invoice_id = '$invoice_id'";
//        $productData = Invoice::GetInvoiceProducts($filterProductInvoice);

        function FancyTable($header, $data, $openingBalance, $product_id, $customer_name,  $setx)
        {
            global $pdf;

            $totalDiscount = 0;
            $productQtyTotal = 0;
            $costPriceTotal = 0;
            $unitPriceTotal = 0;
            $totalProfit = 0;

            // Colors, line width and bold font
            $pdf->SetFillColor(224, 235, 255);
            $pdf->SetTextColor(0);
            $pdf->SetDrawColor(128, 0, 0);
            $pdf->SetLineWidth(.3);
            $pdf->SetFont('Arial', 'B', 9);
            // Header
            if ($customer_name == '' || $customer_name == 'All') {
                $wr = array(10, 18, 15, 29, 39, 20, 17, 22, 15, 10, 19, 12, 19, 19, 19);
            }else{
                $wr = array(10, 18, 15, 45, 20, 20, 29, 15, 10, 20, 15, 20, 20, 20);
            }
            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 = 1;
            $counter_pagebreak = 1;
            $totalPayments = 0;
            if($data){
                $pdf->SetX($setx);
                $pdf->SetFont('Arial', '', 8);
                $pdf->Cell($wr[0], 7, $counter, 'LRBT', 0, 'C', $fill);
                $pdf->Cell($wr[1], 7, 'Opening', 'LBT', 0, 'L', $fill);
                $pdf->Cell($wr[2], 7, '', 'BT', 0, 'R', $fill);
                $pdf->Cell($wr[3], 7, '', 'BT', 0, 'R', $fill);
                $pdf->Cell($wr[4], 7, '', 'BT', 0, 'R', $fill);
                $pdf->Cell($wr[5], 7, '', 'BT', 0, 'R', $fill);
                $pdf->Cell($wr[6], 7, '', 'BT', 0, 'R', $fill);
                $pdf->Cell($wr[7], 7, '', 'BT', 0, 'R', $fill);
                $pdf->Cell($wr[8], 7, '', 'BT', 0, 'R', $fill);
                $pdf->Cell($wr[9], 7, '', 'BT', 0, 'R', $fill);
                $pdf->Cell($wr[10], 7, '', 'BT', 0, 'R', $fill);
                $pdf->Cell($wr[11], 7, '', 'BT', 0, 'R', $fill);
                $pdf->Cell($wr[12], 7, '', 'BT', 0, 'R', $fill);
                if ($customer_name == '' || $customer_name == 'All') {
                    $pdf->Cell($wr[13], 7, '', 'BT', 0, 'R', $fill);
                    $pdf->Cell($wr[14], 7, $openingBalance, 'LRBT', 0, 'R', $fill);
                }else{
                    $pdf->Cell($wr[13], 7, $openingBalance, 'LRBT', 0, 'R', $fill);
                }
                $pdf->Ln();
                $counter++;
                foreach ($data AS $row) {
                    if ($row->nameTable == 'invoice') {
                        $pdf->SetX($setx);
                        $pdf->SetFont('Arial', '', 8);
                        $pdf->Cell($wr[0], 7, $counter, 'LRBT', 0, 'C', $fill);
                        $pdf->Cell($wr[1], 7, date('Y-m-d', strtotime($row->create_date)), 'LRBT', 0, 'L', $fill);

                        $customer = CustomerSetup::GetCustomerSetupById($row->customer_id);
                        $salesPerson = User_setup::GetUserSetupId($row->sales_person_id);
                        $discount_price = $row->discount_price;

                        $pdf->Cell($wr[2], 7, $row->code, 'LRBT', 0, 'L', $fill);

                        $productName = ProductSetup::GetProductSetupById($row->product_id);
                        $productQty = $row->product_qty;
                        $productQtyTotal += $productQty;
                        $costPrice = number_format(($row->product_qty * $row->unit_cost_price), 2, '.', '');
                        $costPriceTotal += $costPrice;
                        $unitPrice = number_format(($row->product_qty * $row->unit_sale_price), 0, '.', '');
                        $unitPriceTotal += $unitPrice;
                        $subtotal = $unitPrice - $costPrice;
                        if (PROJECT_DISCOUNT == 1 || $discount_price != 0) {
                            $filterProducts = " WHERE invoice_id = '$row->invoice_id'";
                            $productSetup = Invoice::GetInvoiceProducts($filterProducts);
                            $count = 0;
                            if($productSetup){
                                foreach ($productSetup as $productSetupRows) {
                                    $count++;
                                }
                            }
                            $totalDiscountper = $row->discount;
                            $subTotalDiscount = round(($unitPrice * ($totalDiscountper / 100)));
                            $subtotalUnitPrice = $unitPrice - $subTotalDiscount;
                            if($row->add_discount > 0){
                                $totalDiscountperAdd = $row->add_discount;
                                $subTotalDiscountAdd = round(($subtotalUnitPrice * ($totalDiscountperAdd / 100)));
                                $subTotalDiscount = $subTotalDiscount + $subTotalDiscountAdd;
                                $subtotalUnitPrice = $subtotalUnitPrice - $subTotalDiscountAdd;
                            }
                            $totalDiscount += number_format($subTotalDiscount, 0, '.', '');
                            $subtotal -= number_format($subTotalDiscount, 0, '.', '');
                        }
                        $totalProfit += number_format(($unitPrice - $subTotalDiscount), 0, '.', '');

                        if ($customer_name == '' || $customer_name == 'All') {
                            $pdf->Cell($wr[3], 7, $customer->name, 'LRBT', 0, 'L', $fill);
                            $pdf->Cell($wr[4], 7, $productName->name, 'LRBT', 0, 'L', $fill);
                            //$pdf->Cell($wr[5], 7, $salesPerson->username, 'LRB', 0, 'R', $fill);
                            $pdf->Cell($wr[5], 7, '-', 'LRBT', 0, 'R', $fill);
                            $pdf->Cell($wr[6], 7, '-', 'LRBT', 0, 'R', $fill);
                            $pdf->Cell($wr[7], 7, $row->description, 'LRBT', 0, 'R', $fill);
                            $pdf->Cell($wr[8], 7, $row->product_qty, 'LRBT', 0, 'R', $fill);
                            $pdf->Cell($wr[9], 7, $row->unit_sale_price, 'LRBT', 0, 'R', $fill);
                            $pdf->Cell($wr[10], 7, number_format(($unitPrice), 0, '.', ''), 'LRBT', 0, 'R', $fill);
                            $pdf->Cell($wr[11], 7, number_format(($subTotalDiscount), 0, '.', ''), 'LRBT', 0, 'R', $fill);
                            $pdf->Cell($wr[12], 7, number_format(($subtotalUnitPrice), 0, '.', ''), 'LRBT', 0, 'R', $fill);
                            $pdf->Cell($wr[13], 7, '-', 'LRBT', 0, 'R', $fill);
                            $pdf->Cell($wr[14], 7, number_format(($openingBalance + ($totalProfit - $totalPayments)), 2, '.', ''), 'LRBT', 0, 'R', $fill);
                        }else{
                            $pdf->Cell($wr[3], 7, $productName->name, 'LRBT', 0, 'L', $fill);
                            //$pdf->Cell($wr[5], 7, $salesPerson->username, 'LRB', 0, 'R', $fill);
                            $pdf->Cell($wr[4], 7, '-', 'LRBT', 0, 'R', $fill);
                            $pdf->Cell($wr[5], 7, '-', 'LRBT', 0, 'R', $fill);
                            $pdf->Cell($wr[6], 7, $row->description, 'LRBT', 0, 'R', $fill);
                            $pdf->Cell($wr[7], 7, $row->product_qty, 'LRBT', 0, 'R', $fill);
                            $pdf->Cell($wr[8], 7, $row->unit_sale_price, 'LRBT', 0, 'R', $fill);
                            $pdf->Cell($wr[9], 7, number_format(($unitPrice), 0, '.', ''), 'LRBT', 0, 'R', $fill);
                            $pdf->Cell($wr[10], 7, number_format(($subTotalDiscount), 0, '.', ''), 'LRBT', 0, 'R', $fill);
                            $pdf->Cell($wr[11], 7, number_format(($subtotalUnitPrice), 0, '.', ''), 'LRBT', 0, 'R', $fill);
                            $pdf->Cell($wr[12], 7, '-', 'LRBT', 0, 'R', $fill);
                            $pdf->Cell($wr[13], 7, number_format(($openingBalance + ($totalProfit - $totalPayments)), 2, '.', ''), 'LRBT', 0, 'R', $fill);
                        }
                    }
                    else if ($row->nameTable == 'payment') {
                        $pdf->SetX($setx);
                        $pdf->SetFont('Arial', '', 8);
                        $pdf->Cell($wr[0], 7, $counter, 'LRBT', 0, 'C', $fill);
                        $pdf->Cell($wr[1], 7, date('Y-m-d', strtotime($row->create_date)), 'LRBT', 0, 'L', $fill);

                        $customer = CustomerSetup::GetCustomerSetupById($row->customer_id);
                        $discount_price = $row->discount_price;
                        $bank = BankSetup::GetBankSetupById($row->bank_name);
                        $totalPayments += $row->total_amount;

                        $pdf->Cell($wr[2], 7, $row->code, 'LRBT', 0, 'L', $fill);
                        if ($customer_name == '' || $customer_name == 'All') {
                            $pdf->Cell($wr[3], 7, $customer->name, 'LRBT', 0, 'L', $fill);
                            $pdf->Cell($wr[4], 7, '-', 'LRBT', 0, 'L', $fill);
                            //$pdf->Cell($wr[5], 7, $salesPerson->username, 'LRB', 0, 'R', $fill);
                            if($row->payment_type == 'bank' || $row->payment_type == 'party'){
                                $chequeDetails = 'Chq/'. $row->cheque_number;
                                $pdf->Cell($wr[5], 7, strlen($chequeDetails) > 17 ? substr($chequeDetails,0,17)."..." : $chequeDetails, 'LRBT', 0, 'L', $fill);
                            }else if($row->payment_type == 'online'){
                                $pdf->Cell($wr[5], 7, ucwords($row->payment_type)." ".(strlen($bank->bank_name) > 11 ? substr($bank->bank_name,0,11)."..." : $bank->bank_name), 'LRBT', 0, 'L', $fill);
                            }else{
                                $pdf->Cell($wr[5], 7, ucwords($row->payment_type), 'LRBT', 0, 'L', $fill);
                            }

                            $pdf->Cell($wr[6], 7, date('Y-m-d', strtotime($row->create_date)), 'LRBT', 0, 'L', $fill);
                            $pdf->Cell($wr[7], 7, $row->description, 'LRBT', 0, 'L', $fill);
                            $pdf->Cell($wr[8], 7, '-', 'LRBT', 0, 'R', $fill);
                            $pdf->Cell($wr[9], 7, '-', 'LRBT', 0, 'R', $fill);
                            $pdf->Cell($wr[10], 7, '-', 'LRBT', 0, 'R', $fill);
                            $pdf->Cell($wr[11], 7, '-', 'LRBT', 0, 'R', $fill);
                            $pdf->Cell($wr[12], 7, '-', 'LRBT', 0, 'R', $fill);
                            $pdf->Cell($wr[13], 7, $row->total_amount, 'LRBT', 0, 'R', $fill);
                            $pdf->Cell($wr[14], 7, number_format(($openingBalance + ($totalProfit - $totalPayments)), 2, '.', ''), 'LRBT', 0, 'R', $fill);
                        }else{
                            $pdf->Cell($wr[3], 7, '-', 'LRBT', 0, 'L', $fill);
                            //$pdf->Cell($wr[5], 7, $salesPerson->username, 'LRB', 0, 'R', $fill);
                            if($row->payment_type == 'bank' || $row->payment_type == 'party'){
                                $chequeDetails = 'Chq/'. $row->cheque_number;
                                $pdf->Cell($wr[4], 7, strlen($chequeDetails) > 17 ? substr($chequeDetails,0,17)."..." : $chequeDetails, 'LRBT', 0, 'L', $fill);
                            }else if($row->payment_type == 'online'){
                                $pdf->Cell($wr[4], 7, ucwords($row->payment_type)." ".(strlen($bank->bank_name) > 11 ? substr($bank->bank_name,0,11)."..." : $bank->bank_name), 'LRBT', 0, 'L', $fill);
                            }else{
                                $pdf->Cell($wr[4], 7, ucwords($row->payment_type), 'LRBT', 0, 'L', $fill);
                            }
                            $pdf->Cell($wr[5], 7, date('Y-m-d', strtotime($row->create_date)), 'LRBT', 0, 'L', $fill);
                            $pdf->Cell($wr[6], 7, $row->description, 'LRBT', 0, 'L', $fill);
                            $pdf->Cell($wr[7], 7, '-', 'LRBT', 0, 'R', $fill);
                            $pdf->Cell($wr[8], 7, '-', 'LRBT', 0, 'R', $fill);
                            $pdf->Cell($wr[9], 7, '-', 'LRBT', 0, 'R', $fill);
                            $pdf->Cell($wr[10], 7, '-', 'LRBT', 0, 'R', $fill);
                            $pdf->Cell($wr[11], 7, '-', 'LRBT', 0, 'R', $fill);
                            $pdf->Cell($wr[12], 7, $row->total_amount, 'LRBT', 0, 'R', $fill);
                            $pdf->Cell($wr[13], 7, number_format(($openingBalance + ($totalProfit - $totalPayments)), 2, '.', ''), 'LRBT', 0, 'R', $fill);
                        }
                    }
                    if($counter == 19 || ($counter != 19 && ($counter_pagebreak)%23==0)){
                        $counter_pagebreak = 1;
                        $pdf->AddPage();
                        $pdf->SetX($setx);
                        $pdf->SetFont('Arial', 'B', 9);
                        for ($i = 0; $i < count($header); $i++)
                            $pdf->Cell($wr[$i], 7, $header[$i], 1, 0, 'C', true);
                    }
                    $pdf->Ln();
                   // $fill = !$fill;
                    $counter++;
                    $counter_pagebreak++;
                }
            }
            //$pdf->SetFillColor(255, 204, 0);
            $pdf->SetX($setx);
            $pdf->SetFont('Arial', '', 8);
            $pdf->Cell($wr[0], 7, '', '', 0, 'L');
            $pdf->Cell($wr[1], 7, '', '', 0, 'L');
            $pdf->Cell($wr[2], 7, "", '', 0, 'R');
            $pdf->Cell($wr[3], 7, "", '', 0, 'R');
            $pdf->Cell($wr[4], 7, "", '', 0, 'R');
            $pdf->Cell($wr[5], 7, "", '', 0, 'R');
            if ($customer_name == '' || $customer_name == 'All') {
                $pdf->Cell($wr[6], 7, "", '', 0, 'R');
                $pdf->Cell($wr[7], 7, "Total", 'LRBT', 0, 'R');
                $pdf->Cell($wr[8], 7, $productQtyTotal, 'LRBT', 0, 'R');
                $pdf->Cell($wr[9], 7, '', 'LRBT', 0, 'R');
                $pdf->Cell($wr[10], 7, $unitPriceTotal, 'LRBT', 0, 'R');
                $pdf->Cell($wr[11], 7, number_format(($totalDiscount), 2, '.', ''), 'LRBT', 0, 'R', "");
                $pdf->Cell($wr[12], 7, number_format(($totalProfit), 2, '.', ''), 'LRBT', 0, 'R', "");
                $pdf->Cell($wr[13], 7, number_format(($totalPayments), 2, '.', ''), 'LRBT', 0, 'R', "");
                $pdf->Cell($wr[14], 7, number_format(($openingBalance + ($totalProfit - $totalPayments)), 2, '.', ''), 'LRBT', 0, 'R', $fill);
            }else{
                $pdf->Cell($wr[6], 7, "Total", 'LRBT', 0, 'R');
                $pdf->Cell($wr[7], 7, $productQtyTotal, 'LRBT', 0, 'R');
                $pdf->Cell($wr[8], 7, '', 'LRBT', 0, 'R');
                $pdf->Cell($wr[9], 7, $unitPriceTotal, 'LRBT', 0, 'R');
                $pdf->Cell($wr[10], 7, number_format(($totalDiscount), 0, '.', ''), 'LRBT', 0, 'R', "");
                $pdf->Cell($wr[11], 7, number_format(($totalProfit), 0, '.', ''), 'LRBT', 0, 'R', "");
                $pdf->Cell($wr[12], 7, number_format(($totalPayments), 0, '.', ''), 'LRBT', 0, 'R', "");
                $pdf->Cell($wr[13], 7, number_format(($openingBalance + ($totalProfit - $totalPayments)), 2, '.', ''), 'LRBT', 0, 'R', $fill);
            }

            $pdf->Ln();
            $pdf->Ln();
            $pdf->SetX($setx);
            $pdf->SetFont('Arial', '', 8);
            $pdf->Cell($wr[0], 7, '', '', 0, 'L');
            $pdf->Cell($wr[1], 7, '', '', 0, 'L');
            $pdf->Cell($wr[2], 7, "", '', 0, 'R');
            $pdf->Cell($wr[3], 7, "", '', 0, 'R');
            $pdf->Cell($wr[4], 7, "", '', 0, 'R');
            $pdf->Cell($wr[5], 7, "", '', 0, 'R');
            if ($customer_name == '' || $customer_name == 'All') {
                $pdf->Cell($wr[6], 7, "", '', 0, 'R');
                $pdf->Cell($wr[7], 7, "", 'LBT', 0, 'R');
                $pdf->Cell($wr[8], 7, "", 'BT', 0, 'R');
                $pdf->Cell($wr[9], 7, 'Total Opening Balance', 'RBT', 0, 'R');
                $pdf->Cell($wr[10], 7, "", 'BT', 0, 'R');
                $pdf->Cell($wr[11], 7, "", 'BT', 0, 'R', "");
                $pdf->Cell($wr[12], 7, "", 'BT', 0, 'R', "");
                $pdf->Cell($wr[13], 7, "", 'BT', 0, 'R', "");
                $pdf->Cell($wr[14], 7, !empty($openingBalance)?number_format(($openingBalance), 2, '.', ''):0, 'RBT', 0, 'R', "");
            }else{
                $pdf->Cell($wr[6], 7, "", 'LBT', 0, 'R');
                $pdf->Cell($wr[7], 7, '', 'BT', 0, 'R');
                $pdf->Cell($wr[8], 7, 'Total Opening Balance', 'RBT', 0, 'R');
                $pdf->Cell($wr[9], 7, '', 'BT', 0, 'R');
                $pdf->Cell($wr[10], 7, '', 'BT', 0, 'R', "");
                $pdf->Cell($wr[11], 7, '', 'BT', 0, 'R', "");
                $pdf->Cell($wr[12], 7, '', 'BT', 0, 'R', "");
                $pdf->Cell($wr[13], 7, !empty($openingBalance)?number_format(($openingBalance), 2, '.', ''):0, 'RBT', 0, 'R', "");
            }
            $pdf->Ln();
            $pdf->SetX($setx);
            $pdf->SetFont('Arial', '', 8);
            $pdf->Cell($wr[0], 7, '', '', 0, 'L');
            $pdf->Cell($wr[1], 7, '', '', 0, 'L');
            $pdf->Cell($wr[2], 7, "", '', 0, 'R');
            $pdf->Cell($wr[3], 7, "", '', 0, 'R');
            $pdf->Cell($wr[4], 7, "", '', 0, 'R');
            $pdf->Cell($wr[5], 7, "", '', 0, 'R');
            if ($customer_name == '' || $customer_name == 'All') {
                $pdf->Cell($wr[6], 7, "", '', 0, 'R');
                $pdf->Cell($wr[7], 7, "", 'LBT', 0, 'R');
                $pdf->Cell($wr[8], 7, "", 'BT', 0, 'R');
                $pdf->Cell($wr[9], 7, 'Total Remaining Balance', 'RBT', 0, 'R');
                $pdf->Cell($wr[10], 7, "", 'BT', 0, 'R');
                $pdf->Cell($wr[11], 7, "", 'BT', 0, 'R', "");
                $pdf->Cell($wr[12], 7, "", 'BT', 0, 'R', "");
                $pdf->Cell($wr[13], 7, "", 'BT', 0, 'R', "");
                $pdf->Cell($wr[14], 7, number_format(($openingBalance + ($totalProfit - $totalPayments)), 2, '.', ''), 'RBT', 0, 'R', "");
            }else{
                $pdf->Cell($wr[6], 7, "", 'LBT', 0, 'R');
                $pdf->Cell($wr[7], 7, '', 'BT', 0, 'R');
                $pdf->Cell($wr[8], 7, 'Total Remaining Balance', 'RBT', 0, 'R');
                $pdf->Cell($wr[9], 7, '', 'BT', 0, 'R');
                $pdf->Cell($wr[10], 7, '', 'BT', 0, 'R', "");
                $pdf->Cell($wr[11], 7, '', 'BT', 0, 'R', "");
                $pdf->Cell($wr[12], 7, '', 'BT', 0, 'R', "");
                $pdf->Cell($wr[13], 7, number_format(($openingBalance + ($totalProfit - $totalPayments)), 2, '.', ''), 'RBT', 0, 'R', "");
            }
            $pdf->Ln();
            $pdf->Ln();
            $pdf->SetX($setx);
            $pdf->SetFont('Arial', '', 9);
            $pdf->Cell($wr[1], 7, "", 'T', 0, 'C');
            $pdf->Cell($wr[2], 7, "", 'T', 0, 'C');
            $pdf->Cell($wr[3], 7, "Signature's", 'T', 0, 'L');
            $pdf->Cell($wr[4], 7, '', '', 0, 'R', "");
            $pdf->Cell($wr[5], 7, '', '', 0, 'R', "");
        }

        FancyTable($header, $invoice, $openingBalance, $product_id, $customer_name, $setx);
    } else {
        header('location: ' . PROJECT_ADMIN_URL);
        exit;
    }

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