<?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']:'';
			$cond2 = isset($_GET['idc'])? ' AND CW.gived_to_id_fk='.$_GET['idc']:'';
			
			$cond = $cond1 . '  ' . $cond2;
			
			$table  =  '(
				SELECT
					capital_withdraw_id,
					withdraw_amount,
					withdraw_date,
					withdraw_by,
					for_company,
					withdraw_usd_rate,
					withdraw_currency,
					withdraw_status,
					withdraw_note,
					staff_customer,
					gived_to_id_fk,
					full_name,
					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 CWP WHERE  CWP.is_deleted = 0  ) AS total_paid
				FROM
					capital_withdraw CW
					LEFT JOIN staff S ON (CW.withdraw_by = S.staff_id )
					LEFT JOIN customer C ON (CW.gived_to_id_fk = C.customer_id )
					
				WHERE
					( CW.is_deleted = 0 '.$cond.') 
			) AS ALLTBL';
			// Table's primary key
			//echo $table;
			$primaryKey = 'capital_withdraw_id';
			$columns = array(
			    array( 'db' => 'capital_withdraw_id', 'dt' => 0 ),

			    array( 'db' => 'withdraw_amount', 'dt' => 1 ),
			    array( 'db' => 'withdraw_date',   'dt' => 2 , 'formatter'=> function($d){
									return date('Y-m-d',strtotime($d));
									 } ),
			    array( 'db' => 'full_name', 'dt' => 3 ),
			    array( 'db' => 'customer_full_name', 'dt' => 4 ),
			    array( 'db' => 'withdraw_status', 'dt' => 5 ),
			    array( 'db' => 'withdraw_note', 'dt' => 6 ),
			    array( 'db' => 'staff_customer', 'dt' => 7 ),
			    array( 'db' => 'withdraw_by', 'dt' => 8 ),
			    array( 'db' => 'gived_to_id_fk', 'dt' => 9 ),
			    array( 'db' => 'total_amount', 'dt' => 10 ),
			    array( 'db' => 'total_paid', 'dt' => 11 ),
			   
			);
			// 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'];
			$withdraw_by				=addslashes($_POST["withdraw_by"]);
			$gived_to_id_fk				=addslashes($_POST["gived_to_id_fk"]);
			$withdraw_amount			=addslashes($_POST["withdraw_amount"]);
			$withdraw_date				=addslashes($_POST["withdraw_date"]);
			$withdraw_note				=addslashes($_POST["withdraw_note"]);
			$withdraw_currency			=1;
			$staff_customer				=0; // 0:customer; 1: staff
			
			$op  = array('is_success'=>false, 'data' => '');

					


			$lastaction = "Update Capital_withdraw";
			$update_qry = "UPDATE capital_withdraw SET  withdraw_by = '$withdraw_by', gived_to_id_fk='$gived_to_id_fk',withdraw_amount='$withdraw_amount',	withdraw_date='$withdraw_date' ,	withdraw_note='$withdraw_note',withdraw_currency='$withdraw_currency',staff_customer='$staff_customer',
				last_action='$lastaction',last_action_by='".$_SESSION['user_id']."' WHERE capital_withdraw_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_withdraw";

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

			

			

			

	  		$res = $db->query("UPDATE capital_withdraw SET is_deleted = 1 ,deleted_at = '$reg_date',last_action='$lastaction',last_action_by='".$_SESSION['user_id']."' WHERE capital_withdraw_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") {
	      		
	      		$withdraw_by				=addslashes($_POST["withdraw_by"]);
				$gived_to_id_fk				=addslashes($_POST["gived_to_id_fk"]);
				$withdraw_amount			=addslashes($_POST["withdraw_amount"]);
				$withdraw_date				=addslashes($_POST["withdraw_date"]);
				$withdraw_note				=addslashes($_POST["withdraw_note"]);
				$withdraw_currency			=1;
				$staff_customer				=0; // 0:customer; 1: staff

			
				$delete = 0;
				if($withdraw_date =='' || $withdraw_date == NULL){
					$withdraw_date = date("Y-m-d", time());
				}

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

				$sql ="INSERT INTO capital_withdraw (withdraw_amount,
											withdraw_date,
											withdraw_by,
											withdraw_usd_rate,
											withdraw_currency,
											withdraw_note,
											staff_customer,
											gived_to_id_fk,
											created_by,
											last_action,
											last_action_by)
									VALUES( '$withdraw_amount',
											'$withdraw_date',
											'$withdraw_by',
											'".$_SESSION['USD_TO_IQD']."',
											'$withdraw_currency',
											'$withdraw_note',
											'$staff_customer',
											'$gived_to_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;
	}
?>
