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

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

    $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 = SalarySetupMart::GetSalarySetupList($filterSalaryReport);

    $qry = ExpenseMartSetup::GetExpenseMartSetupList($filterReport);


    $filterLoan = " WHERE DATE_FORMAT(create_date,'%Y-%m-%d')>='$qryDate' and DATE_FORMAT(create_date,'%Y-%m-%d')<='$qryTo' and status = 'active' ";
    $qryLoan = LoanSetup::GetLoanList($filterLoan);
    $loan = 0;
    if ($qryLoan){
        foreach($qryLoan AS $qryLoanRow){
            $loan += $qryLoanRow->amount;
        }
    }

    $filterMartLoan = " WHERE DATE_FORMAT(create_date,'%Y-%m-%d')>='$qryDate' and DATE_FORMAT(create_date,'%Y-%m-%d')<='$qryTo' and status = 'active' ";
    $qryMartLoan = LoanSetupMart::GetLoanList($filterMartLoan);
    $martLoan = 0;
    if ($qryMartLoan){
        foreach($qryMartLoan AS $qryMartLoanRow){
            $martLoan += $qryMartLoanRow->amount;
        }
    }
  
  $filterpay = " WHERE DATE_FORMAT(pay.create_date,'%Y-%m-%d')>='$qryDate' and DATE_FORMAT(pay.create_date,'%Y-%m-%d')<='$qryTo' AND pay.status <> 'Cancel' ";

    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('Expense 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, 'Expense Mart Report', 0, 0, 'C');

        if ($category_name != 'All') {
            $mainCategory = ExpenseMartCategorySetup::GetExpenseMartCategorySetupById($category_name);
            $subCategoryValue = '';
            if($sub_category != 'All'){
                $subCategory = ExpenseMartCategorySetup::GetExpenseMartCategorySetupById($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, $qrySalary, $setx, $loan, $martLoan, $payfilter)
        {
            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(100, 100);
            }

            //$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 = ExpenseMartCategorySetup::GetExpenseMartCategorySetupById($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);

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

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

                    $amountTotal+=$totalSalary;
                  
                   
                                  $totalPayment = Payment::GetTotalPaymentLists($payfilter);
                                  
                                  $withholdingTax += $totalPayment->withholding_tax;
                                    $amountTotal += $withholdingTax;
                  
                    //$amountTotal+=$loan;
                    $amountTotal+=$martLoan;

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

                    $pdf->Ln();
                    $pdf->SetX($setx);
                    $pdf->SetFont('Arial', '', 12);
                    $pdf->Cell($wr[0], 7, 'Mart Loan', 'LRBT', 0, 'L', $fill);
                    $pdf->Cell($wr[1], 7, $martLoan, 'LRBT', 0, 'R', $fill);
                    //Salary End

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

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

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


                        $catName = $qery->name;
                        if ($counter == 40 || ($counter != 40 && ($counter_pagebreak) % 44 == 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', '', 12);
                    $pdf->Cell(170, 7, 'Total    ', 'LRBT', 0, 'R', $fill);
                    $pdf->Cell(30, 7, $amountSubTotal, 'LRBT', 0, 'C', $fill);
                    $pdf->Ln();

                    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, 'C', true);
                        $pdf->Ln();
                    }
                }
            }
        }

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

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