<?php

require "conn.php";
$test=0;

$CategoryID = $_POST["CategoryID"];
$UserLat = $_POST["UserLat"];
$UserLongt = $_POST["UserLongt"];

$Page = $_POST["Page"];
$KeyWord = $_POST["KeyWord"];

$UserID = $_POST["UserID"];

$Today = date("l");
$CurrentTime = date("H:i", strtotime($CreatedAtTrips. ' + 1 hours'));

$six_digit_random_number = random_int(100000, 999999);
$sql="UPDATE Users SET sentcode = '$six_digit_random_number' WHERE UserID = $UserID;";
					
				if(mysqli_query($con,$sql))
				{}



if($Page==""){
   $Page =0; 
}else{
   $Page = $Page * 20; 
}

$EnglishCategory = "";

$res = mysqli_query($con,"SELECT * FROM Categories WHERE CategoryID = $CategoryID");
                                
                                                $result = array();
                                
                                                while($row = mysqli_fetch_assoc($res)){
													
													$EnglishCategory = $row["EnglishCategory"];
												}
$Key = "";

$res = mysqli_query($con,"SELECT * FROM GoogleKey");
                                
                                                $result = array();
                                
                                                while($row = mysqli_fetch_assoc($res)){
													
													$Key = $row["GKey"];
													
												}



$DistanceValue = 0;
$res = mysqli_query($con,"SELECT * FROM `Distance`");
while($row = mysqli_fetch_assoc($res)){

//$data = $row[0];
$result[] = $row;

$DistanceValue = $row["DistanceValue"];

}


if($KeyWord==""){
$res = mysqli_query($con,"SELECT *, (6372.797 * acos(cos(radians($UserLat)) * cos(radians(ShopLat)) * cos(radians(ShopLongt) - radians($UserLongt)) + sin(radians($UserLat)) * sin(radians(ShopLat)))) AS distance FROM Shops WHERE CategoryID ='$CategoryID' AND Shops.Status = 'ACTIVE' HAVING distance <= $DistanceValue ORDER BY priority DESC , distance ASC LIMIT $Page, 20");
}else{
$res = mysqli_query($con,"SELECT *, (6372.797 * acos(cos(radians($UserLat)) * cos(radians(ShopLat)) * cos(radians(ShopLongt) - radians($UserLongt)) + sin(radians($UserLat)) * sin(radians(ShopLat)))) AS distance FROM Shops WHERE CategoryID ='$CategoryID' AND ShopName LIKE '%$KeyWord%' AND Shops.Status = 'ACTIVE' HAVING distance <= $DistanceValue ORDER BY priority DESC , distance ASC LIMIT $Page, 20");
}


//$res = mysqli_query($con,"SELECT * FROM Shops WHERE CategoryID ='$CategoryID'");
//$res = mysqli_query($con,"SELECT *, (6372.797 * acos(cos(radians($UserLat)) * cos(radians(ShopLat)) * cos(radians(ShopLongt) - radians($UserLongt)) + sin(radians($UserLongt)) * sin(radians(ShopLat)))) AS distance FROM Shops WHERE CategoryID ='$CategoryID' HAVING distance <= 50 || distance=NULL ORDER BY CategoryID DESC");

$result = array();

$i = 0 ;

while($row = mysqli_fetch_assoc($res)){

//$data = $row[0];


$ShopID = $row["ShopID"];
$Online = $row["ShopOpen"];


//$row["ShopOpen"] = "Closed";


$res6 = mysqli_query($con,"SELECT * FROM ShopTimes WHERE ShopID='$ShopID'");
    
            $result6 = array();

            while($row6 = mysqli_fetch_assoc($res6)){
            
			
			
            //$data = $row[0];
            $result6[] = $row6;
            $Times = $row6["Times"];
            $Day = $row6["Day"];
            
            if($Online=="Closed"){
  
				$row["ShopOpen"] = "Closed";
							
                        break;
            }
            
            
			  if($Today==$Day){
			      
			      if($Times=="Closed"){
                	
							$row["ShopOpen"] = "Closed";
						
                        break;
                    }
				  
				
				  
				  $Split2 = explode("-",$Times);
				  
				  $Start = $Split2[0];
				  $End = $Split2[1];
				  
				  if($End<$Start){
					 
					$End = "23:59";					 
				  }
				  
				  if ($CurrentTime >  $Start && $CurrentTime < $End)
					{
					//	echo 'FondDay';
					 
							
							$row["ShopOpen"] = "Open";
	
					}else{
					    
					    
							
							$row["ShopOpen"] = "Closed";
							
					
					}
				  break;
			  }
            }

$result[] = $row;



$test=4;

$isIntrst = 0;
        $res4 = mysqli_query($con,"SELECT * FROM Following WHERE UserID='$UserID' AND ShopID='$ShopID'");
        
        while($row4 = mysqli_fetch_assoc($res4)){
        

        
        $isIntrst = 1;
        
        }


        if($isIntrst==0){
            
            $result[$i] ->Follow = ('no');
             $array = [
            "isFollow" => "no",
            
            ];
        }else if($isIntrst==1){
            $result[$i] ->Follow = ('yes');
             $array = [
                "isFollow" => "yes",
            ];
        }




        array_splice($result[$i], 24, 25, $array);
        
        
        $result[$i]['Follow'] = $result[$i]['0'];
        unset($result[$i]['0']);
        
      //  $result[$i]['0'] = 'a7a';


    $i++;

}
if($KeyWord==""){
$res2 = mysqli_query($con,"SELECT *, (6372.797 * acos(cos(radians($UserLat)) * cos(radians(ShopLat)) * cos(radians(ShopLongt) - radians($UserLongt)) + sin(radians($UserLat)) * sin(radians(ShopLat)))) AS distance FROM Shops WHERE CategoryID ='$CategoryID' HAVING distance <= $DistanceValue ORDER BY priority DESC , distance ASC"); 
}else{
$res2 = mysqli_query($con,"SELECT *, (6372.797 * acos(cos(radians($UserLat)) * cos(radians(ShopLat)) * cos(radians(ShopLongt) - radians($UserLongt)) + sin(radians($UserLat)) * sin(radians(ShopLat)))) AS distance FROM Shops WHERE CategoryID ='$CategoryID' AND ShopName LIKE '%$KeyWord%' HAVING distance <= $DistanceValue ORDER BY priority DESC , distance ASC"); 

}
while($row2 = mysqli_fetch_assoc($res2)){

//$data = $row[0];

$result2[] = $row2;
$count =  $row2["count(*)"];
//if($count>20){
//$test=4;
//}else{
//	$test = 0;
//}

}

$count = count($result2);
$Page = $Page/20;
$next = 0;
$next = 20 * $Page;
$has = false;
$next = $next +20;

if($next>=$count){
    
    $has = false;
}else{
    $has =  true;
}

$array = array(
    "allresult" => $count,
    "currentpage" => $Page,
    "hasNextPage" => $has,
);




/////////////
//echo json_encode(array("result"=>$result));
if($test==4){
    $message ="sucssesfully";
    $success = true;
    $status_code = 200;

echo json_encode(array('status_code' => $status_code,'success' => $success ,"data"=>$result,"message"=>$message,"PageObject"=>$array));
}
else{
    
    
    $res = mysqli_query($con,"SELECT * FROM Shops JOIN Categories ON Shops.CategoryID = Categories.CategoryId WHERE Shops.CategoryID ='$CategoryID' AND Categories.DisplayAll='YES'");


    $result = array();



    while($row = mysqli_fetch_assoc($res)){
    
    //$data = $row[0];
    $result[] = $row;
    
    
    
    $test=4;
    
    }
    
    
    if($test==4){
    $message ="sucssesfully";
    $success = true;
    $status_code = 200;

echo json_encode(array('status_code' => $status_code,'success' => $success ,"data"=>$result,"message"=>$message,"PageObject"=>$array));
}
else{
    
//	$message ="No data";
//    $success = false;
//    $status_code = 200;
//		$result = []; 
 //  echo json_encode(array('status_code' => $status_code,'success' => $success ,"data"=>$result,"message"=>$message));
   
   
   $loc = $UserLat . ',' . $UserLongt;
   $x = getShops($EnglishCategory,$Key,$loc,'');

   $arr = json_decode($x, true);
   
   $arrLength = count($arr["results"]);
   $ss = $arr["results"];
   $next_page_token = $arr["next_page_token"];
   
   
   foreach($arr["results"] as $result) {
    $ShopName = $result['name'];
//	echo 'Name :' .$ShopName;
	
	foreach($result['geometry'] as $geometry) {
		
		
		$locations = $geometry['viewport'];
		$ShopLat =  $geometry['lat'];
		$ShopLongt = $geometry['lng'];

		 
	//	echo 'location : '. $ShopLat . ' , ' .  $ShopLongt;
		break;
		
	}
	

	
	//echo ' Rate : '. $result['rating']; 
	$actualpath = '';
	foreach($result['photos'] as $photo) {
		$photow = 'https://maps.googleapis.com/maps/api/place/photo?photoreference='.$photo["photo_reference"].'&sensor=false&maxheight=400&maxwidth=400&key='.$Key;
		$actualpath = $photow;
//		$photo["photo_reference"];
	//	echo ' Photo ' .$actualpath; 
	}
	
 //	echo ' CategoryID ' . $CategoryID;
//	echo  '<br>';
	
	
	//$actualpath = 'https://maps.googleapis.com/maps/api/place/photo?photoreference=AW30NDw8XqjBCrnwmel3PqAQpnk7s1unc3vkSDr8WyyHm0JPik1chBMpyV5eDARARZeMEjpuSmP1iXBj5rRlUNzQsaHquCXC_11Ve0wUXQq7nPHrgJCbZoWdHf9nka2FmcLCJAR2jVw1zsEKfSerabdRQpO1ocJZdNq2WP6CeCoIzudK1WtN&sensor=false&maxheight=400&maxwidth=400&key=AIzaSyC2E7CGzA-t0WDY6VXvnvErSyI-emyMgok';
	
	//$ShopName = 'Shilvanti Patel';
	//echo $ShopName;
//	$ShopLat = floatval($ShopLat);
//	$ShopLongt = floatval($ShopLongt);
	
	//echo ' loc ';
	//echo  $ShopLat . ' ';
	//echo  $ShopLongt;
	
	$ShopName2 = str_replace(" ","",$ShopName);
	
	$sql="INSERT INTO Shops (ShopName,ShopPhone,ShopLogName,ShopPassword,ShopLat,ShopLongt,ShopLogo,ShopCover,CategoryID,Type,AdminID,googleshophkey) VALUES
  ('$ShopName','','$ShopName2','admin',$ShopLat,$ShopLongt,'$actualpath','$actualpath','$CategoryID','Other','1','YES')";
   if(mysqli_query($con,$sql))
   {
	   
	//   echo 'added';
	   
   }else{
	   
	//   echo $con -> error;
   }
   
   
   
   
	
	}



/////////////////second

//	sleep(2000); 

   $loc = $UserLat . ',' . $UserLongt;
   $x = getShops($EnglishCategory,$Key,$loc,$next_page_token);

   $arr = json_decode($x, true);
   
   $arrLength = count($arr["results"]);
   $ss = $arr["results"];
   $next_page_token = $arr["next_page_token"];
   
   
   foreach($arr["results"] as $result) {
    $ShopName = $result['name'];
//	echo 'Name :' .$ShopName;
	
	foreach($result['geometry'] as $geometry) {
		
		
		$locations = $geometry['viewport'];
		$ShopLat =  $geometry['lat'];
		$ShopLongt = $geometry['lng'];

		 
	//	echo 'location : '. $ShopLat . ' , ' .  $ShopLongt;
		break;
		
	}
	

	
	//echo ' Rate : '. $result['rating']; 
	$actualpath = '';
	foreach($result['photos'] as $photo) {
		$photow = 'https://maps.googleapis.com/maps/api/place/photo?photoreference='.$photo["photo_reference"].'&sensor=false&maxheight=400&maxwidth=400&key='.$Key;
		$actualpath = $photow;
//		$photo["photo_reference"];
	//	echo ' Photo ' .$actualpath; 
	}
	
 //	echo ' CategoryID ' . $CategoryID;
//	echo  '<br>';
	
	
	//$actualpath = 'https://maps.googleapis.com/maps/api/place/photo?photoreference=AW30NDw8XqjBCrnwmel3PqAQpnk7s1unc3vkSDr8WyyHm0JPik1chBMpyV5eDARARZeMEjpuSmP1iXBj5rRlUNzQsaHquCXC_11Ve0wUXQq7nPHrgJCbZoWdHf9nka2FmcLCJAR2jVw1zsEKfSerabdRQpO1ocJZdNq2WP6CeCoIzudK1WtN&sensor=false&maxheight=400&maxwidth=400&key=AIzaSyC2E7CGzA-t0WDY6VXvnvErSyI-emyMgok';
	
	//$ShopName = 'Shilvanti Patel';
	//echo $ShopName;
//	$ShopLat = floatval($ShopLat);
//	$ShopLongt = floatval($ShopLongt);
	
	//echo ' loc ';
	//echo  $ShopLat . ' ';
	//echo  $ShopLongt;
	
	$ShopName2 = str_replace(" ","",$ShopName);
	
	if(strlen($ShopName)<20){
	
		$sql="INSERT INTO Shops (ShopName,ShopPhone,ShopLogName,ShopPassword,ShopLat,ShopLongt,ShopLogo,ShopCover,CategoryID,Type,AdminID,googleshophkey) VALUES
	  ('$ShopName','','$ShopName2','admin',$ShopLat,$ShopLongt,'$actualpath','$actualpath','$CategoryID','Other','1','YES')";
	   if(mysqli_query($con,$sql))
	   {
		   
		//   echo 'added';
		   
	   }else{
		   
		//   echo $con -> error;
	   }
   
	}
   
   
   
	
	}




$res = mysqli_query($con,"SELECT *, (6372.797 * acos(cos(radians($UserLat)) * cos(radians(ShopLat)) * cos(radians(ShopLongt) - radians($UserLongt)) + sin(radians($UserLat)) * sin(radians(ShopLat)))) AS distance FROM Shops WHERE CategoryID ='$CategoryID' HAVING distance <= $DistanceValue ORDER BY priority DESC , distance ASC");


    $result = array();



    while($row = mysqli_fetch_assoc($res)){
    
    //$data = $row[0];
    $result[] = $row;
    
    
    
    $test=4;
    
    }
    
    
    if($test==4){
    $message ="sucssesfully";
    $success = true;
    $status_code = 200;

echo json_encode(array('status_code' => $status_code,'success' => $success ,"data"=>$result,"message"=>$message,"PageObject"=>$array));
}
else{
    
	$message ="No data";
    $success = false;
    $status_code = 200;
		$result = []; 
   echo json_encode(array('status_code' => $status_code,'success' => $success ,"data"=>$result,"message"=>$message));
   
}
   
   
   
   
}
}




function getShops($Category,$Key,$loca,$next_page_token)
	{
		$url = 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?location='.$loca.'&type='.$Category.'&key='.$Key.'&pagetoken='.$next_page_token.'&language=en&rankby=distance';
		$fields =array(
			 'to' => $tokens,
			 'notification'=>array(
			 'title' => $PostTitle,
			 'body' => $Message)
			);

			$headers = array(
			'Authorization:key=AAAAEDOF67k:APA91bFMPNwvWHetPtqc1i--ztKxrPdSd7ZbTXvrm0LWFV6KHlkw5I-9yOdt6ZtBq1PXo3uVEDcJnFmbAKpNH7tTS9wiKLjAaeLzB0J0KMI6xvsZ5z0C-4Kn98VzSLp_fJs-ibpmOJY2',
			'Content-Type:application/json'
			);

	   $ch = curl_init();
       curl_setopt($ch, CURLOPT_URL, $url);
       curl_setopt($ch, CURLOPT_POST, true);
       curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
       curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
       curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);  
       curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
       curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
       $result = curl_exec($ch);           
       if ($result === FALSE) {
           die('Curl failed: ' . curl_error($ch));
       }
       curl_close($ch);
       return $result;
	}





die;
mysqli_close($con);
?>