<?php
	session_start();
	require_once('includes/config.php');
	
	$active     = $_REQUEST['active'];
	$role_name  = $_REQUEST['role_name'];
	$dttm       = strtotime(date('d-m-Y h:i:s'));
	$user       = $_SESSION['userid'];
	$rId        = !empty( $_REQUEST['rId'] ) ? $_REQUEST['rId'] : 0;
	$call_back  = !empty( $_REQUEST['call_back'] ) ? $_REQUEST['call_back'] : 'roles';
	$table      = !empty( $_REQUEST['table'] ) ? $_REQUEST['table'] : 'roles';
	$key        = !empty( $_REQUEST['identifier'] ) ? $_REQUEST['identifier'] : 0;

	if( $rId == 0 ){
		$return = 0;
		$chk_query = "SELECT role_name FROM ".$table." WHERE role_name ='".$role_name."'";
		$cexe = mysqli_query( $con, $chk_query );
		$count = mysqli_num_rows( $cexe );

		if( $count >= 1 ) {
			echo json_encode( ['code' => 401 , 'data' => 'Role already exists', 'url' => $call_back  ] );exit;
		}else{
			$query = "INSERT INTO ".$table." ( role_name, active, created_at, created_by ) values( '".$role_name."', ".$active.", ".$dttm.", ".$user." )";			
			$exe = mysqli_query( $con, $query );		
			( $exe ) ? $return = 1 : $return = 0;
		}
		
		if( $return ){
			echo json_encode( ['code' => 200,'data' => 'Role added successfully', 'url' => $call_back ] );exit;
		}else{
			echo json_encode( ['code' => 405 , 'data' => 'Error Occured', 'url' => $call_back ] );exit;	
		}	
	}else{
		$query = "UPDATE ".$table." SET role_name = '".$role_name."', active = ".$active.", updated_at = ".$dttm.", updated_by = ".$user." WHERE ".$key." = ".$rId;			
		$exe = mysqli_query( $con, $query );		
		( $exe ) ? $return = 1 : $return = 0;				
		if( $return ){
			echo json_encode( ['code' => 200,'data' => 'Roles updated successfully', 'url' => $call_back ] );exit;
		}else{
			echo json_encode( ['code' => 405 , 'data' => 'Error Occured' , 'url' => $call_back ] );exit;	
		}	
	}

?>