<?php
if(!isset($_SESSION)) 
{ 
session_start(); 
} 
if(!isset($_SESSION['is_login']) ){
header("location: login.php");
?>
<script>
window.location="login.php";
</script>
<?php
}

// $permission  = explode(',',$_SESSION['permission_id']);
// if(!in_array(19,$permission) && !in_array(1,$permission)  ){

// $op['is_success'] = false;
// $op['data'] 	  = "عذرا انت غير مخول للوصل الى هذه الصفحة";
// echo json_encode($op);
// exit;

// }

date_default_timezone_set($_SESSION['SYSTimezone']);

if (isset($_POST['type']) || isset($_GET['type'])){
		require("db_connect.php");

		if( isset($_GET['type']) && ($_GET['type'] == "load")){
			// DB table to use
			// show All products for specific category
			// $cond1 = isset($_GET['id'])? ' AND CW.withdraw_by='.$_GET['id']:'';
			$cond = isset($_GET['id'])? ' AND PY.customer_id_fk='.$_GET['id']:'';

			if(isset($_GET['branch_id']) && $_GET['branch_id'] !=0){ 
				// in term
				$cond = $cond . ' AND PY.branch_id_fk ='.$_GET['branch_id'];
			}
			
			// $cond = $cond1 . '  ' . $cond2;
			
			$table  =  '(
				SELECT
					payment_id,
					payment_number,
					pay_usd_rate,
					pay_currency,
					paid_amount,
					paid_date,
					payment_note,
					payment_transaction,
					invoice_id_fk,
					customer_id_fk,
					paper_number,
					saleman_id_fk,
					saleman_full_name,

					customer_full_name,
					(SELECT sum(paid_amount) FROM payments PY  WHERE is_deleted =0 AND payment_transaction ="Payment" '.$cond.') AS total_paid,
					(SELECT sum(paid_amount) FROM payments PY  WHERE is_deleted =0 AND payment_transaction ="Discount" '.$cond.') AS total_account_discount,
					(SELECT sum(paid_amount) FROM payments PY  WHERE is_deleted =0 AND payment_transaction ="Return" '.$cond.') AS total_returned
				FROM
					payments PY
					
					LEFT JOIN customer C ON (PY.customer_id_fk = C.customer_id )
					LEFT JOIN saleman S ON (PY.saleman_id_fk = S.saleman_id )
					
				WHERE
					( PY.is_deleted = 0 '.$cond.') 
			) AS ALLTBL';
			// Table's primary key
			//echo $table;
			$primaryKey = 'payment_id';
			$columns = array(
			    array( 'db' => 'payment_id', 'dt' => 0 ),

			    array( 'db' => 'customer_full_name', 'dt' => 1 ),
			    array( 'db' => 'payment_number', 'dt' => 2 ),
			    array( 'db' => 'paid_amount', 'dt' => 3 ),
			    array( 'db' => 'paid_date',   'dt' => 4 , 'formatter'=> function($d){
									return date('Y-m-d',strtotime($d));
									 } ),
			    array( 'db' => 'payment_transaction', 'dt' => 5 ),
			    array( 'db' => 'payment_note', 'dt' => 6 ),
			    array( 'db' => 'paper_number', 'dt' => 7 ),
			    array( 'db' => 'saleman_full_name', 'dt' => 8 ),
			    array( 'db' => 'total_paid', 'dt' => 9 ),
			    array( 'db' => 'total_account_discount', 'dt' => 10 ),
			    array( 'db' => 'total_returned', 'dt' => 11 ),
			    array( 'db' => 'customer_id_fk', 'dt' => 12 ),
			    array( 'db' => 'saleman_id_fk', 'dt' => 13 ),
			    
			   
			);
			// SQL server connection information
			$sql_details = array(
			    'user' => $mysql_user,
			    'pass' => $mysql_password,
			    'db'   => $mysql_db,
			    'host' => $mysql_server
			);
			require( 'ssp.php' );
			echo json_encode(
			    SSP::complex( $_GET, $sql_details, $table, $primaryKey, $columns ,null, '' )
			);
			exit;
		}

		

		if ($_POST['type']=="get_Staff") {

			// $user_id = $_POST['obj_id'];
			$op  = array('is_success'=>false, 'data' => array());

			$res = $db->query("SELECT * FROM staff WHERE is_deleted=0 ");
			if ($res) {
				
				$op['is_success'] = true;
				while ($row = $res->fetch_assoc()) {
				    // do what you need.
						$result['staff_id'] = $row['staff_id'];
						$result['full_name'] = $row['full_name'];
						array_push($op['data'],$result);
				}

				echo json_encode($op);
				exit;
			}else{
				$op['is_success'] = false;
				$op['data'] 	  	= "حصل خطأ: الرجاء اعادة تحميل الصفحة والمحاولة من جديد";
				echo json_encode($op);
				exit;
			}
		}

		
		if ($_POST['type']=="get_Customer") {

			// $user_id = $_POST['obj_id'];
			$op  = array('is_success'=>false, 'data' => array());

			$res = $db->query("SELECT * FROM customer WHERE is_deleted=0 ");
			if ($res) {
				
				$op['is_success'] = true;
				while ($row = $res->fetch_assoc()) {
				    // do what you need.
						$result['customer_id'] 			= $row['customer_id'];
						$result['customer_full_name'] 	= $row['customer_full_name'];
						array_push($op['data'],$result);
				}

				echo json_encode($op);
				exit;
			}else{
				$op['is_success'] = false;
				$op['data'] 	  	= "حصل خطأ: الرجاء اعادة تحميل الصفحة والمحاولة من جديد";
				echo json_encode($op);
				exit;
			}
		}


		if ($_POST['type'] == "update") {

			$id 				= $_POST['payment_id'];
			$customer_id_fk		=addslashes($_POST["customer_id_fk"]);
			$saleman_id			=addslashes($_POST["saleman_id"]);
			$paid_amount		=addslashes($_POST["paid_amount"]);
			$paid_date			=addslashes($_POST["paid_date"]);
			$payment_note		=addslashes($_POST["payment_note"]);
				
			$withdraw_currency			=1;
			$staff_customer				=0; // 0:customer; 1: staff
			
			$op  = array('is_success'=>false, 'data' => '');

					
			$reg_date 	= date("Y-m-d H:i:s", time());


			$lastaction = "Update Payment";
			$update_qry = "UPDATE payments SET  
								  paid_amount 	  = '$paid_amount',
								  paid_date       ='$paid_date',
								  payment_note    ='$payment_note',
								  customer_id_fk  ='$customer_id_fk' ,
								  saleman_id_fk   ='$saleman_id' ,
								  last_action     ='$lastaction',
								  last_action_by  ='".$_SESSION['user_id']."' 
							WHERE payment_id = $id";


			$res = $db->query($update_qry);
			if ($res) {

				$lastaction = "Updated Amount in Payment";
				$safe_note 	= "Update Payment ID : " . $id;


				$update_qry = "UPDATE safe SET 	safe_amount 	='$paid_amount',
										  		date_of_add 	='$paid_date',
										  		safe_note  		='$safe_note',	
										  		
											  	updated_at      ='$reg_date',
											  	last_action     ='$lastaction',
											  	last_action_by  ='".$_SESSION['user_id']."' 
									WHERE id_fk = $id AND table_name='payments'";


				$res2 = $db->query($update_qry);

				if($res2){

					$op['is_success'] = true;
					$op['data'] 	 	  = "تمت عملية التحديث بنجاح";
					echo json_encode($op);
					exit;

				}else{

					$op['is_success'] = false;
					$op['data'] 	  	= "حصل خطأ: الرجاء اعادة تحميل الصفحة والمحاولة من جديد";
					echo json_encode($op);
					exit;

				}

				
			}else{
				$op['is_success'] = false;
				$op['data'] 	  	= "حصل خطأ: الرجاء اعادة تحميل الصفحة والمحاولة من جديد";
				echo json_encode($op);
				exit;
			}
		}


		if ($_POST['type']=="delete") {

			$id			=addslashes($_POST["obj_id"]);

			$reg_date 	= date("Y-m-d H:i:s", time());
			$lastaction = "Delete Payment";

			$op  		= array('is_success'=>false, 'data' => '');

			

			

			$db->autocommit(FALSE); // to rollback insertion if update fail
			

	  		$res = $db->query("UPDATE payments SET 	is_deleted = 1 ,
	  												deleted_at = '$reg_date',
	  												last_action='$lastaction',
	  												last_action_by='".$_SESSION['user_id']."' 
	  								WHERE payment_id=$id");
	    	if ($res){

	    			

	    		$res2 = $db->query("UPDATE safe SET is_deleted 	= 1 ,
	  												deleted_at 		= '$reg_date',
	  												updated_at  	= '$reg_date',
	  												last_action 	= '$lastaction',
	  												last_action_by 	= '".$_SESSION['user_id']."'
	  										WHERE id_fk = $id AND table_name='payments'");

	    		if(!$res2){
	    			$db->rollback();
	      			$op['is_success'] = false;
					$op['data'] 	  = "حصل خطأ: الرجاء اعادة تحميل الصفحة والمحاولة من جديد";
					echo json_encode($op);
					exit;
	    		}


	    		$res2 = $db->query("SELECT 	invoice_id_fk, paid_amount	FROM payments_details PD
								 		
								 					WHERE PD.payment_id_fk='$id'   AND PD.is_deleted = 0");

				if ($res2) {
						
						while ($row = $res2->fetch_assoc()) {

							$invoice_id_fk = $row['invoice_id_fk'];
							$paid_amount   = $row['paid_amount'];


							$res3 = $db->query("SELECT 
							  
							 		 invoice_total_net_balance,

							  		 invoice_status,

							  		(SELECT sum(paid_amount) FROM payments_details IP WHERE IP.customer_id_fk = I.customer_id_fk AND IP.is_returned=0 AND IP.is_deleted =0 AND IP.payment_transaction ='Payment' AND IP.invoice_id_fk= I.invoice_id) AS total_paid

							FROM invoice I
						 		
						 	WHERE I.invoice_id='$invoice_id_fk'   AND I.is_deleted = 0");

							while ($row2 = $res3->fetch_assoc()) {

								if($row2['total_paid'] > $paid_amount){

									$invoice_status = 1;

								}else{

									$invoice_status = 0;


								}


								$sql ="UPDATE invoice SET   
												
											invoice_status 				= '$invoice_status',
											updated_at 					= '$reg_date', 
											last_action 				= '$lastaction', 
											last_action_by 				= '".$_SESSION['user_id']."'
									 		WHERE invoice_id = '$invoice_id_fk'";
						
								$resI = $db->query($sql);

								if(!$resI){
									$db->rollback();
									$op['is_success'] = false;
									$op['data'] 	  = "الرجاء قم بادخال دفعة واحدة على الاقل";
									echo json_encode($op);
									exit;
								}

							} // while


			

						}
				}else{

					$db->rollback();
	      			$op['is_success'] = false;
					$op['data'] 	  = "حصل خطأ: الرجاء اعادة تحميل الصفحة والمحاولة من جديد";
					echo json_encode($op);
					exit;

				}


	    				
							

	    			


	    			$res1 = $db->query("UPDATE payments_details SET 	
	    											is_deleted 		= 1 ,
	  												deleted_at 		= '$reg_date',
	  												last_action		='$lastaction',
	  												last_action_by  ='".$_SESSION['user_id']."' 
	  								WHERE payment_id_fk=$id");

	    			if ($res1){
						$db->commit();
		        		$op['is_success'] = true;
						$op['data'] 	  = "تمت عملية الحذف بنجاح";
						echo json_encode($op);
						exit;
					}
	     	}else{
					
					$db->rollback();
	      			$op['is_success'] = false;
					$op['data'] 	  = "حصل خطأ: الرجاء اعادة تحميل الصفحة والمحاولة من جديد";
					echo json_encode($op);
					exit;
	     	}
		}

		if ($_POST['type'] == "discount") {
	      		
	      		$customer_id_fk		=addslashes($_POST["customer_id_fk"]);
				$paid_amount		=addslashes($_POST["paid_amount"]);
				$paid_date			=addslashes($_POST["paid_date"]);
				$payment_note		=addslashes($_POST["payment_note"]);
				
				$pay_currency			=1;
				
			
				$delete = 0;
				if($paid_date =='' || $paid_date == NULL){
					$paid_date = date("Y-m-d", time());
				}

				$reg_date 				= date("Y-m-d h:i:s", time());
				$lastaction 			= "Add New Discount";
				
				$dd 	  				= date("y", time());
			
				$next_payment_date 		='';
				$next_payment_amount 	= '';


				$resP = $db->query("SELECT pay_sequence_no FROM payments ORDER BY payment_id DESC LIMIT 1");
				$rowP = $resP->fetch_assoc();
				$pay_sequence_no 	= $rowP['pay_sequence_no'] +1;

				
				$payment_number 		= "DSC".$dd.($pay_sequence_no);
				$payment_transaction 	= 'Discount';

				$sql_p ="INSERT INTO payments(payment_number,
		 									  pay_usd_rate,
		 									  pay_currency,
		 									  paid_amount,
		 									  paid_date,
		 									  payment_note,
		 									  payment_transaction,
		 									  pay_sequence_no,
		 									  invoice_id_fk,
		 									  customer_id_fk,
		 									  created_by,
		 									  last_action,
		 									  last_action_by)
		 							   VALUES('$payment_number',
		 							   		  '".$_SESSION['USD_TO_IQD']."',
		 							    	  '$pay_currency',
		 							    	  '$paid_amount',
		 							    	  '$paid_date',
		 							    	  '$payment_note',
		 							    	  '$payment_transaction',
		 							    	  '$pay_sequence_no',
		 							    	  '',
		 							    	  '$customer_id_fk',
		 							    	  '".$_SESSION['user_id']."',
		 							    	  '$lastaction',
		 							    	  '".$_SESSION['user_id']."')";
				$res_P = $db->query($sql_p);

				if ($res_P) {

						$op['is_success'] = true;
						$op['data'] 	  = "تمت عملية الاضافة بنجاح";
						echo json_encode($op);
						exit;
				}
				else{
							$op['is_success'] = false;
							$op['data'] 	  = "حصل خطأ: الرجاء اعادة تحميل الصفحة والمحاولة من جديد";
							echo json_encode($op);
							exit;
				}
			

		}


		if ($_POST['type'] == "return") {
	      		
	      		$customer_id_fk		=addslashes($_POST["customer_id_fk"]);
				$paid_amount		=addslashes($_POST["paid_amount"]);
				$paid_date			=addslashes($_POST["paid_date"]);
				$payment_note		=addslashes($_POST["payment_note"]);
				
				$pay_currency			=1;
				
			
				$delete = 0;
				if($paid_date =='' || $paid_date == NULL){
					$paid_date = date("Y-m-d", time());
				}

				$reg_date 				= date("Y-m-d h:i:s", time());
				$lastaction 			= "Add New Return Amount";
				
				$dd 	  				= date("y", time());
			
				$next_payment_date 		='';
				$next_payment_amount 	= '';


				$resP = $db->query("SELECT pay_sequence_no FROM payments ORDER BY payment_id DESC LIMIT 1");
				$rowP = $resP->fetch_assoc();
				$pay_sequence_no 	= $rowP['pay_sequence_no'] +1;

				
				$payment_number 		= "RTN".$dd.($pay_sequence_no);
				$payment_transaction 	= 'Return';

				$sql_p ="INSERT INTO payments(payment_number,
		 									  pay_usd_rate,
		 									  pay_currency,
		 									  paid_amount,
		 									  paid_date,
		 									  payment_note,
		 									  payment_transaction,
		 									  pay_sequence_no,
		 									  invoice_id_fk,
		 									  customer_id_fk,
		 									  created_by,
		 									  last_action,
		 									  last_action_by)
		 							   VALUES('$payment_number',
		 							   		  '".$_SESSION['USD_TO_IQD']."',
		 							    	  '$pay_currency',
		 							    	  '$paid_amount',
		 							    	  '$paid_date',
		 							    	  '$payment_note',
		 							    	  '$payment_transaction',
		 							    	  '$pay_sequence_no',
		 							    	  '',
		 							    	  '$customer_id_fk',
		 							    	  '".$_SESSION['user_id']."',
		 							    	  '$lastaction',
		 							    	  '".$_SESSION['user_id']."')";
				$res_P = $db->query($sql_p);

				if ($res_P) {

						$op['is_success'] = true;
						$op['data'] 	  = "تمت عملية الاضافة بنجاح";
						echo json_encode($op);
						exit;
				}
				else{
							$op['is_success'] = false;
							$op['data'] 	  = "حصل خطأ: الرجاء اعادة تحميل الصفحة والمحاولة من جديد";
							echo json_encode($op);
							exit;
				}
			

		}
	}
	else{
		header("Location:../");
		exit;
	}
?>
