<?php
    require_once("../../php/db_utils.php");
    
    try {
        // Connect to the database
        $database = databaseConnect();
        
        // Incoming data
        $tag = $_POST["tag"];
        $description = $_POST["description"];
        $username = $_POST["username"];
        
        // Check if tag already exists
        $query = "SELECT tag FROM tags WHERE tag = '" . $tag . "' AND username = '" . $username . "';";
        
        $recordSet = databaseQueryWithReturn($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 username='" . $username . "';";
        }
        // Else if the tag is new
        else {
            // Add new tag
            $query = "INSERT INTO tags (tag, description, username) VALUES ('" . $tag . "', '" . $description . "', '" . $username . "');";
        }
        
        // Insert new or update old description
        databaseQueryNoReturn($database, $query);
        
        // Close the connection to the database
        databaseClose($database);
    }
    catch(Exception $e) {
        $errorMsg = $e->getMessage();
        print_r($errorMsg);
    }
?>