<?php 
    include_once dirname(__FILE__) . '/../database.php';
    include_once dirname(__FILE__) . '/../global_functions.php';
    
    // attempt to delete the full route
    function updateTaskStatusRouteName($db, $userRow, $tidToUpdate, $routingTemplateName) {
        try {
            // Determine if we have a route to update and name to update to
            if ($tidToUpdate!=null && $tidToUpdate!="" && is_numeric($tidToUpdate) && $tidToUpdate>0 && 
                $routingTemplateName!=null && trim($routingTemplateName)!=""){
                // Create a query to delete the selected route fully
                $sql='UPDATE tasks ' . 
                     'SET LastAppliedRouteTitle="' . $routingTemplateName . '" ' . 
                     'WHERE TaskID = ' . $tidToUpdate . ';';

                // Run the delete query
                $db->queryDB($sql, $userRow, "update_task_routing_template_name Form occurance 1");
            }
        } 
        catch (Exception $exc) {
            // Create the error string to return back to the caller
            return 'ABORT UPDATE TASK STATUS ROUTE NAME (update_task_routing_template_name)::There was an uncaught error while trying to update the last task status route name.  The exception is: ' . $exc->getMessage() . '. Update aborted...';
        }
        
        // If we got here then assume nothing
        return '';
    }
    
    $db = new Database();
    $db->setupTmsDB();
    
    // Set defaults for the passed in variables
    $sessionID=-1;

    // check the passed in session ID
    if (isset($_GET['sessionID']) ){
        // get the passed in session ID
        $sessionID = $_GET['sessionID'];
    }

    // Attempt to log in with this user
    $currentUser = $db->getLoggedInSessionUser($sessionID);
    if (mysqli_num_rows($currentUser)!=1){
        echo 'ABORT UPDATE TASK STATUS ROUTE (update_task_routing_template_name)::Your session has expired.  ' . 
             'Refresh the page before updating route name.';
    }
    else {
        // Attempt to log in with this user
        $userRow = $currentUser->fetch_assoc();
        
        // Set defaults for the passed in variables
        $updateTaskNumber=-1;
        $tidToUpdate='';
        // check the passed in ID to update
        if (isset($_GET['updateTaskNumber']) ){
            // get the passed in ID to update
            $tidToUpdate = $_GET['updateTaskNumber'];
        }
        
        // check the passed in name to update
        if (isset($_GET['routingTemplateName']) ){
            // get the passed in name to update
            $routingTemplateName = $_GET['routingTemplateName'];
        }
        
        // Attempt to delete the status route they requested
        $returnString=updateTaskStatusRouteName($db, $userRow, $tidToUpdate, $routingTemplateName);

        // return the result
        echo $returnString;
    }
    
?>