<?php
    require_once("../../php/db_utils.php");
    
    try {
        // Connect to the database
        $database = db_connect();
        
        // Incoming data
        $tag = $_POST["tag"];
        $description = $_POST["description"];
        $canvasId = $_POST["canvas_id"];
        
        // Check if the tag already exists
        $query = "SELECT tag FROM tags WHERE tag = '" . $tag . "' AND canvas_id = '" . $canvasId . "';";
        
        $recordSet = db_query_return($database, $query);
        
        $record = mysqli_fetch_assoc($recordSet);
        $tagCheck = $record["tag"];
        mysqli_free_result($recordSet);
        
        // If the tag already exists in the database
        if($tagCheck == $tag) {
            // Update description
            $query = "UPDATE tags SET description='" . $description . "' WHERE tag='" . $tag . "' AND canvas_id='" . $canvasId . "';";
        }
        // Else if the tag is new
        else {
            // Add new tag
            $query = "INSERT INTO tags (tag, description, canvas_id) VALUES ('" . $tag . "', '" . $description . "', '" . $canvasId . "');";
        }
        
        // Insert new or update old description
        db_query_no_return($database, $query);
        
        // Close the connection to the database
        db_close($database);
    }
    catch(Exception $e) {
        $errorMsg = $e->getMessage();
        print_r($errorMsg);
    }
?>