<?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 P.category_id_fk='.$_GET['id']:'';
			
			$cond2 = isset($_GET['tp'])? ' AND P.product_type="'.$_GET['tp'].'"':'';

			$cond = $cond1 . " " . $cond2;
			$table  =  '(
				SELECT
					branch_id,
					
					branch_name,
					location,
					branch_address,
					branch_phone,
					branch_email,
					

					full_name
					
				FROM
					branch B
					LEFT JOIN staff S ON (B.last_action_by = S.staff_id)
					
				WHERE
					( B.is_deleted = 0 '.$cond.') 
			) AS ALLTBL';
			// Table's primary key
			//echo $table;
			$primaryKey = 'branch_id';
			$columns = array(
			    array( 'db' => 'branch_id', 'dt' => 0 ),
			    array( 'db' => 'branch_name', 'dt' => 1 ),

			    array( 'db' => 'location', 'dt' => 2 ),
			    array( 'db' => 'branch_address', 'dt' => 3 ),
			    array( 'db' => 'branch_phone', 'dt' => 4 ),
			    array( 'db' => 'branch_email', 'dt' => 5 ),
			    array( 'db' => 'full_name', 'dt' => 6 ),	
				
				
			);
			// 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'];

			$cond = (isset($_POST['branch_id']) && $_POST['branch_id'] > 0)? ' AND B.branch_id='.$_POST['branch_id']:'';


			$res = $db->query("SELECT   branch_id,
										branch_name,
										B.location,
										branch_address,
										branch_phone,
										branch_email,
										stock_id
									FROM branch B
									LEFT JOIN stock S ON (S.branch_id_fk = B.branch_id)
								WHERE B.is_deleted = 0 AND S.is_deleted=0  $cond ");
			if ($res) {
				//$row = $res->fetch_all();
				$op  = array();
				while ($row = $res->fetch_assoc()) {
				   
						$result['branch_id']  		= $row['branch_id'];
						$result['branch_name']  	= $row['branch_name'];
						$result['location']  		= $row['location'];
						$result['branch_address']  	= $row['branch_address'];
						$result['branch_phone']  	= $row['branch_phone'];
						$result['branch_email']  	= $row['branch_email'];
						$result['stock_id']  		= $row['stock_id'];
						array_push($op,$result);
				}
				echo json_encode($op);
				exit;
			}else{
				echo $db->error;
				exit;
			}
		}


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

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

			$cond = (isset($_POST['branch_id']) && $_POST['branch_id'] > 0)? ' AND B.branch_id='.$_POST['branch_id']:'';


			$res = $db->query("SELECT   branch_id,
										branch_name,
										B.location,
										branch_address,
										branch_phone,
										branch_email
									FROM branch B
								WHERE B.is_deleted = 0   $cond ");
			if ($res) {
				//$row = $res->fetch_all();
				$op  = array();
				while ($row = $res->fetch_assoc()) {
				   
						$result['branch_id']  		= $row['branch_id'];
						$result['branch_name']  	= $row['branch_name'];
						$result['location']  		= $row['location'];
						$result['branch_address']  	= $row['branch_address'];
						$result['branch_phone']  	= $row['branch_phone'];
						$result['branch_email']  	= $row['branch_email'];
						array_push($op,$result);
				}
				echo json_encode($op);
				exit;
			}else{
				echo $db->error;
				exit;
			}
		}

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

			$id = $_POST['obj_id'];
			$op  = array('is_success'=>false, 'data' => array());

			$res = $db->query("SELECT 
									branch_id,
				
									branch_name,
									location,
									branch_address,
									branch_phone,
									branch_email
				 				FROM branch B  WHERE B.is_deleted = 0 AND branch_id = '$id'");
			if ($res) {
				
				
				while ($row = $res->fetch_assoc()) {
				   
						$result['branch_id']  		= $row['branch_id'];
						$result['branch_name']  	= $row['branch_name'];
						$result['location']  		= $row['location'];
						$result['branch_address']  	= $row['branch_address'];
						$result['branch_phone']  	= $row['branch_phone'];
						$result['branch_email']  	= $row['branch_email'];
						
						
						array_push($op['data'],$result);
				}
				$op['is_success'] = true;
				echo json_encode($op);
				exit;
			}else{
				$op['is_success'] = false;
				$op['data'] 	  = "No Data";
				echo json_encode($op);

				exit;
			}
		}

	


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

			$id 						= $_POST['edit_objid'];
			
			$branch_name				=addslashes($_POST["edit_branch_name"]);
			$branch_phone				=addslashes($_POST["edit_branch_phone"]);
			$branch_email				=addslashes($_POST["edit_branch_email"]);
			$location					=addslashes($_POST["edit_location"]);
			$branch_address				=addslashes($_POST["edit_branch_address"]);
			

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

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

			$res = $db->query("SELECT * FROM branch WHERE is_deleted=0 AND branch_name = '$branch_name' AND branch_id != '$id'");
			if (mysqli_num_rows($res)>0) {
					$op['is_success'] = false;
					$op['data'] 	  = "خطا الاسم مكرر";
					echo json_encode($op);
					exit;
			}



			$lastaction = "Update Branch";
			$update_qry = "UPDATE branch SET  
									branch_name 	= 	'$branch_name',
									branch_phone	=	'$branch_phone',
									branch_email	=	'$branch_email',
									location 		=	'$location',
									branch_address 	=	'$branch_address',
									
									updated_at='$reg_date',
									last_action='$lastaction',
									last_action_by='".$_SESSION['user_id']."' 
									WHERE branch_id = $id";


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

					

			      	$lastaction = "Update Branch roles";
					$role_name = 'Access_Branch_'.$branch_name;
					
					$update_qry1 = "UPDATE role SET role = '$role_name',
													last_action='$lastaction',
													last_action_by='".$_SESSION['user_id']."' 
									WHERE id_fk = $id AND table_name = 'branch' AND action ='view'";

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

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

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

			$res = $db->query("SELECT * FROM staff WHERE is_deleted=0 AND branch_id_fk = '$id'");
			if (mysqli_num_rows($res)>0) {
				$op['is_success'] = false;
				$op['data'] 	  = "لا يمكن حذف هذه المادة فقد تم بيع البعض منها";
				echo json_encode($op);
				exit;
			}

			

			

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

      		$branch_name				=addslashes($_POST["branch_name"]);
			$branch_phone				=addslashes($_POST["branch_phone"]);
			$branch_email				=addslashes($_POST["branch_email"]);
			$location					=addslashes($_POST["location"]);
			$branch_address				=addslashes($_POST["branch_address"]);
			
			
			$res = $db->query("SELECT * FROM branch WHERE is_deleted=0 AND branch_name = '$branch_name'");
			if (mysqli_num_rows($res)>0) {
					$op['is_success'] = false;
					$op['data'] 	  = "خطأ الاسم مكرر";
					echo json_encode($op);
					exit;
			}

			

			

			$delete = 0;
			$reg_date = date("Y-m-d h:i:s", time());
			$lastaction = "Create New Branch";

			$sql ="INSERT INTO branch (
										branch_name,
										location,
										branch_address,
										branch_phone,
										branch_email,
										
										created_by,
										last_action,
										last_action_by,
										created_at,
										updated_at)
								VALUES( '$branch_name',
										'$location',
										'$branch_address',
										'$branch_phone',
										'$branch_email',
										'".$_SESSION['user_id']."',
										'$lastaction',
										'".$_SESSION['user_id']."',
										'$reg_date',
										'$reg_date')";

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

				if ($res) {

					
					$last_inserted_id = $db->insert_id;
					// create Role for this stock
					$lastaction = "Create New Role for Branch ".$branch_name;
					$role_name = 'Access_Branch_'.$branch_name;

					$sql1 ="INSERT INTO role (	role,
												id_fk,
												table_name,
												action,
												created_by,
												last_action,
												last_action_by)
										VALUES('$role_name',
												'$last_inserted_id',
												'branch',
												'view',
												'".$_SESSION['user_id']."',
												'$lastaction',
												'".$_SESSION['user_id']."')";
					$res1 = $db->query($sql1);

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