<?php
    require_once("../../php/db_utils.php");
    
    try {
        // Connect to the database
        $database = db_connect();
        
        // Incoming data
        $canvasId = $_POST["canvas_id"];
        $username = $_POST["username"];
        $collaborator = $_POST["collaborator"];
        
        // Check if the collaborator already exists
        $query = "SELECT * FROM collaborators WHERE canvas_id = '" . $canvasId . "' AND owner = '" . $username . "' AND collaborator = '" . $collaborator . "';";
        
        $recordSet = db_query_return($database, $query);
        
        $record = mysqli_fetch_assoc($recordSet);
        $collaboratorCheck = $record["collaborator"];
        mysqli_free_result($recordSet);
        
        // If the tag already exists in the database
        if($collaboratorCheck == null) {
            // Add collaborator
            $query = "INSERT INTO collaborators (canvas_id, owner, collaborator) VALUE ('" . $canvasId . "', '" . $username . "', '" . $collaborator . "');";
            echo(1);
        }
        else if($collaboratorCheck == $collaborator) {
            echo(2);
        }
        else {
            echo(3);
        }
        
        // 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);
    }
?>