<?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'].'"':'';

			$cond5 = '';

			if (isset($_GET['city_id'])) {
				$pidc = explode(',', $_GET['city_id']);

				$cond5 = ' AND ( ';
				$orr = ' ';
				for ($mr=0; $mr <count($pidc) ; $mr++) { 

					if ($pidc[$mr] !='') {
						$cond5 =   $cond5 . $orr . ' PH.city_id_fk='.$pidc[$mr] ;
						$orr = ' OR ';
					}
					
					
				}
				
				$cond5 = $cond5 . ' ) ';

			}

			$cond = $cond1 . " " . $cond2 . " " . $cond3 . " " . $cond4 . " " . $cond5;
			$table  =  '(
				SELECT
					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_id
			) AS ALLTBL';
			// Table's primary key
			//echo $table;
			$primaryKey = 'pharmacy_id';
			$columns = array(
			    array( 'db' => 'pharmacy_id', 'dt' => 0 ),
			    array( 'db' => 'pharmacy_name', 'dt' => 1 ),
			    array( 'db' => 'pharmacy_address', 'dt' => 2 ),
			    // array( 'db' => 'pharmer_name', 'dt' => 3 ),
			    array( 'db' => 'pharmacy_phone', 'dt' => 3 ),
			    array( 'db' => 'pharmacy_type', 'dt' => 4 ),
			    array( 'db' => 'pharmacy_note', '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']=="get") {

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

			$res = $db->query("SELECT
									pharmacy_id,
									
									pharmacy_name,
									pharmacy_address,
									pharmer_name,
									pharmacy_phone,
									pharmacy_type,
									pharmacy_note,
									GROUP_CONCAT(doctor_id_fk SEPARATOR ';') AS doctor_id_fk,
									city_id_fk,
									zone_id_fk
									
									
									
								FROM
									pharmacy PH
									
				                LEFT JOIN pharmacy_doctor PD ON (PD.pharmacy_id_fk = PH.pharmacy_id)
				                   
									
								WHERE
									( PH.is_deleted = 0  )
				                    GROUP BY pharmacy_id");
			if ($res) {
				//$row = $res->fetch_all();
				$op  = array();
				while ($row = $res->fetch_assoc()) {
				   
						$result['pharmacy_id']  	= $row['pharmacy_id'];
						$result['pharmacy_name']  	= $row['pharmacy_name'];
						$result['pharmacy_address'] = $row['pharmacy_address'];
						
						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
									pharmacy_id,
									
									pharmacy_name,
									pharmacy_address,
									pharmer_name,
									pharmacy_phone,
									pharmacy_type,
									pharmacy_note,
									GROUP_CONCAT(doctor_id_fk SEPARATOR ';') AS doctor_id_fk,
									city_id_fk,
									zone_id_fk,
									sub_zone_id_fk,
									quarter_id_fk,
									street_id_fk
									
									
									
								FROM
									pharmacy PH
									
				                    LEFT JOIN pharmacy_doctor PD ON (PD.pharmacy_id_fk = PH.pharmacy_id)
				                   
									
								WHERE
									( PH.is_deleted = 0 AND  pharmacy_id = '$id' )
				                    GROUP BY pharmacy_id");
			if ($res) {
				
				
				while ($row = $res->fetch_assoc()) {
				   
						$result['pharmacy_id']  		= $row['pharmacy_id'];
						$result['pharmacy_name']  		= $row['pharmacy_name'];
						$result['pharmacy_address']  	= $row['pharmacy_address'];
						$result['pharmer_name']  		= $row['pharmer_name'];
						$result['pharmacy_phone']  		= $row['pharmacy_phone'];
						$result['pharmacy_type']  		= $row['pharmacy_type'];
						$result['pharmacy_note']  		= $row['pharmacy_note'];
						$result['doctor_id_fk']  		= $row['doctor_id_fk'];
						$result['zone_id_fk']  			= $row['zone_id_fk'];
						$result['city_id_fk']  			= $row['city_id_fk'];
						$result['sub_zone_id_fk']  		= $row['sub_zone_id_fk'];
						$result['quarter_id_fk']  		= $row['quarter_id_fk'];
						$result['street_id_fk']  		= $row['street_id_fk'];
						
						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']=="remove_image") {

			$id 		=addslashes($_POST["obj_id"]);
			$img_path 	=addslashes($_POST["img_path"]);

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

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

			

			

	  		$res = $db->query("UPDATE pharmacy SET pharmacy_file = '',last_action='$lastaction',last_action_by='".$_SESSION['user_id']."' WHERE pharmacy_id=$id");
	    	if ($res){
	        $op['is_success'] = true;
	        		if(@unlink('../'.$img_path)){

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

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

			$user_id = $_POST['obj_id'];

			$res = $db->query("SELECT * FROM product_image WHERE is_deleted=0 AND product_id_fk = '$user_id'");
			if ($res) {
				//$row = $res->fetch_all();
				$op  = array();
				while ($row = $res->fetch_assoc()) {
				    // do what you need.
						$result[0] = $row['image_path'];
						array_push($op,$result);
				}

				echo json_encode($op);
				exit;
			}else{
				echo 0;
				exit;
			}
		}


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

			$id = $_POST['category_id'];
			$cond = "";
			
			if($id !='' AND $id !=NULL AND $id > 0){
				$cond = " AND P.category_id_fk='$id' ";
			}


			$res = $db->query('

								SELECT
										product_id,
										
										product_name,
										product_code,
										barcode,
										made_in,
										image_path,
										color,

										total_length,
										total_area,
										width,
										height,
										thickness,
										liter,

										product_type,
										product_sequence,
										product_note,
										product_min_notification,
										
										category_id_fk,
										category
									FROM
										product P
										LEFT JOIN category C ON (P.category_id_fk = C.category_id)
										
									WHERE
										( P.is_deleted = 0 '.$cond.') 

								');
			if ($res) {
				
				$op  = array('invoice'=>array(),'details'=>array());
				while ($row = $res->fetch_assoc()) {
				   
					$result['product_id']  					= $row['product_id'];
					$result['product_name']  				= $row['product_name'];
					$result['product_code']  				= $row['product_code'];
					$result['barcode']  					= $row['barcode'];
					$result['made_in'] 						= $row['made_in'];
					$result['image_path']  					= $row['image_path'];
					$result['color']  						= $row['color'];
					$result['product_type']  				= $row['product_type'];
					$result['product_sequence']  			= $row['product_sequence'];
					$result['product_note']  				= $row['product_note'];
					$result['product_min_notification']  	= $row['product_min_notification'];
					$result['category']						= $row['category'];
					$result['category_id_fk']  				= $row['category_id_fk'];

					$result['total_length']  				= $row['total_length'];
					$result['total_area']  					= $row['total_area'];
					$result['width']  						= $row['width'];
					$result['height']  						= $row['height'];
					$result['thickness']  					= $row['thickness'];
					$result['liter']  						= $row['liter'];
					
					array_push($op['invoice'],$result);
			
				}		
				echo json_encode($op);
				exit;
			}else{
				echo 0;
				exit;
			}
		}

	


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

			$id 						= $_POST['edit_objid'];
			$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_id_fk			=($_POST["edit_doctor_id_fk"]);
			
			$pharmacy_name			=addslashes($_POST["edit_pharmacy_name"]);
			$pharmacy_address		=addslashes($_POST["edit_pharmacy_address"]);
			$pharmer_name			=addslashes($_POST["edit_pharmer_name"]);
			$pharmacy_phone			=addslashes($_POST["edit_pharmacy_phone"]);
			$pharmacy_type			=addslashes($_POST["edit_pharmacy_type"]);
			$pharmacy_note			=addslashes($_POST["edit_pharmacy_note"]);			
			

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

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

		

			$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 AND pharmacy_id != '$id'");
			if (mysqli_num_rows($res)>0) {
					$op['is_success'] = false;
					$op['data'] 	  = "خطأ اسم  مكررة";
					echo json_encode($op);
					exit;
			}

							


			$lastaction = "Update Pharmacy";
			$update_qry = "UPDATE pharmacy SET  
									pharmacy_name 		= '$pharmacy_name',
									pharmacy_address 	='$pharmacy_address',
									pharmer_name 		='$pharmer_name',
									pharmacy_phone 		='$pharmacy_phone',
									pharmacy_type 		='$pharmacy_type',
									pharmacy_note 		='$pharmacy_note',
									
									city_id_fk 			='$city_id_fk',
									zone_id_fk 			='$zone_id_fk',
									sub_zone_id_fk 		='$sub_zone_id_fk',
									quarter_id_fk 		='$quarter_id_fk',
									street_id_fk 		='$street_id_fk',
									
									updated_at			='$reg_date',
									last_action			='$lastaction',
									last_action_by		='".$_SESSION['user_id']."' 
							WHERE   pharmacy_id = $id";


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

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

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

				if(!$res3){
					
					$op['is_success'] = false;
					$op['data'] 	  = "هناك خطأ : Can't Delete Doctors from pharmacy doctor";
					echo json_encode($op);
					exit;
				}



				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',
 								 				
 								 				'$id',
 								 				'".$_SESSION['user_id']."',
 								 				'$reg_date',
 								 				'$reg_date',
 								 				'$lastaction',
 								 				'".$_SESSION['user_id']."')";
				
					$res2 = $db->query($sql2);
				        
				}


				$target_dir = '../pharmacy_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  = 'pharmacy_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 = "pharmacy_file = '$image_path'";

		        }

		       
		        // echo $update_file;
		        if($update_file !=''){
		        	$sql ="UPDATE  pharmacy SET $update_file WHERE pharmacy_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_selected") {

			$city_id_fk				=addslashes($_POST["delete_city_id_fk"]);
      		$zone_id_fk				=addslashes($_POST["delete_zone_id_fk"]);
      		$sub_zone_id_fk			=addslashes($_POST["delete_sub_zone_id_fk"]);
			$quarter_id_fk			=addslashes($_POST["delete_quarter_id_fk"]);
			$street_id_fk			=addslashes($_POST["delete_street_id_fk"]);

			$cond1 	= " is_deleted=1 ";
			$cond 	= " is_deleted=0 ";

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

			if ($city_id_fk > 0) {
				$cond .= " AND city_id_fk=$city_id_fk ";
			}
			if ($zone_id_fk > 0) {
				$cond .= " AND zone_id_fk=$zone_id_fk ";
			}
			
			if ($sub_zone_id_fk > 0) {
				$cond .= " AND sub_zone_id_fk=$sub_zone_id_fk ";
			}
			if ($quarter_id_fk > 0) {
				$cond .= " AND quarter_id_fk=$quarter_id_fk ";
			}
			if ($street_id_fk > 0) {
				$cond .= " AND street_id_fk=$street_id_fk ";
			}
			
			
			if ($cond=='') {
				$cond 	= $cond1;
			}


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

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


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