<?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_once "db_connect.php";

		if( isset($_GET['type']) && ($_GET['type'] == "load")){
			// DB table to use
			
			$cond_y = isset($_GET['y'])? ' AND YEAR(E.expenses_date)  	='.$_GET['y']:'';
			$cond_m = isset($_GET['m'])? ' AND MONTH(E.expenses_date) 	='.$_GET['m']:'';
			$cond_d = isset($_GET['d'])? ' AND DAY(E.expenses_date) 	='.$_GET['d']:'';

			$cond   = $cond_y . ' ' . $cond_m . ' ' . $cond_d;


			$table  =  '(
				SELECT
					expenses_group_id,
					group_name,
					group_description,

					(
						 COALESCE((SELECT sum( expenses_quantity * expenses_unit_price )  FROM expenses E  WHERE is_deleted =0 AND E.expenses_group_id_fk= EG.expenses_group_id AND expenses_currency=0 '.$cond.'),0)

					) AS total_expenses_iq,

					(
						 COALESCE((SELECT sum( expenses_quantity * expenses_unit_price )  FROM expenses E  WHERE is_deleted =0 AND E.expenses_group_id_fk= EG.expenses_group_id AND expenses_currency=1  '.$cond.'),0)
					) AS total_expenses_usd

				FROM
					expenses_group EG
					
				WHERE
					( EG.is_deleted = 0 ) 
			) AS ALLTBL';

			// Table's primary key
			$primaryKey = 'expenses_group_id';
			$columns =  array(
				  			  array( 'db' => 'expenses_group_id', 'dt' => 0 ),
			    				array( 'db' => 'group_name', 'dt' => 1 ),
			    				array( 'db' => 'group_description', 'dt' => 2 ),
			    				array( 'db' => 'total_expenses_usd',   'dt' => 3),
								array( 'db' => 'total_expenses_iq',   'dt' => 4 )
			);
			// 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") {

			//$user_id = $_POST['cusid'];

			$res = $db->query("SELECT * FROM expenses_group WHERE is_deleted = 0");
			if ($res) {
				$op  = array();
				while ($row = $res->fetch_assoc()) {
				    // do what you need.
						$result[0] = $row['expenses_group_id'];
						$result[1] = $row['group_name'];
						array_push($op,$result);
				}
				echo json_encode($op);
				exit;
			}else{
				echo 0;
				exit;
			}
		}


		if ($_POST['type'] == "update") {

			$id 								= $_POST['obj_id'];
			$name 							=addslashes($_POST["name"]);
			$group_description	=addslashes($_POST["group_description"]);
			
			$op  = array('is_success'=>false, 'data' => '');
			$lastaction = "Update Expenses Group ";

			$res = $db->query("SELECT * FROM expenses_group WHERE is_deleted=0 AND group_name = '$name' AND expenses_group_id != '$id'");

			if (mysqli_num_rows($res)>0) {
				$op['is_success'] = false;
				$op['data'] 	  = "خطأ الاسم مكرر";
				echo json_encode($op);
				exit;
			}



			$lastaction = "Update Expenses Group information";
			$update_qry = "UPDATE expenses_group SET  group_name = '$name', group_description='$group_description',last_action='$lastaction',last_action_by='".$_SESSION['user_id']."' WHERE expenses_group_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 Expenses Group";


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

			$res = $db->query("SELECT * FROM expenses WHERE is_deleted=0  AND expenses_group_id_fk = '$id'");
			if (mysqli_num_rows($res)>0) {
			
				$op['is_success'] = false;
				$op['data'] 	  = "لا يمكنك حذف هذه المجموعة فهنالك مصاريف مرتبطة بالمجموعة";
				echo json_encode($op);
				exit;
			}

			
			

			


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

            $name=addslashes($_POST["name"]);
						$res = $db->query("SELECT * FROM expenses_group WHERE group_name = '$name' AND is_deleted=0");
						if (mysqli_num_rows($res)>0) {
							$op['is_success'] = false;
							$op['data'] 	  = "خطأ الاسم مكرر";
							echo json_encode($op);
							exit;
						}else{
							$group_description=addslashes($_POST["group_description"]);
							
							$delete = 0;
							$reg_date = date("Y-m-d h:i:s", time());
							$lastaction = "Create New Expneses Group";

						$sql ="INSERT INTO expenses_group (group_name,group_description,created_by,last_action,last_action_by)
						VALUES('$name','$group_description','".$_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;
	}
?>

