<?php
    require_once("../../php/db_utils.php");
    
    try {
        // Connect to the database
        $database = db_connect();
        
        // Incoming data
        $currentTag = $_POST["tag"];
        $canvasId = $_POST["canvas_id"];
        
        // Declare query
        $query = "SELECT tag, description, canvas_id FROM tags WHERE NOT canvas_id='" . $canvasId . "' ORDER BY tag;";
        
        // Run query
        $recordSet = db_query_return($database, $query);
        
        // Get similar tags
        $tags = Array();
        
        $index = 0;
        
        while($record = $recordSet->fetch_assoc()) {
            $percentage;
            
            similar_text($currentTag, $record["tag"], $percentage);
            
            if($percentage > 75) {
                $tags[$index]["tag"] = $record["tag"];
                $tags[$index]["description"] = $record["description"];
                $tags[$index]["canvas_id"] = $record["canvas_id"];
                $tags[$index]["percentage"] = $percentage;
                $index++;
            }
        }
        
        // Sort tags by relevance
        function sortByRelevance($a, $b) {
            return $b["percentage"] - $a["percentage"];
        }
        
        usort($tags, "sortByRelevance");
        
        mysqli_free_result($recordSet);
        
        echo(json_encode($tags));
        
        // Close the connection to the database
        db_close($database);
    }
    catch(Exception $e) {
        $errorMsg = $e->getMessage();
        print_r($errorMsg);
    }
?>