<?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 SP.supplier_id_fk='.$_GET['id']:'';
			$cond1 = isset($_GET['id'])? ' AND P.supplier_id_fk='.$_GET['id']:'';
			
			// $cond = $cond1 . '  ' . $cond2;
			
			$table  =  '(
				SELECT
					supplier_payment_id,
					payment_amount,
					payment_date,
					payment_usd_rate,
					payment_currency,
					payment_note,
					supplier_id_fk,
					
					supplier_full_name,
					(SELECT sum(buy_price_per_meter * item_length) FROM
					 	 purchase P  , purchase_item PP, purchase_item_detail PID 
					WHERE 
					(PP.purchase_id_fk = P.purchase_id AND P.is_deleted = 0 AND PP.is_deleted = 0 AND PID.purchase_item_id_fk = PP.purchase_item_id AND PID.is_deleted = 0  '.$cond1.')

					) AS total_amount,
					(SELECT sum(payment_amount) FROM supplier_payments SP WHERE  SP.is_deleted = 0  '.$cond.') AS total_paid
				FROM
					supplier_payments SP
					
					LEFT JOIN suppliers SU ON (SP.supplier_id_fk = SU.supplier_id )
					
				WHERE
					( SP.is_deleted = 0 '.$cond.') 
			) AS ALLTBL';
			// Table's primary key
			//echo $table;
			$primaryKey = 'supplier_payment_id';
			$columns = array(
			    array( 'db' => 'supplier_payment_id', 'dt' => 0 ),

			    array( 'db' => 'supplier_full_name', 'dt' => 1 ),
			    array( 'db' => 'payment_amount', 'dt' => 2 ),
			    array( 'db' => 'payment_date',   'dt' => 3 , 'formatter'=> function($d){
									return date('Y-m-d',strtotime($d));
									 } ),
			    array( 'db' => 'payment_note', 'dt' => 4 ),
			    array( 'db' => 'supplier_id_fk', 'dt' => 5 ),
			    array( 'db' => 'total_amount', 'dt' => 6 ),
			    array( 'db' => 'total_paid', 'dt' => 7 ),
			    
			   
			);
			// 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 AND customer_type =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['obj_id'];
			$supplier_id_fk		=addslashes($_POST["supplier_id_fk"]);
			$payment_amount		=addslashes($_POST["payment_amount"]);
			$payment_date		=addslashes($_POST["payment_date"]);
			$payment_note		=addslashes($_POST["payment_note"]);
				
			$withdraw_currency			=1;
			$staff_customer				=0; // 0:customer; 1: staff
			
			$op  = array('is_success'=>false, 'data' => '');

					


			$lastaction = "Update Supplier Payment";
			$update_qry = "UPDATE supplier_payments SET  supplier_id_fk = '$supplier_id_fk', payment_amount='$payment_amount',payment_date='$payment_date',	payment_note='$payment_note' ,payment_currency='$withdraw_currency',
				last_action='$lastaction',last_action_by='".$_SESSION['user_id']."' WHERE supplier_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 Supplier Payment";

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

			

			

			

	  		$res = $db->query("UPDATE supplier_payments SET is_deleted = 1 ,deleted_at = '$reg_date',last_action='$lastaction',last_action_by='".$_SESSION['user_id']."' WHERE supplier_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'] == "create") {
	      		
	      		$supplier_id_fk		=addslashes($_POST["supplier_id_fk"]);
				$payment_amount		=addslashes($_POST["payment_amount"]);
				$payment_date		=addslashes($_POST["payment_date"]);
				$payment_note		=addslashes($_POST["payment_note"]);
				
				$withdraw_currency			=1;
				
				$rnd_no						=rand(100000000,1000000000).uniqid();
			
				$delete = 0;
				if($payment_date =='' || $payment_date == NULL){
					$payment_date = date("Y-m-d", time());
				}

				$reg_date = date("Y-m-d h:i:s", time());
				$lastaction = "Add New Payment to Supplier";

				$sql ="INSERT INTO supplier_payments (payment_amount,
											payment_date,
											payment_usd_rate,
											payment_currency,
											payment_note,
											supplier_id_fk,
											created_by,
											last_action,
											last_action_by)
									VALUES( '$payment_amount',
											'$payment_date',
											'".$_SESSION['USD_TO_IQD']."',
											'$withdraw_currency',
											'$payment_note',
											'$supplier_id_fk',
											'".$_SESSION['user_id']."',
											'$lastaction',
											'".$_SESSION['user_id']."')";

				$res = $db->query($sql);

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

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