<?php
if(!isset($_SESSION)) 
{ 
session_start(); 
} 
if(!isset($_SESSION['is_login']) ){
header("location: login.php");
?>
<script>
window.location="login.php";
</script>
<?php
}



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 D.class_id_fk='.$_GET['id']:'';
			
			$cond2 = isset($_GET['zid'])? ' AND D.zone_id_fk="'.$_GET['zid'].'"':'';
			$cond3 = isset($_GET['sid'])? ' AND D.sub_class_id_fk="'.$_GET['sid'].'"':'';
			$cond4 = isset($_GET['cid'])? ' AND D.city_id_fk="'.$_GET['cid'].'"':'';
			$cond5 = isset($_GET['city_id'])? ' AND D.city_id_fk="'.$_GET['city_id'].'"':'';


			$cond6 = '';

			if (isset($_GET['sp_id'])) {
				$pids = explode(',', $_GET['sp_id']);

				$cond6 = ' AND ( ';
				$orr = ' ';
				for ($mr=0; $mr <count($pids) ; $mr++) { 

					if ($pids[$mr] !='') {
						$cond6 =   $cond6 . $orr . ' D.specialty_id_fk='.$pids[$mr] ;
						$orr = ' OR ';
					}
					
					
				}
				
				$cond6 = $cond6 . ' ) ';

			}

			$cond = $cond1 . " " . $cond2 . " " . $cond3 . " " . $cond4 . " " . $cond5 . " " . $cond6;
			$table  =  '(
				SELECT
					GROUP_CONCAT(doctor_id) as ids,
					doctor_id,
					
					doctor_name,
					doctor_address,
					SP.doctor_specialty,
					SP.specialty_description,
					COUNT(*) as C,
					doctor_note,
					class_name,
					sub_class_name,
					city_name,
					full_name,
					zone_name,
					sub_zone_name,
					quarter_name,
					street_name
					
					
					
				FROM
					doctor D
					LEFT JOIN class CL ON (D.class_id_fk = CL.class_id)
					LEFT JOIN city C ON (D.city_id_fk = C.city_id)
					LEFT JOIN sub_class S ON (D.sub_class_id_fk = S.sub_class_id)
					LEFT JOIN zone Z ON (D.zone_id_fk = Z.zone_id)
					LEFT JOIN sub_zone SZ ON (D.sub_zone_id_fk = SZ.sub_zone_id)
					LEFT JOIN quarter Q ON (D.quarter_id_fk = Q.quarter_id)
					LEFT JOIN street SR ON (D.street_id_fk = SR.street_id)
                    LEFT JOIN staff ST ON (D.created_by = ST.staff_id)
                    LEFT JOIN specialty SP ON (D.specialty_id_fk = SP.specialty_id)

					
					
				WHERE
					( D.is_deleted = 0  '.$cond.') 
					GROUP BY doctor_name,D.city_id_fk HAVING C>1 ORDER BY C DESC
			) AS ALLTBL';
			// Table's primary key
			//echo $table;
			$primaryKey = 'doctor_id';
			$columns = array(
			    array( 'db' => 'ids', 'dt' => 0 ),
			    array( 'db' => 'doctor_name', 'dt' => 1 ),

			    array( 'db' => 'doctor_address', 'dt' => 2 ),
			    array( 'db' => 'doctor_specialty', 'dt' => 3 ),
			    array( 'db' => 'specialty_description', 'dt' => 4 ),
			    array( 'db' => 'C', 'dt' => 5 ),
			    array( 'db' => 'doctor_note', 'dt' => 6 ),
			    array( 'db' => 'class_name', 'dt' => 7 ),
			    array( 'db' => 'sub_class_name', 'dt' => 8 ),
			    array( 'db' => 'street_name', 'dt' => 9 ),
			    array( 'db' => 'quarter_name', 'dt' => 10 ),
			    array( 'db' => 'sub_zone_name', 'dt' => 11 ),
			    array( 'db' => 'zone_name', 'dt' => 12 ),
			    array( 'db' => 'city_name', 'dt' => 13 ),	
			    array( 'db' => 'full_name', 'dt' => 14 ),	
				
				
			);
			// 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']=="delete_duplicated") {

			

			if($_SESSION['profile_type'] != 5 ){
				$Validator['is_success'] = false;
				$Validator['data'] = "You Are Not Allowed To perform this Action";
				echo json_encode($Validator);
				exit;
			}
			

			


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

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

			

			$res = $db->query("DELETE D1 FROM doctor D1
								
								WHERE is_deleted=1");

			$res = $db->query("DELETE D1 FROM doctor D1
								
								WHERE doctor_name=''");

	  		$res = $db->query("DELETE D1 FROM doctor D1
								INNER JOIN doctor D2 
								WHERE D1.doctor_id < D2.doctor_id AND D1.doctor_name = D2.doctor_name AND D1.city_id_fk = D2.city_id_fk");

	  		

	  		

	    	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'] == "update") {

			$id 						= $_POST['edit_objid'];
			$class_id_fk				=addslashes($_POST["edit_class_id_fk"]);
			$sub_class_id_fk			=addslashes($_POST["edit_sub_class_id_fk"]);
			$city_id_fk					=addslashes($_POST["edit_city_id_fk"]);
			$zone_id_fk					=addslashes($_POST["edit_zone_id_fk"]);
			$sub_zone_id_fk				=addslashes($_POST["edit_sub_zone_id_fk"]);
			$quarter_id_fk				=addslashes($_POST["edit_quarter_id_fk"]);
			$street_id_fk				=addslashes($_POST["edit_street_id_fk"]);
			
			$doctor_name				=addslashes($_POST["edit_doctor_name"]);
			$doctor_address				=addslashes($_POST["edit_doctor_address"]);
			$specialty_id_fk			=addslashes($_POST["edit_specialty_id_fk"]);			
			$doctor_phone_no1			=addslashes($_POST["edit_doctor_phone_no1"]);
			$doctor_phone_no2			=addslashes($_POST["edit_doctor_phone_no2"]);
			$doctor_email				=addslashes($_POST["edit_doctor_email"]);
			$doctor_note				=addslashes($_POST["edit_doctor_note"]);
			

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

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

			$res = $db->query("SELECT * FROM doctor WHERE is_deleted=0 AND doctor_name = '$doctor_name' AND city_id_fk = $city_id_fk AND zone_id_fk=$zone_id_fk AND doctor_id != '$id'");
			if (mysqli_num_rows($res)>0) {
					$op['is_success'] = false;
					$op['data'] 	  = "خطأ اسم  مكررة";
					echo json_encode($op);
					exit;
			}

							


			$lastaction = "Update Doctor";
			$update_qry = "UPDATE doctor SET  
									doctor_name 		= '$doctor_name',
									doctor_address 		='$doctor_address',
									specialty_id_fk 	='$specialty_id_fk',
									doctor_phone_no1 	='$doctor_phone_no1',
									doctor_phone_no2 	='$doctor_phone_no2',
									doctor_email 		='$doctor_email',
									doctor_note 		='$doctor_note',
									
									class_id_fk 		='$class_id_fk',
									sub_class_id_fk 	='$sub_class_id_fk',
									street_id_fk 		='$street_id_fk',
									quarter_id_fk 		='$quarter_id_fk',
									sub_zone_id_fk 		='$sub_zone_id_fk',
									zone_id_fk 			='$zone_id_fk',
									city_id_fk 			='$city_id_fk',
									updated_at			='$reg_date',
									last_action			='$lastaction',
									last_action_by		='".$_SESSION['user_id']."' 
							WHERE   doctor_id = $id";


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

				// $target_dir = '../product_img/'.$id;
				// if(! file_exists($target_dir)){
				// 	mkdir($target_dir);
				// }

				// $image_path		='';
			    //             $manual_path 	='';
			    //             $State 			=true;
			    //             $State1			=true;
			    //             $error 			= '';			
			    //             $error1			= '';
			    //             $msgg			= "تمت عملية التحديث بنجاح";

				
				// if($_FILES['edit_image_path']['size'] > 0 ){
					
				// 	$ext11  = pathinfo(basename($_FILES['edit_image_path']['name']),PATHINFO_EXTENSION);
					
				// 	$image_file = $id ."_". rand(100000,10000000) ."_.".$ext11;
					
				// 	$target_file 		= $target_dir .'/'. basename($image_file);
					
				// 	$uploadOk = 1;
				// 	$imageFileType  = pathinfo($target_file,PATHINFO_EXTENSION);
										
				// 	$State1=true;
				// 	// Check file size
				// 	if ($_FILES["edit_image_path"]["size"] > 4000000) {
				// 			$error1= " Sorry, your Image is too large. ";
				// 			$State1=false;
				// 	}

					
				// 	// Allow certain file formats
				// 	if(strtolower($imageFileType) != "jpg" && strtolower($imageFileType) != "png" && strtolower($imageFileType) != "jpeg" && strtolower($imageFileType) != "gif" && strtolower($imageFileType) != "bmp" && strtolower($imageFileType) != "pdf" ) {
				// 		$error1= " Sorry, only JPG, JPEG, PNG & GIF & PDF files are allowed. ";
				// 		$State1=false;
				// 	}

				// 	// Check if $uploadOk is set to 0 by an error
				// 	if ($State1 == true) {
					
				// 		if (move_uploaded_file($_FILES["edit_image_path"]["tmp_name"], $target_file)){

				// 			$image_path  = 'product_img/'.$id .'/'.$image_file;
				// 			$State1=true;											  

				// 		} else {
				// 			$error1= " Sorry, there was an error uploading your file. ";
				// 			$State1=false;
				// 		}
				// 	}
				// }		
                
    			//             $tmp 			='';
		  		//       $update_file 	= '';
		        
				  //       if($image_path !=''){
				  //       	$update_file = "image_path = '$image_path'";

				  //       }

		       
				  //       // echo $update_file;
				  //       if($update_file !=''){
				  //       	$sql ="UPDATE  product SET $update_file WHERE product_id ='$id'";
									
						// 	$query = $db->query($sql);
				  //       }
		        
					



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

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

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

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

			

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

      		$city_id_fk				=addslashes($_POST["city_id_fk"]);
      		$zone_id_fk				=addslashes($_POST["zone_id_fk"]);
      		$class_id_fk			=addslashes($_POST["class_id_fk"]);
      		$sub_class_id_fk		=addslashes($_POST["sub_class_id_fk"]);

      		$sub_zone_id_fk			=addslashes($_POST["sub_zone_id_fk"]);
			$quarter_id_fk			=addslashes($_POST["quarter_id_fk"]);
			$street_id_fk			=addslashes($_POST["street_id_fk"]);
			
			
			$doctor_name			=addslashes($_POST["doctor_name"]);
			$doctor_address			=addslashes($_POST["doctor_address"]);
			$specialty_id_fk		=addslashes($_POST["specialty_id_fk"]);
			$doctor_phone_no1		=addslashes($_POST["doctor_phone_no1"]);
			$doctor_phone_no2		=addslashes($_POST["doctor_phone_no2"]);
			$doctor_email			=addslashes($_POST["doctor_email"]);			
			$doctor_note			=addslashes($_POST["doctor_note"]);			
			


			$res = $db->query("SELECT * FROM doctor WHERE is_deleted=0 AND doctor_name = '$doctor_name' AND city_id_fk = $city_id_fk AND zone_id_fk=$zone_id_fk");
			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 Doctor";

			$sql ="INSERT INTO doctor (
										doctor_name,
										doctor_address,
										specialty_id_fk,
										doctor_phone_no1,
										doctor_phone_no2,
										doctor_email,
										doctor_note,
										class_id_fk,
										sub_class_id_fk,
										street_id_fk,
										quarter_id_fk,
										sub_zone_id_fk,
										zone_id_fk,
										city_id_fk,
										created_by,
										last_action,
										last_action_by,
										created_at,
										updated_at)
								VALUES( '$doctor_name',
										
										'$doctor_address',
										'$specialty_id_fk',
										'$doctor_phone_no1',
										'$doctor_phone_no2',
										'$doctor_email',
										'$doctor_note',
										'$class_id_fk',
										'$sub_class_id_fk',
										'$street_id_fk',
										'$quarter_id_fk',
										'$sub_zone_id_fk',
										'$zone_id_fk',
										'$city_id_fk',
										'".$_SESSION['user_id']."',
										'$lastaction',
										'".$_SESSION['user_id']."',
										'$reg_date',
										'$reg_date')";

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

				if ($res) {

					
					



					$op['is_success'] = true;
					$op['data'] 	  = "تمت عملية الاضافة بنجاح";
					// $op['image'] 	  = $msgg;
					echo json_encode($op);
					exit;
				}
				else{
							$op['is_success'] = false;
							$op['data'] 	  = "حصل خطأ: الرجاء اعادة تحميل الصفحة والمحاولة من جديد";
							echo json_encode($op);
							exit;
				}
			

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