<?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 CWP.payment_gived_to_id_fk='.$_GET['id']:'';
			
			// $cond = $cond1 . '  ' . $cond2;
			
			$table  =  '(
				SELECT
					capital_withdraw_payment_id,
					payment_withdraw_amount,
					payment_withdraw_date,
					payment_withdraw_usd_rate,
					payment_withdraw_currency,
					payment_withdraw_note,
					payment_gived_to_id_fk,
					
					customer_full_name,
					(SELECT sum(withdraw_amount) FROM capital_withdraw  WHERE is_deleted =0) AS total_amount,
					(SELECT sum(payment_withdraw_amount) FROM capital_withdraw_payments CWP1 WHERE  CWP1.is_deleted = 0  ) AS total_paid
				FROM
					capital_withdraw_payments CWP
					
					LEFT JOIN customer C ON (CWP.payment_gived_to_id_fk = C.customer_id )
					
				WHERE
					( CWP.is_deleted = 0 '.$cond.') 
			) AS ALLTBL';
			// Table's primary key
			//echo $table;
			$primaryKey = 'capital_withdraw_payment_id';
			$columns = array(
			    array( 'db' => 'capital_withdraw_payment_id', 'dt' => 0 ),

			    array( 'db' => 'customer_full_name', 'dt' => 1 ),
			    array( 'db' => 'payment_withdraw_amount', 'dt' => 2 ),
			    array( 'db' => 'payment_withdraw_date',   'dt' => 3 , 'formatter'=> function($d){
									return date('Y-m-d',strtotime($d));
									 } ),
			    array( 'db' => 'payment_withdraw_note', 'dt' => 4 ),
			    array( 'db' => 'payment_gived_to_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'];
			$payment_gived_to_id_fk		=addslashes($_POST["payment_gived_to_id_fk"]);
			$payment_withdraw_amount	=addslashes($_POST["payment_withdraw_amount"]);
			$payment_withdraw_date		=addslashes($_POST["payment_withdraw_date"]);
			$payment_withdraw_note		=addslashes($_POST["payment_withdraw_note"]);
				
			$withdraw_currency			=1;
			$staff_customer				=0; // 0:customer; 1: staff
			
			$op  = array('is_success'=>false, 'data' => '');

					


			$lastaction = "Update Capital_Payment";
			$update_qry = "UPDATE capital_withdraw_payments SET  payment_gived_to_id_fk = '$payment_gived_to_id_fk', payment_withdraw_amount='$payment_withdraw_amount',payment_withdraw_date='$payment_withdraw_date',	payment_withdraw_note='$payment_withdraw_note' ,payment_withdraw_currency='$withdraw_currency',
				last_action='$lastaction',last_action_by='".$_SESSION['user_id']."' WHERE capital_withdraw_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 Capital_Payment";

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

			

			

			

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

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

				$sql ="INSERT INTO capital_withdraw_payments (payment_withdraw_amount,
											payment_withdraw_date,
											payment_withdraw_usd_rate,
											payment_withdraw_currency,
											payment_withdraw_note,
											payment_gived_to_id_fk,
											group_no,
											created_by,
											last_action,
											last_action_by)
									VALUES( '$payment_withdraw_amount',
											'$payment_withdraw_date',
											'".$_SESSION['USD_TO_IQD']."',
											'$withdraw_currency',
											'$payment_withdraw_note',
											'$payment_gived_to_id_fk',
											'$rnd_no',
											'".$_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;
	}
?>
