<?php
error_reporting(0);
if (substr_count($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip')) ob_start("ob_gzhandler"); else ob_start();
session_start();  
include_once('../config/minho.php');
include_once('../config/autoloadClass.php');
$autoload		=	new autoloadClass(); 
$mecon			=	new condbClass();
$formClass		=	new formClass();
$requestData	=	$_REQUEST; 
$columns = array(
	 
	0	=>	'Block', 
	1	=>	'Lot',
	2	=>	'TCT', 
	3	=>	'LastName', 
	4	=>	'FirstName', 
	5	=>	'MiddleName',
	6	=>	'NOA', 
	7	=>	'HLID', 
	8	=>	'TakeOut',
	9	=>	'ApprovedLoanable', 
	10	=>	'ReservationStatus'  
);
$tobedate 	= isset($_REQUEST['tobe_stat_date'])   ? $_REQUEST['tobe_stat_date']	  : "yes";
$rangeStart = isset($_REQUEST['range_start']) ?  $_REQUEST['range_start'] : date('Y-m-d', strtotime(date('01-m-Y')));
$rangeEnd 	= isset($_REQUEST['range_end'])   ? $_REQUEST['range_end']	  : date("Y-m-t", strtotime(date('Y-m-d')));
    
//$resultQuery 		= "SELECT r.ReservationStatus as ReservationStatus, r.Id as Id, bpm.LoanableAmount as LoanableAmount, r.Block as Block, r.Lot as Lot, CONCAT(r.LastName,', ',r.FirstName,' ', r.MiddleName) as Fullname, r.PricelistDate as PricelistDate, r.Phase as Phase, r.Project as Project, r.Model as Model, r.ReservationDate as ReservationDate, r.Project, r.Model, r.ScheduleLoan as ScheduleLoan, r.ToBeDeliveredDate as ToBeDeliveredDate FROM reservation r LEFT JOIN buyer_payment_monitoring bpm ON bpm.ReservationId=r.Id  "; 
 
//$sql			=	$resultQuery."  WHERE r.Status = 'active' AND (r.ScheduleLoan='to_be_delivered' OR r.ScheduleLoan='delivered') ";

$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(!empty($requestData['search']['value']) ) { 
	$arr = explode(" ",$requestData['search']['value']);  
	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 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,'%d-%b-%Y')) LIKE '%".$ind."%' ) ";   
	}
	//$sql.=" OR r.ScheduleLoan = '".strtolower(str_replace(" ","_",$requestData['search']['value']))."' ";
}

if($tobedate=="yes"){ 
	if( !empty($requestData['columns'][0]['search']['value']) && !empty($requestData['columns'][1]['search']['value']) ){
		$sql .= " AND bsf.TakeOut BETWEEN ('".date('Y-m-d', strtotime($requestData['columns'][0]['search']['value']))."') AND ('".date('Y-m-d', strtotime($requestData['columns'][1]['search']['value']))."')";
	}else if( !empty($requestData['columns'][0]['search']['value'])){
		$sql .= " AND bsf.TakeOut >= ('".date('Y-m-d', strtotime($requestData['columns'][0]['search']['value']))."') ";
	}else if( !empty($requestData['columns'][1]['search']['value'])){
		$sql .= " AND bsf.TakeOut <= ('".date('Y-m-d', strtotime($requestData['columns'][1]['search']['value']))."') ";
	}

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

$mecon->query($sql);
$result			= $mecon->resultset(); 
$totalData		= count($result);
$totalFiltered	=	$totalData;
  
  
$sql.=" ORDER BY ". $columns[$requestData['order'][0]['column']]."   ".$requestData['order'][0]['dir'].", cast(r.Block as unsigned) asc, cast(r.Lot as unsigned) asc  LIMIT ".$requestData['start']." ,".$requestData['length']."   "; 

$detArr = array();
$data = array(); 
$mecon->query($sql);
$result			= $mecon->resultset(); 

		for($a=0; $a<count($result); $a++){
			$nestedData=array();  
			 

				$nestedData[]	= trim($result[$a]['Block']);
				$nestedData[]	= trim($result[$a]['Lot']); 
				$nestedData[]	= trim($result[$a]['TCT']);
 				$nestedData[] 	= strtoupper(trim(html_entity_decode(stripslashes($result[$a]['LastName']))));
				$nestedData[] 	= strtoupper(trim(html_entity_decode(stripslashes($result[$a]['FirstName']))));
				$nestedData[] 	= strtoupper(trim(html_entity_decode(stripslashes($result[$a]['MiddleName']))));

				$nestedData[] = (($result[$a]['NOA']=='1970-01-01') || ($result[$a]['NOA']=='')) ? "" : date('m/d/Y', strtotime($result[$a]['NOA']));

				$nestedData[] 	= strtoupper(trim(html_entity_decode(stripslashes($result[$a]['HLID']))));

				$nestedData[] = (($result[$a]['TakeOut']=='1970-01-01') || ($result[$a]['TakeOut']=='')) ? "" : date('m/d/Y', strtotime($result[$a]['TakeOut']));

				$nestedData[] 	= (isset($result[$a]['ApprovedLoanable'])) ? number_format($result[$a]['ApprovedLoanable'],2) : ""; 				
 				$nestedData[] = strtoupper(trim(html_entity_decode(stripslashes($result[$a]['ReservationStatus']))));

			$data[] = $nestedData;
		} 
$json_data = array(
			"draw"            => intval( $requestData['draw'] ),
			"recordsTotal"    => intval( $totalData ),
			"recordsFiltered" => intval( $totalFiltered ),
			"data"            => $data
			);
			 
echo json_encode($json_data);
exit();
ob_end_flush();
?>