<?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.staff_id_fk='.$_GET['id']:'';
			$table  =  '(
				SELECT
					Cap.capital_id,
					Cap.capital_number,
					Cap.capital_amount,
					Cap.date_of_add,
					Cap.staff_id_fk,
					
					Cap.capital_usd_rate,
					Cap.capital_currency,
					Cap.capital_note,
					O.owner_full_name,
					S.branch_id_fk,
					Cap.capital_transaction,
					(SELECT sum(capital_amount) FROM capital Cap  WHERE Cap.is_deleted =0 AND Cap.capital_transaction="Add Capital Amount" '.$cond.') AS total_amount,

					(SELECT sum(safe_amount) FROM safe Cap  WHERE Cap.is_deleted =0 AND Cap.safe_transaction="Withdraw" '.$cond.') AS total_withdraw


				FROM
					capital Cap
					LEFT JOIN owner O ON (Cap.staff_id_fk = O.owner_id )
					LEFT JOIN safe S ON (Cap.capital_id = S.id_fk AND S.table_name="capital" )
					
					
				WHERE
					( Cap.is_deleted = 0 '.$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' => 'owner_full_name', 'dt' => 4 ),
			    array( 'db' => 'capital_transaction', 'dt' => 5 ),
			    array( 'db' => 'capital_note', 'dt' => 6 ),
			    array( 'db' => 'staff_id_fk', 'dt' => 7 ),
			    array( 'db' => 'total_amount', 'dt' => 8 ),
			    array( 'db' => 'total_withdraw', 'dt' => 9 ),
			    array( 'db' => 'branch_id_fk', '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']=="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']=="accepted") {

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

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

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

	  		$res = $db->query("UPDATE capital SET is_accepted = 1 ,
	  													  accepted_by = '".$_SESSION['user_id']."',
	  													  updated_at = '$reg_date',
	  													  last_action='$lastaction',
	  													  last_action_by='".$_SESSION['user_id']."' 
	  									WHERE capital_id=$id");
	    	if ($res){

	    		$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";

				$res1 = $db->query("SELECT * FROM capital  WHERE capital_id= '$id'");
				$row1 = $res1->fetch_assoc();
				
				$amount_owner_staff_id_fk	= 	$_SESSION['user_id'];
				
				$capital_amount				=	$row1['capital_amount'];
				$capital_note				=	$row1['capital_note'];
				$capital_currency			=1;


				$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";

				$sql2 ="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']."')";

				$res2 = $db->query($sql2);

				if ($res2) {
					$db->commit();

					$op['is_success'] = true;
					// $op['data'] 	  = "تمت عملية الاضافة بنجاح";
					$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']=="rejected") {

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

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

			

	  		$res = $db->query("UPDATE capital SET is_accepted = 2 ,
	  													  accepted_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'];
			$staff_id_fk				=addslashes($_POST["staff_id_fk"]);
			$date_of_add				=addslashes($_POST["date_of_add"]);
			$capital_amount				=addslashes($_POST["capital_amount"]);
			$capital_note				=addslashes($_POST["capital_note"]);
			$branch_id					=addslashes($_POST["branch_id"]);
			
			$op  = array('is_success'=>false, 'data' => '');

					
			$reg_date = date("Y-m-d H:i:s", time());

			$lastaction = "Update Capital";

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

			$update_qry = "UPDATE capital SET staff_id_fk='$staff_id_fk',
											  date_of_add='$date_of_add',
											  capital_amount='$capital_amount',	
											  capital_note='$capital_note',
											  updated_at='$reg_date',
											  last_action='$lastaction',
											  last_action_by='".$_SESSION['user_id']."' 
										WHERE capital_id = $id";


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

				$lastaction = "Updated Amount in Capital";
				$safe_note 	= "Update added Amount to Capital By : " . $staff_id_fk;


				$update_qry = "UPDATE safe SET 	safe_amount 	='$capital_amount',
										  		date_of_add 	='$date_of_add',
										  		safe_note  		='$safe_note',	
										 		staff_id_fk 	='$staff_id_fk',
										  		branch_id_fk 	='$branch_id',
											  	updated_at      ='$reg_date',
											  	last_action     ='$lastaction',
											  	last_action_by  ='".$_SESSION['user_id']."' 
									WHERE id_fk = $id AND table_name='capital'";


				$res2 = $db->query($update_qry);

				if($res2){

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

				}else{

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

				}

					
			}else{
				$db->rollback();
				$op['is_success'] = false;
				$op['data'] 	  	= "2حصل خطأ: الرجاء اعادة تحميل الصفحة والمحاولة من جديد";
				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' => '');


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

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

	    		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'] == "withdraw") {
	      		
	      		$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 = "WD".$dd.($capital_sequence_no);

				// Upadte purchase_sequence_no

				$capital_transaction = "Withdraw";
			
				$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 = "Withdraw amount from 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;
				}
			

		}


		if ($_POST['type'] == "profit") {
	      		
	      		$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 = "PF".$dd.($capital_sequence_no);

				// Upadte purchase_sequence_no

				$capital_transaction = "Profit";
			
				$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 = "Profit amount added to 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;
				}
			

		}

		if ($_POST['type'] == "create") {
	      		
	      		$staff_id_fk				=addslashes($_POST["staff_id_fk"]);
				$date_of_add				=addslashes($_POST["date_of_add"]);
				$capital_amount				=addslashes($_POST["capital_amount"]);
				$capital_note				=addslashes($_POST["capital_note"]);
				$branch_id					=addslashes($_POST["branch_id"]);

				$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 = "CAP".$dd.($capital_sequence_no);

				// Upadte purchase_sequence_no

				$capital_transaction = "Add Capital Amount";
			
				$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 = "Add New Amount to Capital";

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


				$sql ="INSERT INTO capital (capital_number,
											capital_amount,
											date_of_add,
											staff_id_fk,
											capital_note,
											capital_usd_rate,
											capital_currency,
											capital_transaction,
											capital_sequence_no,
											created_by,
											created_at,
										    updated_at,
											last_action,
											last_action_by)
									VALUES( '$capital_number',
											'$capital_amount',
											'$date_of_add',
											'$staff_id_fk',
											'$capital_note',
											'".$_SESSION['USD_TO_IQD']."',
											'$capital_currency',
											'$capital_transaction',
											'$capital_sequence_no',
											'".$_SESSION['user_id']."',
											'$reg_date',
											'$reg_date',
											'$lastaction',
											'".$_SESSION['user_id']."')";

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

				if ($res) {

						$inserted_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 = "CAP".$dd.($safe_sequence_no);

						// Upadte purchase_sequence_no

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

						$reg_date 	= date("Y-m-d h:i:s", time());
						$lastaction = "Add New Amount to Capital";
						$safe_note 	= "Add New Amount to Capital By : " . $staff_id_fk;

						$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',
											'$capital_amount',
											'$date_of_add',
											'$safe_transaction',
											'$transaction_type',
											'".$_SESSION['USD_TO_IQD']."',
											'$capital_currency',
											'capital',
											'$inserted_id',
											'$safe_sequence_no',
											'$safe_note',
											'$staff_id_fk',
											'$branch_id',
											'".$_SESSION['user_id']."',
											'$reg_date',
											'$reg_date',
											'$lastaction',
											'".$_SESSION['user_id']."')";

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

						if($res1){

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

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