<?php 
set_time_limit(0);
error_reporting(0);
if (substr_count($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip')) ob_start("ob_gzhandler"); else ob_start();
session_start();
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
date_default_timezone_set('Asia/Manila');
if (PHP_SAPI == 'cli')
	die('This example should only be run from a Web Browser'); 
require_once dirname(__FILE__) . '/Classes/PHPExcel/IOFactory.php'; 
$objReader = PHPExcel_IOFactory::createReader('Excel5');
PHPExcel_Cell::setValueBinder( new PHPExcel_Cell_AdvancedValueBinder() );
include_once('../config/minho.php');
include_once('../config/autoloadClass.php');

$autoload	=	new autoloadClass();
$mecon		=	new condbClass();
$main		=	array();
$main2		=	array();
$main3		=	array();
$main4		=	array();

$monthFrom		= isset($_GET['month_from']) ? strip_tags($_GET['month_from']) : "";
$monthTo		= isset($_GET['month_to']) ? strip_tags($_GET['month_to']) : "";
$filterSearch = isset($_GET['filter']) ? str_replace("'"," ",$_GET['filter']) : "";
$filterSearch	= isset($_GET['filter']) ? strip_tags($_GET['filter']) : "";
$isfilterdate = isset($_GET['isfilterdate']) ? strip_tags($_GET['isfilterdate']) : "";
$check_tobedelivered_date 	= isset($_REQUEST['check_tobedelivered_date'])   ? $_REQUEST['check_tobedelivered_date']	  : "";
$tobedate 	= isset($_REQUEST['tobe_stat_date'])   ? $_REQUEST['tobe_stat_date']	  : "";

$requestData = [];
   
$resultQuery = "SELECT r.Id as Id, r.Project as Project, r.Model as Model, r.ReservationDate as ReservationDate, r.Phase as Phase, r.Block as Block, r.Lot as Lot, CONCAT(r.LastName,', ',r.FirstName,' ',r.MiddleName) as FullName, CONCAT(MID(r.MiddleName, 1, 1),'.') as MiddleInitial, r.Broker as Broker, r.Agent as Agent, r.Spouse as Spouse, r.HomeTel as HomeTel, r.CellphoneNo as CellphoneNo, r.SpouseContactNo as SpouseContactNo, r.Address1 as Address1, r.Address2 as Address2, r.EmployerName as EmployerName, r.EmployeeType as EmployeeType, r.GrossIncome as GrossIncome, r.DiscountPromo as DiscountPromo, r.Position as Position, r.BuyerProfile as BuyerProfile, r.SpouseIncome as SpouseIncome, r.TinNo as TinNo, r.OfficeTel as OfficeTel, r.AggregateIncome as AggregateIncome, r.NoCoBorrower as NoCoBorrower, r.ReservationStatus as ReservationStatus, r.Status as rStatus, r.EmployeeType as EmployeeType, bsf.TakeOut as TakeOut, con.ReleasedPagibig as ReleasedPagibig, con.ProcessedDate as ProcessedDate, con.ReleasedDate as ReleasedDate, DATE_ADD(bsf.TakeOut, INTERVAL 18 MONTH) as conversions, bpm.ApprovedLoanable as ApprovedLoanable, ubl.TDLandNo as TDLandNo, ubl.TDBldgNo as TDBldgNo, cd.NotarialDate as NotarialDate, cd.TCT as TCT, cd.LMVTD as LMVTD, cd.ZonalValue as ZonalValue, cd.BMVTD as BMVTD, r.LastName as LastName, r.FirstName as FirstName, r.MiddleName as MiddleName, bsf.HLID as HLID, bsf.NOA as NOA, r.PricelistDate as PricelistDate FROM  reservation r LEFT JOIN buyer_status_folder_pagibig bsf ON bsf.ReservationId=r.Id LEFT JOIN conversion con ON con.ReservationId=r.Id LEFT JOIN buyer_payment_monitoring bpm ON bpm.ReservationId=r.Id LEFT JOIN units_block_lot ubl ON ubl.Block=r.Block AND ubl.Lot=r.Lot LEFT JOIN conversion_details cd ON cd.ReservationId=r.Id "; 
  

$sql			=	$resultQuery."  WHERE r.Status = 'active' AND r.ReservationStatus='active'  AND (bsf.TakeOut!='1970-01-01' OR bsf.TakeOut!=NULL) ";

if($tobedate=="yes" || $isfilterdate=="yes" || $check_tobedelivered_date=='yes'){
$sql .= " AND bsf.TakeOut BETWEEN ('".date('Y-m-d', strtotime($monthFrom))."') AND ('".date('Y-m-d', strtotime($monthTo))."')";
}
 

if(!empty($filterSearch)) { 
	$arr = explode(" ",$filterSearch);  
	foreach($arr as $ind){

		$ind = str_replace(',','',$ind);
		$sql.=" AND ( r.Block LIKE '%".$ind."%' ";
		$sql.=" OR r.Lot LIKE '%".$ind."%' "; 
		$sql.=" OR r.Project LIKE '%".$ind."%' ";
		$sql.=" OR r.ScheduleLoan LIKE '%".$ind."%' ";
		$sql.=" OR r.Model LIKE '%".$ind."%' ";
		$sql.=" OR CONCAT(r.LastName,', ',r.FirstName,' ',r.MiddleName) LIKE '%".htmlentities($ind)."%' ";
		$sql.=" OR UPPER(DATE_FORMAT(r.ReservationDate,'%m/%d/%Y')) LIKE '%".$ind."%' ";
		//$sql.=" OR r.ScheduleLoan = '".strtolower(str_replace(" ","_",$requestData['search']['value']))."' ";
		$sql.=" OR r.ScheduleLoan = '".strtolower(str_replace(" ","_",$ind))."' ";
		$sql.=" OR UPPER(DATE_FORMAT(r.ToBeDeliveredDate,'%m/%d/%Y')) LIKE '%".$ind."%' ";
		$sql.=" OR UPPER(DATE_FORMAT(r.ToBeDeliveredDate,'%d-%b-%Y')) LIKE '%".$ind."%'  ";   
		$sql.=" OR UPPER(DATE_FORMAT(bsf.TakeOut,'%m/%d/%Y')) LIKE '%".$ind."%' ";
		$sql.=" OR UPPER(DATE_FORMAT(bsf.TakeOut,'%d-%b-%Y')) LIKE '%".$ind."%'  "; 
		$sql.=" OR UPPER(DATE_FORMAT(r.ReservationDate,'%m/%d/%Y')) LIKE '%".$ind."%'  )";
		 
	}
}
 

if($isfilterdate=="yes"){
	if(!empty($monthFrom) && !empty($monthTo)){
		$sql .= " AND bsf.TakeOut BETWEEN ('".date('Y-m-d', strtotime($monthFrom))."') AND ('".date('Y-m-d', strtotime($monthTo))."')";
	}else if( !empty($monthFrom)){
		$sql .= " AND bsf.TakeOut >= ('".date('Y-m-d', strtotime($monthFrom))."') ";
	}else if( !empty($monthTo)){
		$sql .= " AND bsf.TakeOut <= ('".date('Y-m-d', strtotime($monthTo))."') ";
	} 
}	



  
$sql.=" ORDER BY  bsf.TakeOut DESC, cast(r.Block as unsigned) asc, cast(r.Lot as unsigned) asc "; 


$mecon->query($sql);
$main = $mecon->resultset(); 
$counter = count($main); 
$arr1 = array();
$arr2 = array();  
$arr3 = array();  

for($a=0; $a<$counter; $a++){   
	$arr1[0]	= trim($main[$a]['Block']);
	$arr1[1]	= trim($main[$a]['Lot']);
	$arr1[2]	= trim($main[$a]['TCT']);
	$arr1[3]	= strtoupper(trim(html_entity_decode(stripslashes($main[$a]['LastName']))));
	$arr1[4]	= strtoupper(trim(html_entity_decode(stripslashes($main[$a]['FirstName']))));
	$arr1[5]	= strtoupper(trim(html_entity_decode(stripslashes($main[$a]['MiddleName']))));
	$arr1[6]	= (($main[$a]['NOA']=='1970-01-01') || ($main[$a]['NOA']=='')) ? "" : date('m/d/Y', strtotime($main[$a]['NOA']));
	$arr1[7]	= strtoupper(trim(html_entity_decode(stripslashes($main[$a]['HLID']))));
	$arr1[8]	= (($main[$a]['TakeOut']=='1970-01-01') || ($main[$a]['TakeOut']=='')) ? "" : date('m/d/Y', strtotime($main[$a]['TakeOut']));
	$arr1[9]	= (isset($main[$a]['ApprovedLoanable'])) ? number_format($main[$a]['ApprovedLoanable'],2) : "";
	$arr2[] 	= $arr1;
}

$arr3['data'] = $arr2;
$fileName    = "takeout_accounts_report.xls";
$objPHPExcel = $objReader->load("templates/takeout_accounts_report.xls"); 
$baseRow = 2; 
for($a=0; $a<count($arr3['data']); $a++){ 
	$row = $baseRow + $a + 1;
				$objPHPExcel->getActiveSheet()->insertNewRowBefore($row,1); 
				$objPHPExcel->getActiveSheet()->setCellValue('A'.$row, $arr3['data'][$a][0])
											  ->setCellValue('B'.$row, $arr3['data'][$a][1])
											  ->setCellValue('C'.$row, $arr3['data'][$a][2])
											  ->setCellValue('D'.$row, $arr3['data'][$a][3])
											  ->setCellValue('E'.$row, $arr3['data'][$a][4])
											  ->setCellValue('F'.$row, $arr3['data'][$a][5])
											  ->setCellValue('G'.$row, $arr3['data'][$a][6])
											  ->setCellValue('H'.$row, $arr3['data'][$a][7])
											  ->setCellValue('I'.$row, $arr3['data'][$a][8])
											  ->setCellValue('J'.$row, $arr3['data'][$a][9]);
											  

			$objPHPExcel->getActiveSheet()->getStyle('G'.$row)->getNumberFormat()->setFormatCode('mm/dd/yyyy');
			$objPHPExcel->getActiveSheet()->getStyle('I'.$row)->getNumberFormat()->setFormatCode('mm/dd/yyyy');
			$objPHPExcel->getActiveSheet()->getStyle('H'.$row)->getNumberFormat()->setFormatCode('###0');
			$objPHPExcel->getActiveSheet()->getStyle('A'.$row)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_RIGHT); 
			$objPHPExcel->getActiveSheet()->getStyle('B'.$row)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_RIGHT); 
			$objPHPExcel->getActiveSheet()->getStyle('C'.$row)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_RIGHT); 
			$objPHPExcel->getActiveSheet()->getStyle('G'.$row)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_RIGHT); 
			$objPHPExcel->getActiveSheet()->getStyle('H'.$row)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_RIGHT); 
			$objPHPExcel->getActiveSheet()->getStyle('I'.$row)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_RIGHT); 
			$objPHPExcel->getActiveSheet()->getStyle('J'.$row)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_RIGHT); 
			$objPHPExcel->getActiveSheet()->getStyle('D'.$row)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_LEFT); 
			$objPHPExcel->getActiveSheet()->getStyle('E'.$row)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_LEFT); 
			$objPHPExcel->getActiveSheet()->getStyle('F'.$row)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_LEFT); 
			$styleArray = array('borders' => array('allborders' => array('style' => PHPExcel_Style_Border::BORDER_THIN)),'font' => array('bold' => false));
 			$objPHPExcel->getActiveSheet()->getStyle('A'.$row.':J'.$row)->applyFromArray($styleArray);

 }  
//$objPHPExcel->getActiveSheet()->removeRow($baseRow-1,1);
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5'); 
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="'.$fileName.'"');
header('Cache-Control: max-age=0');
header('Cache-Control: max-age=1');
header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified

//header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
//header ('Pragma: public'); // HTTP/1.0

header("Cache-Control: no-cache, no-store, must-revalidate"); // HTTP 1.1.
header("Pragma: no-cache"); // HTTP 1.0.
header("Expires: 0"); // Proxies.


$objWriter->save('php://output'); 