<?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")){
			
			// show All products for specific category
			$cond = isset($_GET['id'])? ' AND E.expenses_group_id_fk='.$_GET['id']:'';
			$table  =  '(
				SELECT
					sub_class_id,
					sub_class_name,
					sub_class_description,
					class_id_fk,
					C.created_at,
					
					class_name,
					(SELECT COUNT(doctor_id)  FROM doctor D WHERE D.is_deleted=0 AND D.sub_class_id_fk = C.sub_class_id) AS class_count
				FROM
					sub_class C

					LEFT JOIN class CC ON (CC.class_id = C.class_id_fk)
					
					
				WHERE
					( C.is_deleted = 0 ) 
			) AS ALLTBL';
			
			$primaryKey = 'sub_class_id';
			$columns =  array(
				  			  	array( 'db' => 'sub_class_id', 'dt' => 0 ),
			    				array( 'db' => 'sub_class_name', 'dt' => 1 ),
			    				array( 'db' => 'sub_class_description',  'dt' => 2 ),
			    				array( 'db' => 'class_count',  'dt' => 3 ),
			    				array( 'db' => 'class_name',  'dt' => 4 ),
			    				array( 'db' => 'created_at',   'dt' => 5 , 'formatter'=> function($d){
									return date('Y-m-d',strtotime($d));
									 } ),
								array( 'db' => 'class_id_fk',   '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'];

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


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

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

			$res = $db->query('SELECT
									sub_class_id,
									
									sub_class_name,
									sub_class_description,
									class_id_fk
									

									FROM
										sub_class C
										
									WHERE
										( C.is_deleted = 0 AND C.sub_class_id = '.$id.') 

								');
			if ($res) {
				
				
				while ($row = $res->fetch_assoc()) {
				   
					$result['sub_class_id']  			= $row['sub_class_id'];
					$result['sub_class_name']  			= $row['sub_class_name'];
					$result['sub_class_description']  	= $row['sub_class_description'];
					$result['class_id_fk']  			= $row['class_id_fk'];
						
						
						
					array_push($op['data'],$result);
				}
				$op['is_success'] = true;
				echo json_encode($op);
				exit;
			}else{
				$op['is_success'] = false;
				$op['data'] 	  = $db->error;
				echo json_encode($op);

				exit;
			}
		}

		
		

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

			$id 				= $_POST['obj_id'];
			$name 				=addslashes($_POST["name"]);
			$sub_class_description 	=addslashes($_POST["sub_class_description"]);
			$class_id_fk 	=addslashes($_POST["class_id_fk"]);

			

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

			$res = $db->query("SELECT * FROM sub_class WHERE is_deleted=0 AND sub_class_name = '$name' AND sub_class_id != '$id'");

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

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


			$lastaction = "Update Sub-Class";
			$update_qry = "UPDATE sub_class SET sub_class_name = '$name',
												sub_class_description='$sub_class_description',
												class_id_fk='$class_id_fk',
												last_action='$lastaction',
												updated_at='$reg_date',
												last_action_by='".$_SESSION['user_id']."' 
										  WHERE sub_class_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 Class";


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

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

			

			


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

			$res = $db->query("SELECT * FROM sub_class WHERE sub_class_name = '$name' AND is_deleted=0");
			
			if (mysqli_num_rows($res)>0) {
				$op['is_success'] = false;
				$op['data'] 	  = "خطأ اسم الفئة مكرر";
				echo json_encode($op);
				exit;
			}
			
			$sub_class_description=addslashes($_POST["sub_class_description"]);

			

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

			$sql ="INSERT INTO sub_class (	sub_class_name,
										 	sub_class_description,
										 	class_id_fk,
											created_by,
											created_at,
										    updated_at,
											last_action,
											last_action_by)
									VALUES( '$name',
											'$sub_class_description',
											'$class_id_fk',
											'".$_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;
			}
						

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

