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

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

    $category_name = $_GET['category_name'];
    $sub_category = $_GET['sub_category'];

    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 = " AS ex RIGHT JOIN " . TABLE_PURCHASECATEGORYSETUP . " AS exCat ON ex.category_id = exCat.id WHERE DATE_FORMAT(lastupdated,'%Y-%m-%d')>='$qryDate' and DATE_FORMAT(lastupdated,'%Y-%m-%d')<='$qryTo' ";

    if (isset($category_name) && $category_name != 'All') {
        if (isset($sub_category) && $sub_category != 'All') {
            $filterReport .= " AND ex.category_id ='$sub_category'";
        } else {
            $filterReport .= " AND exCat.parent_id ='$category_name'";
        }
        $filterReport .= " ORDER BY ex.category_id";
    } else {
        $filterReport .= " ORDER BY exCat.parent_id";
    }

    $qry = PurchaseSetup::GetPurchaseSetupList($filterReport);

    $filterReportPay = " WHERE DATE_FORMAT(create_date,'%Y-%m-%d')>='$qryDate' AND DATE_FORMAT(create_date,'%Y-%m-%d')<='$qryTo' AND status <> 'Cancel'";
    if (isset($category_name) && $category_name != 'All') {
        $filterReportPay .= " AND supplier_id = '$category_name'";
    }
    $qrypayment = Purpayment::GetPurpaymentList($filterReportPay);

    if (!empty($qry)) {

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

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

        $pdf->SetTitle('Purchase 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, 'Purchase Report', 0, 0, 'C');

        if ($category_name != 'All') {
            $mainCategory = PurchaseCategorySetup::GetPurchaseCategorySetupById($category_name);
            $subCategoryValue = '';
            if($sub_category != 'All'){
                $subCategory = PurchaseCategorySetup::GetPurchaseCategorySetupById($sub_category);
                $subCategoryValue = ' ( '.$subCategory->name.' )';
            }
            $pdf->Ln();
            $pdf->SetFont('Arial', '', 14);
            $pdf->Cell(0, 6, $mainCategory->name.''.$subCategoryValue, 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 ($category_name != 'All' || $sub_category != 'All') {
            $header = array('S.No', 'Date', 'Description', 'Amount');
        }
        //$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, $category_name, $sub_category, $setx, $qrypayment)
        {
            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', 12);
            // Header
            if ($category_name != 'All' || $sub_category != 'All') {
                $wr = array(15, 30, 125, 30);
                //for ($i = 0; $i < count($header); $i++)
                //    $pdf->Cell($wr[$i], 7, $header[$i], 1, 0, 'C', true);
            }else{
                $wr = array(170, 30);
            }

            //$pdf->Ln();
            // Color and font restoration
            $pdf->SetFillColor(224, 235, 255);
            $pdf->SetTextColor(0);
            $pdf->SetFont('');
            // Data
            $fill = false;

            $counter = 1;
            $counter_pagebreak = 1;
            if ($data) {

                if ($category_name == 'All' && $sub_category == 'All') {
                    $counter = 0;
                    $counterSerial = 0;
                    $amountTotal = 0;
                    $amountSubTotal = 0;
                    $mainCat = '';
                    $catName = '';
                    foreach ($data as $qery) {
                        $exPCategory = PurchaseCategorySetup::GetPurchaseCategorySetupById($qery->parent_id);
                        $counter++;
                        if ($exPCategory->name != $mainCat && $counter != 1) {
                            $pdf->Cell($wr[1], 7, $amountSubTotal, 'LRBT', 0, 'R', $fill);
                        }
                        if ($catName != $exPCategory->name) {
                            $amountSubTotal = 0;
                            $counterSerial = 0;
                            $pdf->Ln();
                            $pdf->SetX($setx);
                            $pdf->SetFont('Arial', '', 12);
                            $pdf->Cell($wr[0], 7, $exPCategory->name, 'LRBT', 0, 'L', $fill);


                            //$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', $fill);

                    $totalPayment = 0;
                    if($qrypayment){
                        foreach($qrypayment AS $qrypaymentRow){
                            $totalPayment += $qrypaymentRow->amount;
                        }
                    }
                    $amountTotalfinal = $amountTotal- $totalPayment;

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

//                    $pdf->Ln();
//                    $pdf->Ln();
//                    $pdf->SetX($setx);
//                    $pdf->SetFont('Arial', '', 7);
//                    $pdf->Cell($wr[0], 7, 'Total Payment', 'LRBT', 0, 'L', $fill);
//                    $pdf->Cell($wr[1], 7, $totalPayment, 'LRBT', 0, 'R', $fill);

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

                } else {
                    $counter = 0;
                    $counterSerial = 0;
                    $amountTotal = 0;
                    $amountSubTotal = 0;
                    $catName = '';
                    foreach ($data as $qery) {
                        $counter++;
                        if ($qery->name != $catName && $counterSerial != 0) {
                            $counter++;
                            $counter_pagebreak++;
                            $pdf->SetX($setx);
                            $pdf->SetFont('Arial', '', 12);
                            $pdf->Cell(170, 7, 'Total    ', 'LRBT', 0, 'R', $fill);
                            $pdf->Cell(30, 7, $amountSubTotal, 'LRBT', 0, 'L', $fill);
                            $pdf->Ln();
                        }
                        if ($catName != $qery->name) {
                            $amountSubTotal = 0;
                            $counterSerial = 0;

                            $pdf->Ln();
                            $pdf->SetX($setx);
                            $pdf->SetFont('Arial', '', 12);
                            $pdf->Cell(200, 7, $qery->name, 'LRBT', 0, 'C', $fill);
                            $counter++;
                            $counter_pagebreak++;

                            $pdf->Ln();
                            $pdf->SetFont('Arial', '', 12);
                            $pdf->SetX($setx);
                            if ($category_name != 'All' || $sub_category != 'All') {
                                $counter++;
                                $counter_pagebreak++;
                                for ($i = 0; $i < count($header); $i++)
                                    $pdf->Cell($wr[$i], 7, $header[$i], 1, 0, 'L', true);
                            }
                            $pdf->Ln();
                        }
                        $counterSerial++;

                        $pdf->SetX($setx);
                        $pdf->SetFont('Arial', '', 12);
                        $pdf->Cell($wr[0], 7, $counterSerial, 'LRBT', 0, 'L', $fill);
                        $pdf->Cell($wr[1], 7, date('Y-m-d', strtotime($qery->lastupdated)), 'LRBT', 0, 'L', $fill);
                        $pdf->Cell($wr[2], 7, $qery->description, 'LRBT', 0, 'L', $fill);
                        $pdf->Cell($wr[3], 7, number_format(($qery->amount), 2, '.', ''), 'LRBT', 0, 'L', $fill);

                        $amountSubTotal += $qery->amount;
                        $amountTotal += $qery->amount;


                        $catName = $qery->name;
                        if ($counter == 30 || ($counter != 30 && ($counter_pagebreak) % 32 == 0)) {
                            $counter_pagebreak = 1;
                            $pdf->AddPage();
                            $pdf->SetX($setx);
                            $pdf->SetFont('Arial', 'B', 12);
                            for ($i = 0; $i < count($header); $i++)
                                $pdf->Cell($wr[$i], 7, $header[$i], 1, 0, 'L', true);
                        }


                        $pdf->Ln();
                        //$fill = !$fill;
                        $counter++;
                        $counter_pagebreak++;
                    }
                    /*
                    $pdf->SetX($setx);
                    $pdf->SetFont('Arial', '', 7);
                    $pdf->Cell(170, 7, 'Total    ', 'LRBT', 0, 'R', $fill);
                    $pdf->Cell(30, 7, $amountSubTotal, 'LRBT', 0, 'L', $fill);
                    $pdf->Ln();


                    $totalPayment = 0;
                    if($qrypayment){
                        $counterSerial = 0;
                        foreach($qrypayment AS $qrypaymentRow){
                            $counterSerial++;
                            $bank_name = BankSetup::GetBankSetupById($qrypaymentRow->bank_name);
                            if ($counterSerial == 1) {
                                $pdf->Ln();
                                $pdf->SetX($setx);
                                $pdf->SetFont('Arial', '', 7);
                                $pdf->Cell(200, 7, "Payments", 'LRBT', 0, 'C', $fill);
                                $counter++;
                                $counter_pagebreak++;

                                $pdf->Ln();
                                $pdf->SetX($setx);
                                if ($category_name != 'All' || $sub_category != 'All') {
                                    $counter++;
                                    $counter_pagebreak++;
                                    for ($i = 0; $i < count($header); $i++)
                                        $pdf->Cell($wr[$i], 7, $header[$i], 1, 0, 'L', true);
                                }
                            }
                            $pdf->Ln();
                            $pdf->SetX($setx);
                            $pdf->SetFont('Arial', '', 7);
                            $pdf->Cell($wr[0], 7, $counterSerial, 'LRBT', 0, 'L', $fill);
                            $pdf->Cell($wr[1], 7, date('Y-m-d', strtotime($qrypaymentRow->create_date)), 'LRBT', 0, 'L', $fill);
                            $pdf->Cell($wr[2], 7, ucwords($qrypaymentRow->payment_type)." - ".$bank_name->bank_name, 'LRBT', 0, 'L', $fill);
                            $pdf->Cell($wr[3], 7, number_format(($qrypaymentRow->amount), 2, '.', ''), 'LRBT', 0, 'L', $fill);
                            $totalPayment += $qrypaymentRow->amount;
                        }
                        $pdf->Ln();
                        $pdf->SetX($setx);
                        $pdf->SetFont('Arial', '', 7);
                        $pdf->Cell(170, 7, 'Total    ', 'LRBT', 0, 'R', $fill);
                        $pdf->Cell(30, 7, $totalPayment, 'LRBT', 0, 'L', $fill);
                        $pdf->Ln();
                    }
                    $amountTotalfinal = $amountTotal- $totalPayment;
                    */
                    if($sub_category == 'All'){
                        $pdf->Ln();
                        $pdf->SetX($setx);
                        $pdf->SetFont('Arial', '', 12);
                        $pdf->Cell(170, 7, 'Total    ', 'LRBT', 0, 'R', true);
                        $pdf->Cell(30, 7, $amountTotal, 'LRBT', 0, 'L', true);
                        $pdf->Ln();
                    }
                }
            }
        }

        FancyTable($header, $qry, $category_name, $sub_category, $setx, $qrypayment);
    } else {
        header('location: ' . PROJECT_ADMIN_URL);
        exit;
    }

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