<?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));

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

    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 cs.is_mart = 1 AND inv.code IS NULL";
    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";
    }
    $invoice = Invoice::GetInvoiceReportList($filterReport);
    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('Mart 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 Mart 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 Dist.', 'Profit Fact.');
        } else {
            $customer = CustomerSetup::GetCustomerSetupById($customer_name);
            $header = array('S.No', 'Customer', 'Opening Balance', 'Total Balance', 'Sub Total', 'Profit Dist.', '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, $data, $product_id, $customer_name, $setx, $qryDate, $qryTo)
        {
            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(.1);
            $pdf->SetFont('Arial', 'B', 7.5);
            // Header
            if ($customer_name == '' || $customer_name == 'All') {
                $wr = array(7, 83, 22, 22, 22, 22, 22);
            } else {
                $wr = array(7, 83, 22, 22, 22, 22, 22);
            }
            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;
            if($data){
                $countdown = 1;
                $reset = false;
                $qty = 0;
                $factoryRatePrice = 0;
                $distributorRatePrice = 0;
                $salesPrice = 0;
                $subTotalDiscountPrice = 0;
                $totalBalance = 0;
                foreach ($data AS $row) {
                    $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;
                    $unitPrice = number_format(($row->product_qty * $row->unit_sale_price), 2, '.', '');
                    $unitPriceTotal += $unitPrice;
                    $distributorPrice = number_format(($row->product_qty * $row->unit_distributor_price), 2, '.', '');
                    $distributorPriceTotal += $distributorPrice;
                    $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($data[$counter]->custid)){
                        $nextCode = $data[$counter]->custid;
                    }else{
                        $nextCode = 0;
                    }
                    if($reset == true){
                        $qty = 0;
                        $factoryRatePrice = 0;
                        $distributorRatePrice = 0;
                        $salesPrice = 0;
                        $subTotalDiscountPrice = 0;
                        $reset = false;
                        $countdown++;
                    }
                    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, '.', '');
                    }

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

                    $totalBalance += (($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) - $distributorRatePrice), 2, '.', ''), 'LRBT', 0, 'R', $fill);
                        $pdf->Cell($wr[6], 6, number_format(($distributorRatePrice - $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) - $distributorRatePrice), 2, '.', ''), 'LRBT', 0, 'R', $fill);
                        $pdf->Cell($wr[6], 6, number_format(($distributorRatePrice - $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', 'B', 7);
                        for ($i = 0; $i < count($header); $i++)
                            $pdf->Cell($wr[$i], 7, $header[$i], 1, 0, 'C', true);
                    }


                    $pdf->Ln();
                    $fill = !$fill;
                    $counter_pagebreak++;
                }
            }
            //$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');
            if ($customer_name == '' || $customer_name == 'All') {
                $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, number_format((($unitPriceTotal - $totalDiscount) - $distributorPriceTotal), 2, '.', ''), 'LRBT', 0, 'R', "");
                $pdf->Cell($wr[6], 6, number_format(($distributorPriceTotal - $costPriceTotal), 2, '.', ''), 'LRBT', 0, 'R', "");
            }else{
                $pdf->Cell($wr[2], 6, "Total", 'LRBT', 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, number_format((($unitPriceTotal - $totalDiscount) - $distributorPriceTotal), 2, '.', ''), 'LRBT', 0, 'R', "");
                $pdf->Cell($wr[6], 6, number_format(($distributorPriceTotal - $costPriceTotal), 2, '.', ''), 'LRBT', 0, 'R', "");
            }
//            $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, $product_id, $customer_name, $setx, $qryDate, $qryTo);
    } else {
        header('location: ' . PROJECT_ADMIN_URL);
        exit;
    }

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