<?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.supplier_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,
					purchase_id_fk,
					PY.supplier_id_fk,
					paper_number,
					purchase_number,
					purchase_auto_number,
					supplier_full_name,
					(SELECT sum(paid_amount) FROM supplier_payments PY  WHERE is_deleted =0 AND payment_transaction ="Payment" '.$cond.') AS total_paid,

					(SELECT sum(cost_expenses * purchase_quantity ) 

							FROM purchase_item PP
								 		
					 	 	LEFT JOIN purchase PY ON (PP.purchase_id_fk = PY.purchase_id)

							WHERE PP.purchase_id_fk = PY.purchase_id AND PY.is_deleted = 0 AND PY.purchase_transaction="Purchase" '.$cond.') as total_purchase
					
				FROM
					supplier_payments PY
					
					LEFT JOIN suppliers S ON (PY.supplier_id_fk = S.supplier_id )
					LEFT JOIN purchase P ON (PY.purchase_id_fk = P.purchase_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' => 'supplier_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' => 'purchase_auto_number', 'dt' => 7 ),
			    array( 'db' => 'total_paid', 'dt' => 8 ),
			    array( 'db' => 'supplier_id_fk', 'dt' => 9 ),
			    array( 'db' => 'total_purchase', 'dt' => 10 ),
			    
			   
			);
			// 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']=="add_payments") {

			$supplier_id_fk    	= $_POST['cust_id'];
			$purchase_id_fk 	= 0; // $_POST['inv_id'];
			$total_paid 		= $_POST['row_payments'];
			$notes 				= $_POST['notes'];
			$paper_no 			= ''; // $_POST['paper_number'];
			$branch_id_fk 		= $_POST['branch_id_fk'];
			// $branch_id_fk 		= 0;

			$lastaction 		= "Add New Supplier Payment";
			$invoice_currency	= 1; //USD

			if(!isset($_POST['paid_date'])){
				$reg_date = date("Y-m-d H:i:s", time());
			}else{
				$reg_date = $_POST['paid_date'];
			}
			
			$dd 	  = date("y", time());
			
			$next_payment_date 		='';
			$next_payment_amount 	= '';



			$successfully = false;

			for ($i=0;$i<count($total_paid);$i++){

				if($total_paid[$i] > 0){

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

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

				
						$payment_number 		= "SPAY".$dd.($pay_sequence_no);
						$payment_transaction 	= 'Payment';
						$payment_note 			= $notes[$i];


					
						
						if($payment_note ==""){
							$payment_note = "Add Supplier Payment for Supplier ID: ".$supplier_id_fk;
						}


						$sql_p ="INSERT INTO supplier_payments(
													  payment_number,
													  paper_number,
				 									  pay_usd_rate,
				 									  pay_currency,
				 									  paid_amount,
				 									  paid_date,
				 									  payment_note,
				 									  payment_transaction,
				 									  pay_sequence_no,
				 									  supplier_id_fk,
				 									  purchase_id_fk,
				 									  branch_id_fk,
				 									  created_by,
				 									  last_action,
				 									  last_action_by)
				 							   VALUES('$payment_number',
				 							   		  '$paper_no',
				 							   		  '".$_SESSION['USD_TO_IQD']."',
				 							    	  '$invoice_currency',
				 							    	  '$total_paid[$i]',
				 							    	  '$reg_date',
				 							    	  '$payment_note',
				 							    	  '$payment_transaction',
				 							    	  '$pay_sequence_no',
				 							    	  '$supplier_id_fk',
				 							    	  '$purchase_id_fk',
				 							    	  '$branch_id_fk',
				 							    	  '".$_SESSION['user_id']."',
				 							    	  '$lastaction',
				 							    	  '".$_SESSION['user_id']."')";
						


						$res_P = $db->query($sql_p);

						if ($res_P){
							$last_inserted_payment_id = $db->insert_id;


						

							$res = $db->query("SELECT * FROM safe  ORDER BY safe_id DESC LIMIT 1");
							$row = $res->fetch_assoc();
							$safe_sequence_no 	= $row['safe_sequence_no'] +1;

							$dd = date("y", time());
							$safe_number = "SP".$dd.($safe_sequence_no);

							// Upadte purchase_sequence_no

							$safe_transaction = "Purchase";
							$transaction_type = "2";  // 1: add ; 2:subtract;
						
							

							$reg_date 	= date("Y-m-d H:i:s", time());
							$lastaction = "Add New Supplier Payment";
							$safe_note 	= "Add New Supplier Payment  ID : " . $last_inserted_payment_id;

							$sql1 ="INSERT INTO safe 
											   (safe_number,
												safe_amount,
												date_of_add,
												safe_transaction,
												transaction_type,
												capital_usd_rate,
												capital_currency,
												table_name,
												id_fk,
												safe_sequence_no,
												safe_note,
												staff_id_fk,
												branch_id_fk,
												created_by,
												created_at,
											    updated_at,
												last_action,
												last_action_by)
										VALUES( '$safe_number',
												'$total_paid[$i]',
												'$reg_date',
												'$safe_transaction',
												'$transaction_type',
												'".$_SESSION['USD_TO_IQD']."',
												'$invoice_currency',
												'supplier_payments',
												'$last_inserted_payment_id',
												'$safe_sequence_no',
												'$safe_note',
												'".$_SESSION['user_id']."',
												'$branch_id_fk',
												'".$_SESSION['user_id']."',
												'$reg_date',
												'$reg_date',
												'$lastaction',
												'".$_SESSION['user_id']."')";

							$res1 = $db->query($sql1);

							if(!$res1){

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


					
						$successfully = true;
						
				} // if total_paid >0

			}  // for i

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

				
				$db->commit();
				$op['is_success'] = true;
				$op['data'] 	  = "تمت عملية الاضافة بنجاح";
				echo json_encode($op);
				exit;
			}
		}


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

			$id 				= $_POST['payment_id'];
			$supplier_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"]);
				
			$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 Supplier Payment";
			$update_qry = "UPDATE supplier_payments SET  
								  paid_amount 	  = '$paid_amount',
								  paid_date       ='$paid_date',
								  payment_note    ='$payment_note',
								  supplier_id_fk  ='$supplier_id_fk' ,
								  last_action     ='$lastaction',
								  last_action_by  ='".$_SESSION['user_id']."' 
							WHERE payment_id = $id";


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

				$lastaction = "Updated Amount in Supplier Payment";
				$safe_note 	= "Update Supplier 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='supplier_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 supplier_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='supplier_payments'");

    			if ($res2){
					$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;
				}

	     	}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;
	}
?>
