<?  
//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; 
$user_type = isset($_SESSION['danvilles_user_type']) ? strip_tags(stripslashes(trim($_SESSION['danvilles_user_type']))) : "";
$columns = array(
	0	=>	'NotarialDate', //Notarial Date to encode by liaison
	1	=>	'TakeOut',
	2	=>	'Id',
	3	=>	'LastName',
	4	=>	'FirstName',
	5	=>	'MiddleInitial',
	6	=>	'Block',
	7	=>	'Lot',
	8	=>	'', //Lot size get data from query
	9 	=>  'TCT', //TCT to encode by liaison
	10 	=> 'TDLandNo', //pickup last 5 digit from units_block_lot table
	11 	=> 'TDBldgNo', //pickup last 5 digit from units_block_lot table
	12  => 'LMVTD', //LMV -TD to encode by liaison
	13  => 'ZonalValue', //Zonal Value to encode by liaison
	14  => 'BMVTD', //BMV - TD to encode by liaison 
	15  => '', //auto combine from Land-TD No. and Bldg TD No. table column
	16  => 'ApprovedLoanable', //Selling Price / Approved Loanable Amount from acctg1
	17  => 'TinNo' //Tin – data from Documentation1 
);  

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

$mainQuery 		= "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.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			=	$mainQuery."  WHERE r.Status = 'active' AND r.ReservationStatus='active'  AND (bsf.TakeOut!='1970-01-01' OR bsf.TakeOut!=NULL) ";
$tobe 			= isset($_REQUEST['tobe_stat'])   ? $_REQUEST['tobe_stat']	  : "yes";
$tobeno 		= isset($_REQUEST['tobe_stat_no'])   ? $_REQUEST['tobe_stat_no']	  : "yes";
$tobedate 		= isset($_REQUEST['tobe_stat_date'])   ? $_REQUEST['tobe_stat_date']	  : "yes";

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 CONCAT(r.LastName,', ',r.FirstName,' ',r.MiddleName) LIKE '%".htmlentities($ind)."%' ";
		$sql.=" OR UPPER(DATE_FORMAT(con.ReleasedPagibig,'%m/%d/%Y')) LIKE '".$ind."%' ";   
		$sql.=" OR r.TinNo LIKE '".$ind."%' "; 
		$sql.=" OR r.LastName LIKE '".$ind."%' ";
		$sql.=" OR r.FirstName LIKE '".$ind."%' ";
		$sql.=" OR CONCAT(MID(r.MiddleName, 1, 1),'.') LIKE '".$ind."%' ";  
		$sql.=" OR UPPER(DATE_FORMAT(bsf.TakeOut,'%m/%d/%Y')) LIKE '".$ind."%' "; 
		$sql.=" OR r.Lot LIKE '".$ind."%' )"; 
	}
}
 

if($tobedate=="yes"){
	if( !empty($rangeStart) && !empty($rangeEnd) ){
		$sql .= " AND con.ReleasedPagibig BETWEEN ('".date('Y-m-d', strtotime($rangeStart))."') AND ('".date('Y-m-d', strtotime($rangeEnd))."')";
	}else if( !empty($rangeStart)){
		$sql .= " AND con.ReleasedPagibig >= ('".date('Y-m-d', strtotime($rangeStart))."') ";
	}else if( !empty($rangeEnd)){
		$sql .= " AND con.ReleasedPagibig <= ('".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']." LIMIT ".$requestData['start']." ,".$requestData['length']."   "; 

$sql.=" ORDER BY cast(r.Block as unsigned)   ".$requestData['order'][0]['dir'].", cast(r.Lot as unsigned) asc LIMIT ".$requestData['start']." ,".$requestData['length']."   "; 


  
$mecon->query($sql);
$data = array();
$result = $mecon->resultset();
 
			 for($a=0; $a<count($result); $a++){
				$nestedData=array();
				 
 				$notarialDate = date('m/d/Y', strtotime($result[$a]['NotarialDate']));
				$notarialDate = ($notarialDate=='01/01/1970') ? "" : $notarialDate;
				$nestedData[] = '<input value="'.$notarialDate.'" placeholder="mm/dd/yyyy" class="form-control text-right datepicker2" type="text"   name="notarial_date_'.$a.'" onchange="updateConversionDetails(this.value,\'notarial date\','.$result[$a]['Id'].')">'; 
 				
 				
 				$nestedData[] = (($result[$a]['TakeOut']=='1970-01-01') || ($result[$a]['TakeOut']=='')) ? "" : date('m/d/Y', strtotime($result[$a]['TakeOut']));
 				
 				$nestedData[]	= trim($result[$a]['Id']);
 				$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]['MiddleInitial']))));
 				$nestedData[]	= trim($result[$a]['Block']);
				$nestedData[]	= trim($result[$a]['Lot']); 
				
				  
			//get lot size data	
			$pricedate	= (($result[$a]['PricelistDate']=='1970-01-01') || ($result[$a]['PricelistDate']=='') || ($result[$a]['PricelistDate']==NULL)) ? "" : date('Y-m-d', strtotime($result[$a]['PricelistDate']));
			$phase		= html_entity_decode(stripslashes($result[$a]['Phase'])); 
			$block		= html_entity_decode(stripslashes($result[$a]['Block'])); 
			$lot		= html_entity_decode(stripslashes($result[$a]['Lot'])); 
			$project	= html_entity_decode(stripslashes($result[$a]['Project'])); 
			$models		= html_entity_decode(stripslashes($result[$a]['Model'])); 
			if($pricedate!='1970-01-01' || $pricedate!='' || $pricedate!=NULL){
				$other = $formClass->getOtherDetails($pricedate,$models,$project,$phase,$block,$lot);		
				$nestedData[] = $other['lot_size']; 
			}else{
				$nestedData[]	= ''; //LOT SIZE 
			 
			}


				  
 				$tct		  = trim($result[$a]['TCT']); 
				$nestedData[] = '<input value="'.$tct.'" placeholder="" class="form-control text-right" type="text" maxlength="15" name="tct_'.$a.'" onchange="updateConversionDetails(this.value,\'tct\','.$result[$a]['Id'].')">'; 

				$tdLandNo 	  = (!empty(trim($result[$a]['TDLandNo']))) ? 'L - '.substr(trim($result[$a]['TDLandNo']), -5) : "";
				$tdBldgNo	  = (!empty(trim($result[$a]['TDBldgNo']))) ? 'B - '.substr(trim($result[$a]['TDBldgNo']), -5) : "";
 				$nestedData[] =  $tdLandNo;
				$nestedData[] =  $tdBldgNo;

 				$lmvtd		  = (!empty(trim($result[$a]['LMVTD']))) ? number_format(trim($result[$a]['LMVTD']),2) : ""; 
				$nestedData[] = '<input value="'.$lmvtd.'" placeholder="" class="form-control text-right" type="text" name="lmvtd_'.$a.'" onchange="updateConversionDetails(this.value,\'lmvtd\','.$result[$a]['Id'].')" onblur="javascript:this.value=Comma(this.value);"  onkeypress="return isNumberKey(event);">'; 
  
				$zonalvalue	  = (!empty(trim($result[$a]['ZonalValue']))) ? number_format(trim($result[$a]['ZonalValue']),2) : "";

				$nestedData[] = '<input value="'.$zonalvalue.'" placeholder="" class="form-control text-right" type="text" name="zonalvalue_'.$a.'" onchange="updateConversionDetails(this.value,\'zonalvalue\','.$result[$a]['Id'].')" onblur="javascript:this.value=Comma(this.value);"  onkeypress="return isNumberKey(event);">'; 
 
				$bmvtd	  	  = (!empty(trim($result[$a]['BMVTD']))) ? number_format(trim($result[$a]['BMVTD']),2) : "";
				$nestedData[] = '<input value="'.$bmvtd.'" placeholder="" class="form-control text-right" type="text" name="bmvtd_'.$a.'" onchange="updateConversionDetails(this.value,\'bmvtd\','.$result[$a]['Id'].')" onblur="javascript:this.value=Comma(this.value);"  onkeypress="return isNumberKey(event);">'; 
 				
 				if(!empty($tdLandNo) && !empty($tdBldgNo)){
 					$combineTD = $tdLandNo.', '.$tdBldgNo;
 				}else if(!empty($tdLandNo) && empty($tdBldgNo)){
 					$combineTD = $tdLandNo;
 				}else if(empty($tdLandNo) && !empty($tdBldgNo)){
 					$combineTD = $tdBldgNo;
 				}else{
 					$combineTD = "";
 				}

 				$nestedData[] = $combineTD; //auto combine

 				$nestedData[] = (!empty(trim($result[$a]['ApprovedLoanable']))) ? number_format(trim($result[$a]['ApprovedLoanable']),2) : ""; 
 				$nestedData[] = trim($result[$a]['TinNo']);   

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