<?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']:'';
			
			$cond1 = isset($_GET['c'])? ' AND C.customer_type='.$_GET['c']:'';
			
			// $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,
					item_type_id_fk,
					item_name,
					invoice_type,
					customer_full_name,
					(SELECT sum(paid_amount) FROM payments PY  
						LEFT JOIN customer C ON (PY.customer_id_fk = C.customer_id)
						WHERE PY.is_deleted =0 AND payment_transaction ="Payment" '.$cond.' '.$cond1.') AS total_paid,
					(SELECT sum(paid_amount) FROM payments PY  
						LEFT JOIN customer C ON (PY.customer_id_fk = C.customer_id)
						WHERE PY.is_deleted =0 AND payment_transaction ="Discount" '.$cond.' '.$cond1.') AS total_account_discount,
					(SELECT sum(paid_amount) FROM payments PY  
						LEFT JOIN customer C ON (PY.customer_id_fk = C.customer_id)
						WHERE PY.is_deleted =0 AND payment_transaction ="Return" '.$cond.' '.$cond1.') AS total_returned
				FROM
					payments PY
					
					LEFT JOIN customer C ON (PY.customer_id_fk = C.customer_id )
					LEFT JOIN item_type IT ON (PY.item_type_id_fk = IT.item_type_id )
					
				WHERE
					( PY.is_deleted = 0 '.$cond.' '.$cond1.') 
			) 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' => 'item_name', 'dt' => 7 ),
			    array( 'db' => 'invoice_type', 'dt' => 8 ),
			    array( 'db' => 'item_type_id_fk', 'dt' => 9 ),
			    array( 'db' => 'total_paid', 'dt' => 10 ),
			    array( 'db' => 'total_account_discount', 'dt' => 11 ),
			    array( 'db' => 'total_returned', 'dt' => 12 ),
			    array( 'db' => 'customer_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"]);
			$paid_amount		=addslashes($_POST["paid_amount"]);
			$paid_date			=addslashes($_POST["paid_date"]);
			$payment_note		=addslashes($_POST["payment_note"]);
			$pay_type			=addslashes($_POST["pay_type"]);
			$item_type_id_fk	=addslashes($_POST["item_type_id_fk"]);
				
			$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' ,
								  invoice_type ='$pay_type' ,
								  item_type_id_fk='$item_type_id_fk' ,
								  updated_at='$reg_date',
								  last_action='$lastaction',
								  last_action_by='".$_SESSION['user_id']."' 
							WHERE payment_id = $id";


			$res = $db->query($update_qry);
			if ($res) {
					$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']=="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' => '');

			

			

			

	  		$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){
	        $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'] == "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',
		 							    	  '0',
		 							    	  '$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',
		 							    	  '0',
		 							    	  '$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;
	}
?>
