<?php

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

$SearchWord = $_POST["SearchWord"];
$UserLat = $_POST["UserLat"];
$UserLongt = $_POST["UserLongt"];
$UserID  = $_POST["UserID"];


$api_key = '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';

// الكلمة المُدخلة من المستخدم
//$SearchWord = $_POST['SearchWord'] ?? 'piza'; // افتراضياً piza إذا لم يتم إدخال أي كلمة

// تحضير النص المطلوب للإرسال
$prompt = "Correct the following word if it has any spelling mistakes and give me the answer in one word without any additions: \"$SearchWord\".";

// بيانات الطلب
$data = [
    "model" => "gpt-3.5-turbo",
    "messages" => [
        ["role" => "system", "content" => "You are a spelling correction assistant."],
        ["role" => "user", "content" => $prompt]
    ],
    "temperature" => 0
];

// إرسال الطلب إلى OpenAI
$url = 'https://api.openai.com/v1/chat/completions';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data, JSON_UNESCAPED_UNICODE));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'Authorization: Bearer ' . $api_key
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// تنفيذ الطلب
$response = curl_exec($ch);

// التحقق من الأخطاء
if (curl_errno($ch)) {
    die('cURL Error: ' . curl_error($ch));
}
curl_close($ch);

// معالجة الاستجابة
$responseArray = json_decode($response, true);

if (isset($responseArray['choices'][0]['message']['content'])) {
    $correctedWord = trim($responseArray['choices'][0]['message']['content']);
   // echo "Corrected Word: " . htmlspecialchars($correctedWord);
	$SearchWord = $correctedWord;
	//echo $SearchWord;
} else {
   // echo "Error: Unable to correct the word.";
}




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

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

$DistanceValue = $row["DistanceValue"];

}

$sql="INSERT INTO UserSearchTable (UserID,UserSearchTableText) VALUES ('$UserID','$SearchWord');";
   if(mysqli_query($con,$sql))
   { }

$DistanceValue = 10000;

$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 Foods JOIN ShopsCategory ON Foods.FoodCatID = ShopsCategory.CategoryShopID JOIN Shops ON Shops.ShopID = ShopsCategory.ShopID JOIN Categories ON Categories.CategoryId = Shops.CategoryId WHERE Shops.Status = 'ACTIVE' AND Foods.FoodName LIKE '%$SearchWord%' HAVING distance <= $DistanceValue ORDER BY distance ASC LIMIT 0, 20");


$result = array();


$i = 0;
while($row = mysqli_fetch_assoc($res)){


$result[] = $row;


$FoodID = $row["FoodID"];

$k = 0;    

 $res2 = mysqli_query($con,"SELECT * FROM ExtraCategory WHERE ProductID='$FoodID'");

        $result2 = array();
        
        while($row2 = mysqli_fetch_assoc($res2)){
        
        //$data = $row[0];
        $result2[] = $row2;
        
        $test=4;
        
        
        $ExtraCategoryID = $row2["ExtraCategoryID"];
        
        
        
             $res3 = mysqli_query($con,"SELECT * FROM ExtraInSideCategoty WHERE ExtraCategoryID='$ExtraCategoryID'");
    
            $result3 = array();
            
            while($row3 = mysqli_fetch_assoc($res3)){
            
            //$data = $row[0];
            $result3[] = $row3;
                
                
                
            }
        
        
        array_splice($result2[$k], 200, 201, array($result3));
    $k++;   
        
        }

        
        array_splice($result[$i], 200, 201, array($result2));

$i++;


$test=4;

}


$res = mysqli_query($con,"SELECT Shops.*, (6372.797 * acos(cos(radians($UserLat)) * cos(radians(ShopLat)) * cos(radians(ShopLongt) - radians($UserLongt)) + sin(radians($UserLat)) * sin(radians(ShopLat)))) AS distance FROM Foods JOIN ShopsCategory ON Foods.FoodCatID = ShopsCategory.CategoryShopID JOIN Shops ON Shops.ShopID = ShopsCategory.ShopID JOIN Categories ON Categories.CategoryId = Shops.CategoryId WHERE Shops.Status = 'ACTIVE' AND Foods.FoodName LIKE '%$SearchWord%' GROUP BY Shops.ShopID HAVING distance <= $DistanceValue  ORDER BY distance ASC LIMIT 0, 20");
while($row = mysqli_fetch_assoc($res)){

$result2[] = $row;
$test=4;

}

$i = 0;
$res = mysqli_query($con,"SELECT Shops.ShopLat,Shops.ShopLongt,Posts.Video,Posts.BunnyV,Posts.BunnyS,Shops.ShopID,Shops.ShopName,Shops.ShopLogo,Shops.ShopCover,Posts.ProductID,Posts.PostID,Shops.BakatID,Shops.Type,Shops.ShopOpen, (6372.797 * acos(cos(radians($UserLat)) * cos(radians(ShopLat)) * cos(radians(ShopLongt) - radians($UserLongt)) + sin(radians($UserLat)) * sin(radians(ShopLat)))) AS distance FROM Shops JOIN Posts ON Shops.ShopID=Posts.ShopID JOIN ShopsCategory ON Shops.ShopID = ShopsCategory.ShopID JOIN Foods ON Foods.FoodCatID = ShopsCategory.CategoryShopID WHERE Shops.Status = 'ACTIVE' AND Posts.PostStatus='ACTIVE' AND Foods.FoodName LIKE '%$SearchWord%' AND (Posts.Video!='' AND Posts.Video!='0') HAVING distance <= 10050 UNION SELECT Shops.ShopLat,Shops.ShopLongt,ShopStory.StoryPhoto as Video,ShopStory.BunnyV,ShopStory.BunnyS,Shops.ShopID,Shops.ShopName,Shops.ShopLogo,Shops.ShopCover,ShopStory.ProductId as ProductID,ShopStory.StotyID as PostID,Shops.BakatID,Shops.Type,Shops.ShopOpen,(6372.797 * acos(cos(radians($UserLat)) * cos(radians($UserLongt)) * cos(radians(ShopLongt) - radians(31.7081448)) + sin(radians($UserLat)) * sin(radians(ShopLat)))) AS distance FROM Shops JOIN ShopStory ON Shops.ShopID=ShopStory.ShopID JOIN ShopsCategory ON Shops.ShopID = ShopsCategory.ShopID JOIN Foods ON Foods.FoodCatID = ShopsCategory.CategoryShopID WHERE Shops.Status = 'ACTIVE' AND ShopStory.StoryStatus='ACTIVE' AND ShopStory.StotyType='Video' AND Foods.FoodName LIKE '%$SearchWord%' LIMIT 0, 5");
while($row = mysqli_fetch_assoc($res)){
	

	$PostID    = $row["PostID"];
	$ProductID = $row["ProductID"];
	
	if($row["BunnyV"]!='-'){
		$row["Video"] = $row["BunnyV"];
	}
	
		$row["Thumbnail"]= $row["BunnyS"];
	$isLiked = 0;
    $res5 = mysqli_query($con,"SELECT * FROM Likes WHERE PostID='$PostId' AND UserID='$UserID'");
        
        while($row5 = mysqli_fetch_assoc($res5)){
        
        //$data = $row[0];

        
        $isLiked = 1;
        
        }

     if($isLiked==0){
             $array = [
            "isLiked" => "no",
            ];
    }else{
         $array = [
            "isLiked" => "yes",
            ];
    }
	
	$result3 = array();
	
	$res5 = mysqli_query($con,"SELECT * FROM Foods WHERE FoodID='$ProductID '");
        
		
		
		$ii = 0;
        while($row5 = mysqli_fetch_assoc($res5)){
        
        //$data = $row[0];
        $result3[] = $row5;
		
		$FoodID = $row5["FoodID"];
		
		
				$k = 0;
		 $res24 = mysqli_query($con,"SELECT * FROM ExtraCategory WHERE ProductID='$FoodID'");

				$result24 = array();
				
				while($row24 = mysqli_fetch_assoc($res24)){
				
				//$data = $row[0];
				$result24[] = $row24;
				$ExtraCategoryID = $row24["ExtraCategoryID"];
						
						
						////////////////
						
						
						$res35 = mysqli_query($con,"SELECT * FROM ExtraInSideCategoty WHERE ExtraCategoryID='$ExtraCategoryID'");
			
							$result35 = array();
							
							while($row35 = mysqli_fetch_assoc($res35)){
							
							//$data = $row[0];
							$result35[] = $row35;
								
								
								
							}
						
						
						array_splice($result24[$k], 19, 20, array($result35));
					$k++;   
				
				
				
				
				}

				
				array_splice($result3[$ii], 90, 100, array($result24));

		$ii++;
		
		
		

        
        }

		

		$result44[] = $row;
		
		array_splice($result44[$i], 100, 101, array($array));
		array_splice($result44[$i], 200, 201, array($result3[0]));

$test=4;
$i++;

	
}

$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 JOIN Posts ON Shops.ShopID=Posts.ShopID LEFT JOIN Foods ON Posts.ProductID = Foods.FoodID WHERE Shops.Status = 'ACTIVE' AND Posts.PostStatus='ACTIVE' AND Foods.FoodName LIKE '%$SearchWord%' HAVING distance <= 10050 ORDER BY  distance ASC , Posts.PostId DESC LIMIT 0, 5");
$i = 0;
while($row = mysqli_fetch_assoc($res)){
	
	$ShopID = $row["ShopID"];

	$res333 = mysqli_query($con,"SELECT count(*) FROM ShopStory WHERE ShopID = '$ShopID' AND StoryStatus = 'ACTIVE'");
	while($row333 = mysqli_fetch_assoc($res333)){
		
		$storyCount = $row333["count(*)"];
		$row["StoryCount"] = $storyCount;
		if($storyCount==0){
			$row["HasStory"] = "NO";
		}
		
	}
	
	$result445[] = $row;
	$PostId    = $row["PostId"];
	$ProductID = $row["ProductID"];
	
	
	$isLiked = 0;
    $res5 = mysqli_query($con,"SELECT * FROM Likes WHERE PostID='$PostId' AND UserID='$UserID'");
        
        while($row5 = mysqli_fetch_assoc($res5)){
        
        //$data = $row[0];
        $result3[] = $row3;
        
        $isLiked = 1;
        
        }

     if($isLiked==0){
             $array = [
            "isLiked" => "no",
            ];
    }else{
         $array = [
            "isLiked" => "yes",
            ];
    }
	
	
	
	    $res44 = mysqli_query($con,"SELECT * FROM Foods WHERE FoodID ='$ProductID'");

$result2 = array();


$ii = 0;
while($row22 = mysqli_fetch_assoc($res44)){

//$data = $row[0];
$result2[] = $row22;


$FoodID = $row22["FoodID"];

$k = 0;

 $res24 = mysqli_query($con,"SELECT * FROM ExtraCategory WHERE ProductID='$FoodID'");

        $result3 = array();
        
        while($row33 = mysqli_fetch_assoc($res24)){
        
        //$data = $row[0];
        $result3[] = $row33;
        
        $test=4;
        
        
                $ExtraCategoryID = $row33["ExtraCategoryID"];
                
                
                ////////////////
                
                
                $res35 = mysqli_query($con,"SELECT * FROM ExtraInSideCategoty WHERE ExtraCategoryID='$ExtraCategoryID'");
    
                    $result35 = array();
                    
                    while($row35 = mysqli_fetch_assoc($res35)){
                    
                    //$data = $row[0];
                    $result35[] = $row35;
                        
                        
                        
                    }
                
                
                array_splice($result3[$k], 19, 20, array($result35));
            $k++;   
                
                
                /////////////////

        
        }

        
        array_splice($result2[$ii], 9, 10, array($result3));

$ii++;


$test=4;

}

    array_splice($result445[$i], 100, 101, array($array));
    
    

    
    array_splice($result445[$i], 101, 102, array($result2[0]));



$i++;
	
	
}

/////////////
//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 ,"products"=>$result,"shops"=>$result2,"reals"=>$result44,"POSTS"=>$result445,"message"=>$message));
}
else{
	

	$message ="No data";
    $success = true;
    $status_code = 200;
	//	$result = []; 
echo json_encode(array('status_code' => $status_code,'success' => $success ,"products"=>$result,"shops"=>$result2,"reals"=>$result44,"POSTS"=>$result445,"message"=>$message));
}
die;
mysqli_close($con);
?>