<?php
require('includes/cmain.inc.php');

// Check if the search term is provided in the URL
if (isset($_GET['search'])) {
    // Get the search term from the URL
    $search_result = $_GET['search'];
    // Split the search query into separate words
   $search_terms = explode(" ", $search_result);

    // Construct the SQL query dynamically
   $sql_parts = array();
    foreach ($search_terms as $term) {
    $sql_parts[] = "country_name LIKE '%$term%'";
    }
    $sql_condition = implode(" OR ", $sql_parts);
    // Prepare SQL query to fetch related terms from the database
   // $sql = "SELECT country_name,country_url FROM tbl_country WHERE parent_childs!='0' AND  country_name LIKE '%$search_result%' Limit 0,7";
   $sql="SELECT * FROM tbl_country WHERE $sql_condition and parent_childs!='0' Limit 0,10";
    //print_r($search_result);exit();
    $sqlquery = db_query($sql);

    // Fetch related terms into an array
    $relatedTerms = [];
    while ($row = mysqli_fetch_assoc($sqlquery)) {
        // Create URL for each country name
        $slug = strtolower(str_replace(" ", "-", $row['country_url']));
        $url = SITE_WS_PATH . '/' . $slug;

        // Add the country name and URL to the related terms array
        $relatedTerms[] = ['name' => ucwords($row['country_name']), 'url' => $url];
    }

    // Respond with JSON containing related terms
    header('Content-Type: application/json');
    echo json_encode(['relatedTerms' => $relatedTerms]);
} else {
    // If search term is not provided, return an empty array
    echo json_encode(['relatedTerms' => []]);
}
?>
