<?php
error_reporting(0);
if (substr_count($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip')) ob_start("ob_gzhandler"); else ob_start();
session_start();
session_cache_limiter('private');
$cache_limiter 	= session_cache_limiter();
session_cache_expire(60);
$cache_expire 	= session_cache_expire(); 
date_default_timezone_set('Asia/Manila'); 
$CURRENT_DATE 	= date('Y-m-d H:i:s');
include_once('../config/minho.php');
include_once('../config/autoloadClass.php');
$autoload	=	new autoloadClass();
$mecon		=	new condbClass(); 
$mecon2		=	new condbClass(); //28may25
$utility	=	new utilityClass();

$mainArr2 = array(); //28may25
$condArr2 = array(); //28may25


$sactArr = array(); //28may25
if(isset($_POST['current_project']) && isset($_POST['current_model'])){
		$project		= isset($_POST['current_project']) ? str_replace('_',' ',htmlentities(addslashes(strip_tags(trim($_POST['current_project']))))) : ""; 
		$model			= isset($_POST['current_model']) 		? str_replace('_',' ',htmlentities(addslashes(strip_tags(trim($_POST['current_model']))))) : ""; 
		$remarks		= isset($_POST['pricelist_remarks']) 		? htmlentities(addslashes(trim($_POST['pricelist_remarks']))) : "";
		$updatedDate	= isset($_POST['pricelist_updated_date']) 	? trim($_POST['pricelist_updated_date']) : "";
		$reservationFee	= isset($_POST['pricelist_reservation_fee']) 	? str_replace(',','',$_POST['pricelist_reservation_fee']) : "";
		$task			= isset($_POST['action'])			? trim($_POST['action']) : "";
		$key_code		= isset($_POST['key_code'])			? trim($_POST['key_code']) : "";
		$mainid			= isset($_POST['mainid'])			? trim($_POST['mainid']) : "";
		$terms_discount	= isset($_POST['terms_discount'])	? strip_tags(str_replace(',','',trim($_POST['terms_discount']))) : "";
		$terms			= isset($_POST['terms'])			? strip_tags(trim($_POST['terms'])) : "";
		$cash_discount	= isset($_POST['cash_discount']) 	? strip_tags(str_replace(',','',trim($_POST['cash_discount']))) : "";
		
		
		
		$currentUser 	= $_SESSION['danvillee_username'];
		$timeStamp		= date('Y-m-d H:i:s');
		$detailsArr 	= array();
		 
		$pricelist_status	=	isset($_POST['pricelist_status']) 	? $_POST['pricelist_status'] : "";
		$phase				=	isset($_POST['phase']) 				? $_POST['phase'] 			: "";
		$block				=	isset($_POST['block']) 				? $_POST['block'] 			: "";
		$lot				=	isset($_POST['lot']) 				? $_POST['lot']			 	: "";
		$lot_size			=	isset($_POST['lot_size']) 			? $_POST['lot_size'] 		: "";
		$lot_type			=	isset($_POST['lot_type']) 			? $_POST['lot_type'] 		: "";
		$floor_area			=	isset($_POST['floor_area']) 		? $_POST['floor_area'] 		: "";
		//$selling_price		=	isset($_POST['selling_price']) 		? $_POST['selling_price'] 	: "";
		//$taxes				=	isset($_POST['taxes']) 				? $_POST['taxes'] 			: "";
		$contract_price		=	isset($_POST['contract_price']) 	? $_POST['contract_price'] 	: "";

		$discount_type		=	isset($_POST['discount_type']) 	? $_POST['discount_type'] 	: "";
		$discount_amount	=	isset($_POST['discount_amount']) 	? $_POST['discount_amount'] 	: "";
		$discount_tcp		=	isset($_POST['discount_tcp']) 	? $_POST['discount_tcp'] 	: "";
  
		$loanable_amount	=	isset($_POST['loanable_amount']) 	? $_POST['loanable_amount'] : "";
		$downpayment		=	isset($_POST['downpayment']) 		? $_POST['downpayment'] 	: "";
		$pf_net				=	isset($_POST['pf_net']) 			? $_POST['pf_net'] 			: "";
		$pf_payable			=	isset($_POST['pf_payable']) 		? $_POST['pf_payable'] 		: "";
		$required_gross		=	isset($_POST['required_gross']) 	? $_POST['required_gross'] 	: "";
		$amortization		=	isset($_POST['amortization']) 		? $_POST['amortization'] 	: "";
		$detail_terms		=	isset($_POST['detail_terms']) 		? $_POST['detail_terms'] 	: "";
		$discount_remarks		=	isset($_POST['remarks']) 	? $_POST['remarks'] 	: "";
		//SAVING PROMO TABLE DETAILS
		$ctrDetails	= count($phase); 
		if(!empty($_POST['phase'])){
		
		if($task=="create"):
			$pricelistId				=	$mecon->getNextId("Id","pricelist"); 
		elseif($task=="edit"): 
			$pricelistId				=	$mainid;
		endif;
			$b = 1;
			for($a=0; $a<$ctrDetails; $a++){
						$detailsArr[$a]['id'] 					= $b;
						$detailsArr[$a]['pricelist_status'] 	= $pricelist_status[$a];
						$detailsArr[$a]['detail_terms'] 		= str_replace(" ","",$detail_terms[$a]);
						$detailsArr[$a]['phase'] 				= $phase[$a];
						$detailsArr[$a]['block'] 				= $block[$a];
						$detailsArr[$a]['lot'] 					= $lot[$a];
						$detailsArr[$a]['lot_size'] 			= $lot_size[$a];
						$detailsArr[$a]['lot_type'] 			= $lot_type[$a];
						$detailsArr[$a]['floor_area'] 			= $floor_area[$a];
			//			$detailsArr[$a]['selling_price'] 		= $selling_price[$a];
			//			$detailsArr[$a]['taxes'] 				= $taxes[$a];
						$detailsArr[$a]['contract_price'] 		= str_replace(',','',trim($contract_price[$a])); //TCP 28may25


						$detailsArr[$a]['discount_type'] 		= $discount_type[$a];
						$detailsArr[$a]['discount_amount'] 		= str_replace(',','',trim($discount_amount[$a])); //DISCOUNT 28may25
						$detailsArr[$a]['discount_tcp'] 		= str_replace(',','',trim($discount_tcp[$a])); //TCP (Net of Discounts) 28may25

						

						
						
						$detailsArr[$a]['loanable_amount'] 		= str_replace(',','',trim($loanable_amount[$a])); //28may25
						$detailsArr[$a]['downpayment'] 			= str_replace(',','',trim($downpayment[$a])); 	//PDCDownpayment 28may25
						$detailsArr[$a]['pf_net'] 				= str_replace(',','',trim($pf_net[$a]));  		//NetEquity 28may25
						$detailsArr[$a]['pf_payable'] 			= str_replace(',','',trim($pf_payable[$a])); 	//MonthlyEquity / Equity Payable 28may25
						$detailsArr[$a]['required_gross'] 		= str_replace(',','',trim($required_gross[$a])); //28may25
						$detailsArr[$a]['amortization'] 		= str_replace(',','',trim($amortization[$a])); //28may25
						$detailsArr[$a]['remarks'] 				= $discount_remarks[$a];
						$detailsArr[$a]['pricelist_id'] 		= $pricelistId;
						

/*********************************************************************************************/ //28may25
							//CHECK IF THERE IS EXISTING RESERVATION AND RECORD IN BUYERS MONITORING FOLDER TO UPDATE THE AMOUNTS
			 	 		 	$pdate = date("Y-m-d", strtotime($updatedDate));
							$mecon->query("SELECT r.Id as Id FROM reservation r WHERE  r.Model = :model AND r.PricelistDate = :pdate AND r.Phase = :phase AND r.Block = :block AND r.Lot = :lot ORDER BY r.Id DESC");
							 
								$mecon->bind(':model', $model);
								$mecon->bind(':pdate', $pdate);
								$mecon->bind(':phase', $phase[$a]);
								$mecon->bind(':block', $block[$a]);
								$mecon->bind(':lot', $lot[$a]);
								$main2 		= $mecon->resultset(); 
								$ctr2 		= count($main2); 

								 
								if($ctr2>0){
								  		for($r=0; $r<$ctr2; $r++){ 
												$rId = $main2[$r]['Id']; 

												if($rId!=0){ 
															$mainArr2['UpdatedBy']			= $currentUser;
															$mainArr2['UpdatedDate']		= $timeStamp;
															 
															



															$mainArr2['TCP']						= str_replace(',','',trim($contract_price[$a]));
															$mainArr2['LoanableAmount']				= str_replace(',','',trim($loanable_amount[$a]));

															$mainArr2['NetEquity']					= str_replace(',','',trim($pf_net[$a]));

															$mainArr2['Discount']					= str_replace(',','',trim($discount_amount[$a]));
															
													//19OCT25 if terms is cash it will set to 1
															if(strtolower($detail_terms[$a])=="cash"){
																$mainArr2['TermsOfPayment']				= 1;
																$mainArr2['PaymentMode']				= "cash"; 
															}else{
																$mainArr2['TermsOfPayment']				= str_replace(',','',trim($detail_terms[$a]));	
																$mainArr2['PaymentMode']				= "installments"; 
															}
															
															
															$monthly_equity = str_replace(',','',trim($pf_net[$a])) / str_replace(',','',trim($detail_terms[$a]));

															$mainArr2['MonthlyEquity'] 			= str_replace(',','',trim($pf_payable[$a]));	
															 
															$mainArr2['PDCDownpayment']				= str_replace(',','',trim($downpayment[$a])); 
															$mainArr2['PagIbigLoanableAmount']		= str_replace(',','',trim($loanable_amount[$a])); 



 


															$condArr2['ReservationId']		= $rId;
															$output = $mecon->updateQuery($mainArr2,"buyer_payment_monitoring",$condArr2);
												} 
										 }
							 	}
/*********************************************************************************************/					
						


						$b++;
			}
		}
		$outputDetails 					= $detailsArr; 
		$resultDetailsArr 				= array();
		$resultDetailsArr['details']  	= $outputDetails;
		$pricelistTableDetails			= json_encode($resultDetailsArr);
				
		$mainArr						= array(); 
		$output 						= ""; 
		$mainArr['Project']				=	$project;
		$mainArr['Model']				=	$model; 
		$mainArr['PricelistDate']		=	date("Y-m-d", strtotime($updatedDate));
		$mainArr['ReservationFee']		=	$reservationFee;
		$mainArr['Remarks']				=	$remarks; 
		$mainArr['Terms']				=	$terms; 
		$mainArr['TermsDiscount']		=	$terms_discount; 
		$mainArr['CashDiscount']		=	$cash_discount; 
		$mainArr['KeyCode']				=	$key_code; 
		$mainArr['PricelistDetails']	=	$pricelistTableDetails;
		 
		$condArr = array();
		if($task=="create"):
			$mainArr['Id']				=	$mecon->getNextId("Id","pricelist");
			$mainArr['CreatedDate'] 	=	$timeStamp;
			$mainArr['CreatedBy'] 		=	$currentUser;
			$output = $mecon->insertSingleQuery($mainArr,"pricelist");
			
			//LOG TASK
			$actArr['UserType']			= "accountant,assistant_accountant";
			$actArr['Remarks']			= "Created New Pricelist : $updatedDate";
			$actArr['Action']			= "create";
			$actArr['ActionType']		= "pricelist";
			$actArr['ActionContent']	= json_encode($mainArr);
			$actArr['ActionBy'] 		= $currentUser;	
			$actArr['ActionDate']		= $timeStamp;
			$actArr['TransId']			= $pricelistId;
			$utility->encodeActivityLog($actArr);
		elseif($task=="edit"):
			$mainArr['UpdatedDate'] 	=	$timeStamp;
			$mainArr['UpdatedBy'] 		=	$currentUser;
			$condArr['Id']				=	$mainid;
			$output = $mecon->updateQuery($mainArr,"pricelist",$condArr);
			
			//LOG TASK
			/*$actArr['UserType']			= "accountant,assistant_accountant";
			$actArr['Remarks']			= "Updated Pricelist : $updatedDate";
			$actArr['Action']			= "edit";
			$actArr['ActionType']		= "pricelist";
			$actArr['ActionContent']	= json_encode($mainArr);
			$actArr['ActionBy'] 		= $currentUser;	
			$actArr['ActionDate']		= $timeStamp;
			$actArr['TransId']			= $pricelistId;
			$utility->encodeActivityLog($actArr);*/
		endif;

		$resultArr 						=	array();
		$resultArr['output']	  		=	$output;
		echo json_encode($resultArr);

}

/*
TCP - Discount = TCP (Net of Discount)

Loanable Amount
Downpayment

TCP (Net of Discount) - Loanable - Downpayment - Reservation Fee = Net Equity

Net Equity / Terms = Equity Payable
*/
exit();
ob_end_flush();