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

    if (!isset($_REQUEST['datefrom'])) {
        header('location: ../invoice.php');
        exit;
    }

    $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 <> 'Cancel' ";

    if (isset($customer_name) && $customer_name != 'All') {
        $filterReport .= " AND inv.customer_id ='$customer_name'";
    }
    if (isset($status) && $status != 'All') {
        $filterReport .= " AND inv.status ='$status'";
        $filterReport .= " GROUP BY inv.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";

    $invoice = Invoice::GetInvoiceReportList($filterReport);
    if (!empty($invoice)) 
    
    {
        $pdf = new FPDFWithOutWaterMark('L', 'mm', 'A4');
        $pdf->SetMargins(0, 0, 0);
        $pdf->SetTitle('Tax Invoice Status Report');
        $pdf->AddPage();
        $pdf->Ln();
        $pdf->SetFont('Arial', 'B', 16);
        $pdf->Cell(0, 8, PROJECT_NAME, 0, 0, 'C');
        $pdf->SetX(10);
        $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, 'Tax Invoice Status Report', 0, 0, 'C');

        if ($customer_name != 'All' && $customer_name != '') 
           {
            $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(10);

        // Matching headers with the view report
//        $header = array('S.No', 'Date', 'Invoice', 'Customer', 'Status', 'Total Amount', 'Discount', 'Payments', 'Balance');
		 $header = array('S.No', 'Date', 'Invoice', 'Customer','NTN/STRN No.','Qty','Value Exc. Sales tax','Sales Tax %','Sales Tax Amount', 'Value Inc. Sales Tax', 'Advance Tax Amount' , 'Total');

         function FancyTable($header, $data, $product_id, $setx, $customer_name)
          {
            global $pdf;

            // Totals
            $totalAmountSum = 0;
            $totalDiscountSum = 0;
            $totalPaymentSum = 0;
            $totalBalanceSum = 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', 7);

            // Column Widths
              $wr = array(10, 16, 20, 75, 20,10,20, 20, 20, 30,20,20);
            //$wr = array(10, 20, 25, 85, 20, 30, 20, 30, 30);

            // Header
            for ($i = 0; $i < count($header); $i++) {
                $pdf->Cell($wr[$i], 7, $header[$i], 1, 0, 'C', true);
            }
            $pdf->Ln();

            // Data
            $fill = false;
            $counter = 1;

            foreach ($data as $row) 
			{
              // error_log("data as row : " . print_r($data, true));
                $customer = CustomerSetup::GetCustomerSetupById($row->customer_id);

                // Payments calculation
                $filterPayment = " WHERE invoice_reference_code = '$row->invoice_id' AND status <> 'Cancel'";
                $paymentData = Payment::GetPaymentList($filterPayment);
                $pyBalance = 0;
                foreach ($paymentData as $paymentDataRow) 
                {
                    $pyBalance += $paymentDataRow->amount;
                }

                // Balance calculation
                $balance = $row->total_amount - $row->discount_price - $pyBalance;

                // Add to totals
                $totalAmountSum += $row->total_amount;
                $totalDiscountSum += $row->discount_price;
                $totalPaymentSum += $pyBalance;
                $totalBalanceSum += $balance;
              
            
              //////////////////////////
            
          $qry = Invoice::GetInvoiceReportList($filterReport);
                if ($qry) 
                    {
                        $counter = 1;
                        foreach ($qry as $qery) 
						   
                        { 
                               
                                    $customer = CustomerSetup::GetCustomerSetupById($qery->customer_id);
                                    $salesPerson = User_setup::GetUserSetupId($qery->sales_person_id);
                                    $discount_price = $qery->discount_price;
                                    $salesTaxPercentage = $qery->tax;
                                    $salesTaxPrice = $qery->tax_price;
                                    $valueIncSalexTax = $qery->tax_price;
                                    $advanceTaxPrice = $qery->adv_tax_price;
                                    $totalAmount = $qery->total_amount;  
                                   
 
                                    if ($product_id == 'All' || $product_id == '') 
                                    {
//                                        $productsNames = array();
                                        $productsQtys = 0;
                                        $productsUnitCostPrice = 0;
                                        $productsUnitSalePrice = 0;

                                        $filterProducts = " WHERE invoice_id = '$qery->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 ($qery->is_mart == 0) 
                                                {
                                             $productsUnitSalePrice += number_format(($productSetupRows->product_qty * $productSetupRows->unit_sale_price), 2, '.', '');
                                                } else 
                                                {
                                            $productsUnitSalePrice += number_format(($productSetupRows->product_qty * $productSetupRows->unit_sale_price), 2, '.', '');
                                                }
                                            }
                                        }
                                        $subtotal = $productsUnitSalePrice - $productsUnitCostPrice;
                                        if ($qery->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;
                                      	$salesTaxPriceTotal += $salesTaxPrice;
                                      	$advanceTaxPriceTotal += $advanceTaxPrice;
                                        $totalAmountTotal += $totalAmount;
                                      	
                                        }
                                   }

                             }		
                                
             
              }
              

                $pdf->SetX($setx);
                $pdf->SetFont('Arial', '', 8);
                $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->Cell($wr[3], 7, strlen($customer->name) > 40 ? substr($customer->name, 0, 40) . "..." : $customer->name, 'LRBT', 0, 'L', $fill);
                $pdf->Cell($wr[4], 7, $customer->ntn, 'LRBT', 0, 'R', $fill);
                $pdf->Cell($wr[5], 7, $productsQtys, 'LRBT', 0, 'R', $fill);
                $pdf->Cell($wr[6], 7,  $productsUnitSalePrice, 'LRBT', 0, 'R', $fill);
                $pdf->Cell($wr[7], 7, $salesTaxPercentage, 'LRBT', 0, 'R', $fill);
                $pdf->Cell($wr[8], 7, $salesTaxPrice, 'LRBT', 0, 'R', $fill);
                $pdf->Cell($wr[9], 7, $valueIncSalesTax, 'LRBT', 0, 'R', $fill);
                $pdf->Cell($wr[10], 7, $advanceTaxPrice, 'LRBT', 0, 'R', $fill);
                $pdf->Cell($wr[11], 7, $totalAmount, 'LRBT', 0, 'R', $fill);
                $pdf->Ln();

                $counter++;
                $fill = !$fill;
            }

            // Footer Total Row
            $pdf->SetX($setx);
            $pdf->SetFont('Arial', 'B', 10);
            $pdf->Cell($wr[0], 7, '', '', 0, 'C');
            $pdf->Cell($wr[1], 7, '', '', 0, 'L');
            $pdf->Cell($wr[2], 7, '', '', 0, 'L');
            $pdf->Cell($wr[3], 7, 'Total', 'LRBT', 0, 'R');
            $pdf->Cell($wr[4], 7, '', 'LRBT', 0, 'R');
            $pdf->Cell($wr[5], 7, number_format($totalAmountSum, 2, '.', ''), 'LRBT', 0, 'R');
            $pdf->Cell($wr[6], 7, number_format($totalDiscountSum, 2, '.', ''), 'LRBT', 0, 'R');
            $pdf->Cell($wr[7], 7, number_format($totalPaymentSum, 2, '.', ''), 'LRBT', 0, 'R');
            $pdf->Cell($wr[8], 7, number_format($totalBalanceSum, 2, '.', ''), 'LRBT', 0, 'R');
        }

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

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