<?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
			$cond = isset($_GET['id'])? ' AND CAP.amount_owner_staff_id_fk='.$_GET['id']:'';
			$table  =  ' (
				SELECT
					capital_id,
					capital_number,
					capital_amount,
					date_of_add,
					amount_owner_staff_id_fk,
					is_approved,
					approved_by,
					capital_usd_rate,
					capital_currency,
					capital_note,
					CAP.updated_at,
					CAP.last_action_by,
					S.full_name,
					S1.full_name AS approved_by_name,
					S2.full_name AS last_update_by,
					capital_transaction,

					is_accepted,
					accepted_by,
					S3.full_name AS acceptance_name,

					(SELECT sum(capital_amount) FROM capital  WHERE is_deleted =0 AND capital_transaction="Transfer to Factory") AS total_amount,

					(SELECT sum(capital_amount) FROM capital  WHERE is_deleted =0 AND is_approved=1 AND capital_transaction="Transfer to Factory") AS total_approved,

					(SELECT sum(capital_amount) FROM capital  WHERE is_deleted =0 AND is_approved=0 AND capital_transaction="Transfer to Factory") AS total_not_approved
					
				FROM
					capital CAP
					LEFT JOIN staff S ON (CAP.amount_owner_staff_id_fk = S.staff_id )
					LEFT JOIN staff S1 ON (CAP.approved_by = S1.staff_id )
					LEFT JOIN staff S2 ON (CAP.last_action_by = S2.staff_id )
					LEFT JOIN staff S3 ON (CAP.accepted_by = S3.staff_id )
					
				WHERE
					( CAP.is_deleted = 0 AND (CAP.capital_transaction="Transfer to Factory" OR CAP.capital_transaction="Request Transfer") '.$cond.') 
			)  AS ALLTBL';
			// Table's primary key
			//echo $table;
			$primaryKey = 'capital_id';
			$columns = array(
			    array( 'db' => 'capital_id', 'dt' => 0 ),

			    array( 'db' => 'capital_number', 'dt' => 1 ),
			    array( 'db' => 'capital_amount', 'dt' => 2 ),
			    array( 'db' => 'date_of_add',   'dt' => 3 , 'formatter'=> function($d){
									return date('Y-m-d',strtotime($d));
									 } ),
			    array( 'db' => 'full_name', 'dt' => 4 ),
			    array( 'db' => 'is_approved', 'dt' => 5 ),
			    array( 'db' => 'approved_by_name', 'dt' => 6 ),
			    array( 'db' => 'capital_note', 'dt' => 7 ),
			    array( 'db' => 'updated_at', 'dt' => 8 ),
			    array( 'db' => 'last_update_by', 'dt' => 9 ),
			    array( 'db' => 'total_amount', 'dt' => 10 ),
			    array( 'db' => 'total_approved', 'dt' => 11 ),
			    array( 'db' => 'total_not_approved', 'dt' => 12 ),
			    array( 'db' => 'is_accepted', 'dt' => 13 ),
			    array( 'db' => 'acceptance_name', 'dt' => 14 ),
			    array( 'db' => 'capital_transaction', 'dt' => 15 ),
			    array( 'db' => 'amount_owner_staff_id_fk', 'dt' => 16 ),

			   
			);
			// 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']=="approve_recieve") {

			$id=addslashes($_POST["obj_id"]);
			$reg_date = date("Y-m-d h:i:s", time());
			$lastaction = "Approve Recieving Money";

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

			

	  		$res = $db->query("UPDATE capital SET is_approved = 1 ,
	  													  approved_by = '".$_SESSION['user_id']."',
	  													  updated_at = '$reg_date',
	  													  last_action='$lastaction',
	  													  last_action_by='".$_SESSION['user_id']."' 
	  									WHERE capital_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'] == "update") {

			$id 						= $_POST['obj_id'];
			$amount_owner_staff_id_fk	=addslashes($_POST["amount_owner_staff_id_fk"]);
			$date_of_add				=addslashes($_POST["date_of_add"]);
			$capital_amount				=addslashes($_POST["capital_amount"]);
			$capital_note				=addslashes($_POST["capital_note"]);
			
			$op  = array('is_success'=>false, 'data' => '');

					


			$lastaction = "Update Capital";
			$update_qry = "UPDATE capital SET  amount_owner_staff_id_fk = '$amount_owner_staff_id_fk', date_of_add='$date_of_add',capital_amount='$capital_amount',	capital_note='$capital_note',
				last_action='$lastaction',last_action_by='".$_SESSION['user_id']."' WHERE capital_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";

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

			

			

			

	  		$res = $db->query("UPDATE capital SET is_deleted = 1 ,deleted_at = '$reg_date',last_action='$lastaction',last_action_by='".$_SESSION['user_id']."' WHERE capital_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'] == "request") {
	      		
	      		$amount_owner_staff_id_fk	=addslashes($_POST["staff_name"]);
				$date_of_add				=addslashes($_POST["factory_date_of_add"]);
				$capital_amount				=addslashes($_POST["transfer_amount"]);
				$capital_note				=addslashes($_POST["transfer_note"]);
				$capital_currency			=1;
				

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

				$dd = date("y", time());
				$capital_number = "REQ".$dd.($capital_sequence_no);

				// Upadte purchase_sequence_no

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

				$reg_date = date("Y-m-d h:i:s", time());
				$lastaction = "Request Transfer New Amount to Factory Capital";

				$sql ="INSERT INTO capital (capital_number,
											capital_amount,
											date_of_add,
											amount_owner_staff_id_fk,
											capital_note,
											capital_usd_rate,
											capital_currency,
											capital_transaction,
											capital_sequence_no,
											is_approved,
											is_accepted,
											created_by,
											created_at,
											updated_at,
											last_action,
											last_action_by)
									VALUES( '$capital_number',
											'$capital_amount',
											'$date_of_add',
											'$amount_owner_staff_id_fk',
											'$capital_note',
											'".$_SESSION['USD_TO_IQD']."',
											'$capital_currency',
											'$capital_transaction',
											'$capital_sequence_no',
											'0',
											'0',
											'".$_SESSION['user_id']."',
											'$reg_date',
											'$reg_date',
											'$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;
				}
			

		}

		if ($_POST['type'] == "create") {
	      		
	      		$amount_owner_staff_id_fk	=addslashes($_POST["staff_name"]);
				$date_of_add				=addslashes($_POST["factory_date_of_add"]);
				$capital_amount				=addslashes($_POST["transfer_amount"]);
				$capital_note				=addslashes($_POST["transfer_note"]);
				$capital_currency			=1;
				

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

				$dd = date("y", time());
				$capital_number = "TRNS".$dd.($capital_sequence_no);

				// Upadte purchase_sequence_no

				$capital_transaction = "Transfer to Factory";
			
				$delete = 0;
				if($date_of_add =='' || $date_of_add == NULL){
					$date_of_add = date("Y-m-d", time());
				}

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

				$sql ="INSERT INTO capital (capital_number,
											capital_amount,
											date_of_add,
											amount_owner_staff_id_fk,
											capital_note,
											capital_usd_rate,
											capital_currency,
											capital_transaction,
											capital_sequence_no,
											is_approved,
											created_by,
											created_at,
											updated_at,
											last_action,
											last_action_by)
									VALUES( '$capital_number',
											'$capital_amount',
											'$date_of_add',
											'$amount_owner_staff_id_fk',
											'$capital_note',
											'".$_SESSION['USD_TO_IQD']."',
											'$capital_currency',
											'$capital_transaction',
											'$capital_sequence_no',
											'0',
											'".$_SESSION['user_id']."',
											'$reg_date',
											'$reg_date',
											'$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;
	}
?>
