<?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_amount,
					date_of_add,
					amount_owner_staff_id_fk,
					is_company,
					capital_usd_rate,
					capital_currency,
					capital_note,
					full_name,
					(SELECT sum(capital_amount) FROM capital  WHERE is_deleted =0) AS total_amount,
					((SELECT sum(expenses_quantity * expenses_unit_price / expenses_usd_rate)  FROM expenses  WHERE is_deleted =0 AND expenses_currency=0) 
					+ (SELECT sum(expenses_quantity * expenses_unit_price )  FROM expenses  WHERE is_deleted =0 AND expenses_currency=1)) AS total_expenses,
					(SELECT sum(withdraw_amount) FROM capital_withdraw  WHERE is_deleted =0) AS total_withdraw
				FROM
					capital Cap
					LEFT JOIN staff S ON (Cap.amount_owner_staff_id_fk = S.staff_id )
					
				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_amount', 'dt' => 1 ),
			    array( 'db' => 'date_of_add',   'dt' => 2 , 'formatter'=> function($d){
									return date('Y-m-d',strtotime($d));
									 } ),
			    array( 'db' => 'full_name', 'dt' => 3 ),
			    array( 'db' => 'capital_note', 'dt' => 4 ),
			    array( 'db' => 'amount_owner_staff_id_fk', 'dt' => 5 ),
			    array( 'db' => 'total_amount', 'dt' => 6 ),
			    array( 'db' => 'total_expenses', 'dt' => 7 ),
			    array( 'db' => 'total_withdraw', 'dt' => 8 ),
			   
			);
			// 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'] == "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'] == "create") {
	      		
	      		$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"]);
				$capital_currency			=1;
				

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

				$sql ="INSERT INTO capital (capital_amount,
											date_of_add,
											amount_owner_staff_id_fk,
											capital_note,
											capital_usd_rate,
											capital_currency,
											created_by,
											last_action,
											last_action_by)
									VALUES( '$capital_amount',
											'$date_of_add',
											'$amount_owner_staff_id_fk',
											'$capital_note',
											'".$_SESSION['USD_TO_IQD']."',
											'$capital_currency',
											'".$_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;
	}
?>
