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

			$cond = $cond1 . " " . $cond2 . " " . $cond3 . " " . $cond4 . " " . $cond5;
			$table  =  '(
				SELECT

					GROUP_CONCAT(pharmacy_id) AS ids,
					GROUP_CONCAT(doctor_id_fk) AS d_ids,
					COUNT(*) as C ,
					pharmacy_id,
					
					pharmacy_name,
					pharmacy_address,
					pharmer_name,
					pharmacy_phone,
					pharmacy_type,
					pharmacy_note,
					pharmacy_file,
					PH.created_by,
					full_name,
					GROUP_CONCAT(doctor_name SEPARATOR ";") AS doctor_name,
					city_name,
					zone_name,
					sub_zone_name,
					quarter_name,
					street_name
					
					
					
				FROM
					pharmacy PH
					LEFT JOIN city C ON (PH.city_id_fk = C.city_id)
					LEFT JOIN zone Z ON (PH.zone_id_fk = Z.zone_id)
                    LEFT JOIN pharmacy_doctor PD ON (PD.pharmacy_id_fk = PH.pharmacy_id)
                    LEFT JOIN doctor D ON (D.doctor_id = PD.doctor_id_fk)
                    LEFT JOIN staff ST ON (PH.created_by = ST.staff_id)
                    LEFT JOIN sub_zone SZ ON (PH.sub_zone_id_fk = SZ.sub_zone_id)
					LEFT JOIN quarter Q ON (PH.quarter_id_fk = Q.quarter_id)
					LEFT JOIN street SR ON (PH.street_id_fk = SR.street_id)
					
					
				WHERE
					( PH.is_deleted = 0  '.$cond.')
                    GROUP BY pharmacy_name,PH.city_id_fk HAVING C>1 ORDER BY C DESC
			) AS ALLTBL';
			// Table's primary key
			//echo $table;
			$primaryKey = 'pharmacy_id';
			$columns = array(
			    array( 'db' => 'ids', 'dt' => 0 ),
			    array( 'db' => 'pharmacy_name', 'dt' => 1 ),
			    array( 'db' => 'pharmacy_address', 'dt' => 2 ),
			    // array( 'db' => 'pharmer_name', 'dt' => 3 ),
			    array( 'db' => 'C', 'dt' => 3 ),
			    array( 'db' => 'pharmacy_note', 'dt' => 4 ),
			    array( 'db' => 'd_ids', 'dt' => 5 ),
			    array( 'db' => 'doctor_name', 'dt' => 6 ),
			    array( 'db' => 'street_name', 'dt' => 7 ),
			    array( 'db' => 'quarter_name', 'dt' => 8 ),	
			    array( 'db' => 'sub_zone_name', 'dt' => 9 ),	
			    array( 'db' => 'zone_name', 'dt' => 10 ),	
			    array( 'db' => 'city_name', 'dt' => 11 ),	
			    array( 'db' => 'full_name', 'dt' => 12 ),	
			    array( 'db' => 'pharmacy_file', 'dt' => 13 ),	
				
				
			);
			// 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 Pharmacy";

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

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

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

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

			$res = $db->query("SELECT 
										GROUP_CONCAT(pharmacy_id) AS p_ids,
										GROUP_CONCAT(doctor_id_fk) AS d_ids,

								        pharmacy_id,
										pharmacy_name,
								        city_id_fk,
								        zone_id_fk,
								        COUNT(*) as C 
								        
								FROM pharmacy P
								LEFT JOIN pharmacy_doctor PD ON (PD.pharmacy_id_fk = P.pharmacy_id)
								WHERE P.is_deleted =0
								GROUP BY pharmacy_name,city_id_fk HAVING C>1");
			if ($res) {
				while ($row = $res->fetch_assoc()) {
				    
						$p = $row['p_ids'];
						$d = $row['d_ids'];
						$p_ids = explode(',', $p);
						$d_ids = explode(',', $d);
						rsort($p_ids);

						$chosed_pharmacy_id = $p_ids[0];

						// now we should insert it pharmacy_doctor

						


						$resd = $db->query("DELETE D1 FROM pharmacy_doctor D1
															
													WHERE pharmacy_id_fk IN ($p) ");

						$resd = $db->query("DELETE D1 FROM pharmacy_doctor D1
															
													WHERE doctor_id_fk IN ($d) ");
													        

						foreach ($d_ids as $doc_id){

							$resC = $db->query("SELECT doctor_id FROM doctor WHERE is_deleted=0 AND doctor_id = '$doc_id' ");
							if (mysqli_num_rows($resC)>0) {
									
								$sql2 ="INSERT INTO pharmacy_doctor (	
															doctor_id_fk, 
															pharmacy_id_fk,
															created_by,
															created_at,
															updated_at,
															last_action,
															last_action_by)

		 								 			VALUES( '$doc_id',
			 								 				
			 								 				'$chosed_pharmacy_id',
			 								 				'".$_SESSION['user_id']."',
			 								 				'$reg_date',
			 								 				'$reg_date',
			 								 				'$lastaction',
			 								 				'".$_SESSION['user_id']."')";
							
								$res2 = $db->query($sql2);
							}
						        
						} // foreach
						
						
						
				}
				
			}else{
				echo 0;
				exit;
			}


	  		$res = $db->query("DELETE D1 FROM pharmacy D1
								INNER JOIN pharmacy D2 
								WHERE D1.pharmacy_id < D2.pharmacy_id AND D1.pharmacy_name = D2.pharmacy_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']=="delete") {

			$id=addslashes($_POST["obj_id"]);
			$reg_date = date("Y-m-d H:i:s", time());
			$lastaction = "Delete Pharmacy";

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

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

			

			

	  		$res = $db->query("UPDATE pharmacy SET 	is_deleted = 1 ,
	  												deleted_at = '$reg_date',
	  												last_action='$lastaction',
	  												last_action_by='".$_SESSION['user_id']."' 
	  										WHERE pharmacy_id=$id");
	    	if ($res){

	    			$delete_qry = "DELETE FROM pharmacy_doctor WHERE pharmacy_id_fk = $id";

					$res3 = $db->query($delete_qry);

					
	        		$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"]);
      		$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_id_fk			=($_POST["doctor_id_fk"]);
			
			$pharmacy_name			=addslashes($_POST["pharmacy_name"]);
			$pharmacy_address		=addslashes($_POST["pharmacy_address"]);
			$pharmer_name			=addslashes($_POST["pharmer_name"]);
			$pharmacy_phone			=addslashes($_POST["pharmacy_phone"]);
			$pharmacy_type			=addslashes($_POST["pharmacy_type"]);
			$pharmacy_note			=addslashes($_POST["pharmacy_note"]);			
			

			

			$res = $db->query("SELECT * FROM pharmacy WHERE is_deleted=0 AND pharmacy_name = '$pharmacy_name' AND city_id_fk = $city_id_fk AND zone_id_fk=$zone_id_fk AND sub_zone_id_fk=$sub_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 = "Add New Pharmacy";

			$sql ="INSERT INTO pharmacy (
										pharmacy_name,
										pharmacy_address,
										pharmer_name,
										pharmacy_phone,
										pharmacy_type,
										pharmacy_note,
							
										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( 										
										'$pharmacy_name',
										'$pharmacy_address',
										'$pharmer_name',
										'$pharmacy_phone',
										'$pharmacy_type',
										'$pharmacy_note',
										
										'$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) {

					$last_inserted_id = $db->insert_id;

					foreach ($doctor_id_fk as $doc_id){


						$sql2 ="INSERT INTO pharmacy_doctor (	
													doctor_id_fk, 
													pharmacy_id_fk,
													
													
													created_by,
													created_at,
													updated_at,
													last_action,
													last_action_by)

 								 			VALUES( '$doc_id',
	 								 				
	 								 				'$last_inserted_id',
	 								 				'".$_SESSION['user_id']."',
	 								 				'$reg_date',
	 								 				'$reg_date',
	 								 				'$lastaction',
	 								 				'".$_SESSION['user_id']."')";
					
						$res2 = $db->query($sql2);
					        
					}

					
					/// for file upload
					$target_dir = '../pharmacy_img/'.$last_inserted_id;
					if(! file_exists($target_dir)){
						mkdir($target_dir);
					}
					

					$count=0;

					$image_path		='';
	                $manual_path 	='';
	                $State 			=true;
	                $State1			=true;
	                $error 			= '';			
	                $error1			= '';


					
					if($_FILES['image_path']['size'] > 0 ){
						
						$ext11  = pathinfo(basename($_FILES['image_path']['name']),PATHINFO_EXTENSION);
						
						$image_file = $last_inserted_id."_".rand(100000,10000000) ."_.".$ext11;
										
						// $image_file = rand(10000000,1000000000) . "-" .$_FILES['attach_bill']['name'];
						
						$target_file 		= $target_dir .'/'. basename($image_file);
						
						$uploadOk = 1;
						$imageFileType  = pathinfo($target_file,PATHINFO_EXTENSION);
											
						$State1=true;
						// Check file size
						if ($_FILES["image_path"]["size"] > 4000000) {
								$error1= " Sorry, your file 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["image_path"]["tmp_name"], $target_file)){

								$image_path  = 'pharmacy_img/'.$last_inserted_id .'/'.$image_file;
								$State1=true;											  

							} else {
									$error1= " Sorry, there was an error uploading your file. ";
									$State1=false;
							}
						}
					}		
	                
	                $tmp 			='';
			        
			        $sql ="UPDATE  pharmacy SET pharmacy_file = '$image_path' WHERE pharmacy_id ='$last_inserted_id'";
								
					$query = $db->query($sql);
					if (!$query) {
						$msgg= "Image Not Uploaded";
						$State=false;

					}else{
						$msgg= "Successfully Added ";
						$State=true;
					}

					



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