<?php
error_reporting(E_ALL);
ini_set('display_errors', '0');
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 = " LEFT JOIN " . TABLE_CUSTOMERSETUP . " AS cs ON inv.customer_id = cs.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') AND cs.is_mart = 1 ";

    if (isset($cat_name) && (isset($cat_name[1]) || $cat_name[0] != "All")) {
        $filterReport .= " AND cs.category_id IN ('$cat_nameString')";
    }
    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 .= " ORDER BY inv.code ";

    $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('L', 'mm', 'A4');
        $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, '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', 'Date', 'Invoice', 'Customer', 'Product', 'Status', 'Qty', 'Fact. Price', 'Dist. Price', 'Sale Price', 'Discount', 'Sub Total', 'Profit Dist.', 'Profit Fact.');
        } else {
            $customer = CustomerSetup::GetCustomerSetupById($customer_name);
            $header = array('S.No', 'Date', 'Invoice', 'Product', 'Status', 'Qty', 'Fact. Price', 'Dist. Price', 'Sale Price', 'Discount', '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)
        {
            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, 16, 13, 40, 62, 12, 12, 18, 18, 18, 18, 18, 18, 18);
            } else {
                $wr = array(7, 16, 13, 92, 12, 12, 18, 18, 18, 18, 18, 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 = 0;
            $counter_pagebreak = 1;
            $totalAmount = 0;
            $distributorPriceTotal = 0;
            if($data){
                $countdown = 1;
                $reset = false;
                $qty = 0;
                $factoryRatePrice = 0;
                $distributorRatePrice = 0;
                $salesPrice = 0;
                $subTotalDiscountPrice = 0;
                foreach ($data AS $row) {
                    $counter++;
                    $customer = CustomerSetup::GetCustomerSetupById($row->customer_id);
                    $discount_price = $row->discount_price;

                    $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), 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) {
                        $totalDiscountper = $row->discount;

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

                    if(isset($data[$counter]->code)){
                        $nextCode = $data[$counter]->code;
                    }else{
                        $nextCode = 0;
                    }
                    if($reset == true){
                        $qty = 0;
                        $factoryRatePrice = 0;
                        $distributorRatePrice = 0;
                        $salesPrice = 0;
                        $subTotalDiscountPrice = 0;
                        $products = array();
                        $productsNames = "";
                        $reset = false;
                        $countdown++;
                    }
                    if($row->code == $nextCode){
                        $qty += $row->product_qty;
                        $factoryRatePrice += $costPrice;
                        $distributorRatePrice += $distributorPrice;
                        $salesPrice += $unitPrice;
                        $subTotalDiscountPrice += $subTotalDiscount;
                        $products[] = $productName->name;
                        continue;
                    }else{
                        $qty += $row->product_qty;
                        $factoryRatePrice += $costPrice;
                        $distributorRatePrice += $distributorPrice;
                        $salesPrice += $unitPrice;
                        $subTotalDiscountPrice += $subTotalDiscount;
                        $products[] = $productName->name;
                        $reset = true;
                        if(!empty($products)){
                            $productsNames = implode(', ', $products);
                        }
                    }

                    $pdf->SetX($setx);
                    $pdf->SetFont('Arial', '', 7);
                    $pdf->Cell($wr[0], 6, $countdown, 'LRBT', 0, 'C', $fill);
                    $pdf->Cell($wr[1], 6, date('Y-m-d', strtotime($row->create_date)), 'LRBT', 0, 'L', $fill);
                    $pdf->Cell($wr[2], 6, $row->code, 'LRBT', 0, 'L', $fill);

                    if ($customer_name == '' || $customer_name == 'All') {
                        $pdf->SetFont('Arial', '', 6);
                        $pdf->Cell($wr[3], 6, strlen($customer->name) > 28 ? substr($customer->name, 0, 28) . "..." : $customer->name, 'LRBT', 0, 'L', $fill);
                        $pdf->SetFont('Arial', '', 7);
                        $pdf->Cell($wr[4], 6, strlen($productsNames) > 45 ? substr($productsNames, 0, 45) . "..." : $productsNames, 'LRBT', 0, 'L', $fill);
                        $pdf->Cell($wr[5], 6, $row->status, 'LRBT', 0, 'R', $fill);
                        $pdf->Cell($wr[6], 6, $qty, 'LRBT', 0, 'R', $fill);
                        $pdf->Cell($wr[7], 6, $costPrice, 'LRBT', 0, 'R', $fill);
                        $pdf->Cell($wr[8], 6, $distributorRatePrice, 'LRBT', 0, 'R', $fill);
                        $pdf->Cell($wr[9], 6, $salesPrice, 'LRBT', 0, 'R', $fill);
                        $pdf->Cell($wr[10], 6, number_format(($subTotalDiscountPrice), 2, '.', ''), 'LRBT', 0, 'R', $fill);
                        $pdf->Cell($wr[11], 6, number_format(($salesPrice-$subTotalDiscountPrice), 2, '.', ''), 'LRBT', 0, 'R', $fill);
                        $pdf->Cell($wr[12], 6, number_format((($salesPrice-$subTotalDiscountPrice) - $distributorRatePrice), 2, '.', ''), 'LRBT', 0, 'R', $fill);
                        $pdf->Cell($wr[13], 6, number_format(($distributorRatePrice - $factoryRatePrice), 2, '.', ''), 'LRBT', 0, 'R', $fill);
                    }else{
                        $pdf->Cell($wr[3], 6, strlen($productsNames) > 72 ? substr($productsNames, 0, 72) . "..." : $productsNames, 'LRBT', 0, 'L', $fill);
                        $pdf->Cell($wr[4], 6, $row->status, 'LRBT', 0, 'R', $fill);
                        $pdf->Cell($wr[5], 6, $qty, 'LRBT', 0, 'R', $fill);
                        $pdf->Cell($wr[6], 6, $costPrice, 'LRBT', 0, 'R', $fill);
                        $pdf->Cell($wr[7], 6, $distributorRatePrice, 'LRBT', 0, 'R', $fill);
                        $pdf->Cell($wr[8], 6, $salesPrice, 'LRBT', 0, 'R', $fill);
                        $pdf->Cell($wr[9], 6, number_format(($subTotalDiscountPrice), 2, '.', ''), 'LRBT', 0, 'R', $fill);
                        $pdf->Cell($wr[10], 6, number_format(($salesPrice-$subTotalDiscountPrice), 2, '.', ''), 'LRBT', 0, 'R', $fill);
                        $pdf->Cell($wr[11], 6, number_format((($salesPrice-$subTotalDiscountPrice) - $distributorRatePrice), 2, '.', ''), 'LRBT', 0, 'R', $fill);
                        $pdf->Cell($wr[12], 6, number_format(($distributorRatePrice - $factoryRatePrice), 2, '.', ''), 'LRBT', 0, 'R', $fill);
                    }

                    if ($counter == 21 || ($counter != 21 && ($counter_pagebreak) % 25 == 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, '', '', 0, 'L');
            $pdf->Cell($wr[1], 6, '', '', 0, 'L');
            $pdf->Cell($wr[2], 6, "", '', 0, 'R');
            $pdf->Cell($wr[3], 6, "", '', 0, 'R');
            if ($customer_name == '' || $customer_name == 'All') {
                $pdf->Cell($wr[4], 6, "", '', 0, 'R');
                $pdf->Cell($wr[5], 6, "Total", 'LRBT', 0, 'R');
                $pdf->Cell($wr[6], 6, $productQtyTotal, 'LRBT', 0, 'R');
                $pdf->Cell($wr[7], 6, $costPriceTotal, 'LRBT', 0, 'R');
                $pdf->Cell($wr[8], 6, $distributorPriceTotal, 'LRBT', 0, 'R');
                $pdf->Cell($wr[9], 6, $unitPriceTotal, 'LRBT', 0, 'R');
                $pdf->Cell($wr[10], 6, $totalDiscount, 'LRBT', 0, 'R', "");
                $pdf->Cell($wr[11], 6, ($unitPriceTotal - $totalDiscount), 'LRBT', 0, 'R', "");
                $pdf->Cell($wr[12], 6, (($unitPriceTotal - $totalDiscount) - $distributorPriceTotal), 'LRBT', 0, 'R', "");
                $pdf->Cell($wr[13], 6, ($distributorPriceTotal - $costPriceTotal), 'LRBT', 0, 'R', "");
            }else{
                $pdf->Cell($wr[4], 6, "Total", 'LRBT', 0, 'R');
                $pdf->Cell($wr[5], 6, $productQtyTotal, 'LRBT', 0, 'R');
                $pdf->Cell($wr[6], 6, $costPriceTotal, 'LRBT', 0, 'R');
                $pdf->Cell($wr[7], 6, $distributorPriceTotal, 'LRBT', 0, 'R');
                $pdf->Cell($wr[8], 6, $unitPriceTotal, 'LRBT', 0, 'R');
                $pdf->Cell($wr[9], 6, ($totalDiscount), 'LRBT', 0, 'R', "");
                $pdf->Cell($wr[10], 6, ($unitPriceTotal - $totalDiscount), 'LRBT', 0, 'R', "");
                $pdf->Cell($wr[11], 6, (($unitPriceTotal - $totalDiscount) - $distributorPriceTotal), 'LRBT', 0, 'R', "");
                $pdf->Cell($wr[12], 6, ($distributorPriceTotal - $costPriceTotal), '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);
    } else {
        header('location: ' . PROJECT_ADMIN_URL);
        exit;
    }

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