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

    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_INVOICE_PRODUCT . " AS invPr ON inv.id = invPr.invoice_id INNER 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 = 0 ";
    $filterReport = " LEFT JOIN " . TABLE_INVOICE_PRODUCT . " AS invPr ON inv.id = invPr.invoice_id INNER 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') ";

    if (isset($customer_name) && $customer_name != 'All') {
        $filterReport .= " AND inv.customer_id ='$customer_name'";
    }
    if (isset($product_id) && $product_id != 'All') {
        $filterReport .= " AND invPr.product_id ='$product_id'";
    } else {
        $filterReport .= " GROUP BY inv.id";
    }
    $filterReport .= " ORDER BY inv.code ";

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

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

    $invoice = Invoice::GetInvoiceReportList($filterReport);
    if (!empty($invoice)) {

        $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('Invoice 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, 'Invoice 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);
        $header = array('S.No', 'Date', 'Invoice #', 'Customer', 'Status', 'Qty', 'Cost Price', 'Sales Price', 'Discount', 'Profit/Loss');

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

        function FancyTable($header, $data, $product_id, $qryExpense, $qrySalary, $setx, $customer_name)
        {
            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
            $wr = array(10, 25, 25, 83, 17, 20, 25, 25, 20, 30);
            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;
            $totalAmount = 0;
            if ($data) {
                foreach ($data AS $row) {
                    $customer = CustomerSetup::GetCustomerSetupById($row->customer_id);
                    $salesPerson = User_setup::GetUserSetupId($row->sales_person_id);
                    $discount_price = $row->discount_price;

                    $productSetup = ProductSetup::GetProductSetupById($row->product_id);

                    $pdf->SetX($setx);
                    $pdf->SetFont('Arial', '', 10);
                    $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);
                    $pdf->Cell($wr[2], 7, $row->code, 'LRBT', 0, 'L', $fill);
                    $pdf->SetFont('Arial', '', 10);
                    $pdf->Cell($wr[3], 7, strlen($customer->name) > 40 ? substr($customer->name, 0, 40) . "..." : $customer->name, 'LRBT', 0, 'L', $fill);
                    $pdf->SetFont('Arial', '', 10);
                    if ($product_id == 'All' || $product_id == '') {
                        $productsNames = array();
                        $productsQtys = '';
                        $productsUnitCostPrice = '';
                        $productsUnitSalePrice = '';

                        $filterProducts = " WHERE invoice_id = '$row->invoice_id'";
                        $productSetup = Invoice::GetInvoiceProducts($filterProducts);
                        if ($productSetup) {
                            foreach ($productSetup as $productSetupRows) {
                                $product = ProductSetup::GetProductSetupById($productSetupRows->product_id);
                                $productsNames[] = $product->name;
                                $productsQtys += $productSetupRows->product_qty;
                                $productsUnitCostPrice += number_format(($productSetupRows->product_qty * $productSetupRows->unit_cost_price), 2, '.', '');
                                if ($row->is_mart == 0) {
                                    $productsUnitSalePrice += number_format(($productSetupRows->product_qty * $productSetupRows->unit_sale_price), 2, '.', '');
                                } else {
                                    $productsUnitSalePrice += number_format(($productSetupRows->product_qty * $productSetupRows->unit_distributor_price), 2, '.', '');
                                }

                            }
                        }
                        $subtotal = $productsUnitSalePrice - $productsUnitCostPrice;
                        if ($row->is_mart == 0) {
                            if (PROJECT_DISCOUNT == 1 || !empty($discount_price) && ($product_id == '' || $product_id == 'All')) {

                                $subtotal -= $discount_price;
                                $totalDiscount += $discount_price;
                            }
                        }
                        $productsName = implode(', ', $productsNames);
                        $productQtyTotal += $productsQtys;
                        $costPriceTotal += $productsUnitCostPrice;
                        $unitPriceTotal += $productsUnitSalePrice;
                        $totalProfit += $subtotal;

                        //$pdf->Cell($wr[4], 7, strlen($productsName) > 50 ? substr($productsName, 0, 50) . "..." : $productsName, 'LRBT', 0, 'L', $fill);
                        //$pdf->Cell($wr[5], 7, $salesPerson->username, 'LRB', 0, 'R', $fill);
                        $pdf->Cell($wr[4], 7, $row->status, 'LRBT', 0, 'R', $fill);
                        $pdf->Cell($wr[5], 7, $productsQtys, 'LRBT', 0, 'R', $fill);
                        $pdf->Cell($wr[6], 7, $productsUnitCostPrice, 'LRBT', 0, 'R', $fill);
                        $pdf->Cell($wr[7], 7, $productsUnitSalePrice, 'LRBT', 0, 'R', $fill);
                        if ($row->is_mart == 0) {
                            $pdf->Cell($wr[8], 7, $discount_price, 'LRBT', 0, 'R', $fill);
                        } else {
                            $pdf->Cell($wr[8], 7, "0", 'LRBT', 0, 'R', $fill);
                        }
                        $pdf->Cell($wr[9], 7, number_format(($subtotal), 2, '.', ''), 'LRBT', 0, 'R', $fill);
                    } else {
                        $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;
                        if ($row->is_mart == 0) {
                            $unitPrice = number_format(($row->product_qty * $row->unit_sale_price), 2, '.', '');
                            $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 = ($unitPrice * ($totalDiscountper / 100));
                                $totalDiscount += $subTotalDiscount;
                                $subtotal -= $subTotalDiscount;
                            }
                            $totalProfit += $subtotal;
                        } else {
                            $unitPrice = number_format(($row->product_qty * $row->unit_distributor_price), 2, '.', '');
                            $unitPriceTotal += $unitPrice;
                            $subtotal = $unitPrice - $costPrice;
                            $totalProfit += $subtotal;
                        }
                        //$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[4], 7, $row->status, 'LRBT', 0, 'R', $fill);
                        $pdf->Cell($wr[5], 7, $row->product_qty, 'LRBT', 0, 'R', $fill);
                        $pdf->Cell($wr[6], 7, $costPrice, 'LRBT', 0, 'R', $fill);
                        $pdf->Cell($wr[7], 7, $unitPrice, 'LRBT', 0, 'R', $fill);
                        //$pdf->Cell($wr[9], 7, $discount_price, 'LRB', 0, 'R', $fill);
                        if ($row->is_mart == 0) {
                            $pdf->Cell($wr[8], 7, number_format(($subTotalDiscount), 2, '.', ''), 'LRBT', 0, 'R', $fill);
                        } else {
                            $pdf->Cell($wr[8], 7, "0", 'LRBT', 0, 'R', $fill);
                        }
                        $pdf->Cell($wr[9], 7, number_format(($subtotal), 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', 10);
                        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', '', 10);
            $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[4], 7, "Total", 'LRBT', 0, 'R');
            $pdf->Cell($wr[5], 7, $productQtyTotal, 'LRBT', 0, 'R');
            $pdf->Cell($wr[6], 7, $costPriceTotal, 'LRBT', 0, 'R');
            $pdf->Cell($wr[7], 7, $unitPriceTotal, 'LRBT', 0, 'R');
            $pdf->Cell($wr[8], 7, number_format(($totalDiscount), 2, '.', ''), 'LRBT', 0, 'R', "");
            $pdf->Cell($wr[9], 7, number_format($totalProfit, 2), 'LRBT', 0, 'R', "");


            if($customer_name == 'All') {
                $wr = array(280);
                $pdf->Ln();
                $pdf->Ln();
                $pdf->SetX($setx);
                $pdf->SetFont('Arial', 'B', 10);
                $pdf->Cell($wr[0], 7, 'Expense', 'LRBT', 0, 'C', $fill);
                
                $wr = array(215, 65);
                $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, 'LRBT', 0, 'R', '');
                        }
                        if ($catName != $exPCategory->name) {
                            $amountSubTotal = 0;
                            $counterSerial = 0;
                            $pdf->Ln();
                            $pdf->SetX($setx);
                            $pdf->SetFont('Arial', '', 14);
                            $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;

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

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

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

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

                $totalProfit -= $amountTotal;
                $totalProfit -= $totalSalary;
                //Salary End

                $pdf->Ln();
                $pdf->SetX($setx);
                $pdf->SetFont('Arial', '', 20);
                $pdf->Cell($wr[0], 7, 'Grand Expense', 'LRBT', 0, 'L', true);
                $pdf->Cell($wr[1], 7, ($amountTotal + $totalSalary), 'LRBT', 0, 'R', true);

                $pdf->Ln();
                $pdf->Ln();
                $pdf->SetX($setx);
                $pdf->SetFont('Arial', '', 20);
                $pdf->Cell($wr[0], 7, 'Total Profit', 'LRBT', 0, 'L', true);
                $pdf->Cell($wr[1], 7, $totalProfit, 'LRBT', 0, 'R', true);
            }
//            $pdf->Ln();
//            $pdf->Ln();
//            $pdf->SetX($setx);
//            $pdf->SetFont('Arial', '', 9);
//            $pdf->Cell($wr[1], 7, "Signature's", 'T', 0, 'C');
//            $pdf->Cell($wr[2], 7, "", '', 0, 'C');
//            $pdf->Cell($wr[3], 7, '', '', 0, 'R');
//            $pdf->Cell($wr[4], 7, '', '', 0, 'R', "");
//            $pdf->Cell($wr[5], 7, '', '', 0, 'R', "");
        }

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

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