<?php 
    include_once dirname(__FILE__) . '/../database.php';
    include_once dirname(__FILE__) . '/../global_functions.php';
    
    // attempt to copy all tasks inside of or this particular task to the task requested
    function copyInitialToCurrent($db, $userRow, $taskID) {
        $firstRoutingNodeAssocRow=null;
        try {
            // Determine if we have an update task number to work on
            if ($taskID==null || !is_numeric($taskID) || $taskID<1){
                // Return an error string to be reported to the user
                return '-1::ABORT COPY INITIAL TO CURRENT ROUTING (copy_initial_to_current_routing)::The task number (' . $taskID . ') to copy from initial to current is not valid.  Try a different TID. Aborting...';
            }

            // Delete all with this task ID in the current table
            $sql='DELETE FROM taskstatusinfo_current ' .
                 'WHERE TaskID=' . $taskID . ';';

            // Attempt to run the delete query and evaluate the response
            if (!$db->queryDB($sql, $userRow, "copy_initial_to_current_routing occurance 10")){
                // Return an error string to be reported to the user
                return '-1::ABORT COPY INITIAL TO CURRENT ROUTING (copy_initial_to_current_routing)::Cannot delete the TID (' . $taskID . ') from the current routing table.  Contact the TMS admin for troubleshooting. Aborting...';
            }
            else {
                // Let's create the insert query off of what we have
                $sql='INSERT INTO taskstatusinfo_current ' .
                     '(TaskID, StatusID, ExecutionOrder, CompletionFactor, EstimatedTime, StatusNotes, InitialStatusInfoID) ' .
                     'SELECT TaskID, StatusID, ExecutionOrder, CompletionFactor, EstimatedTime, StatusNotes, TaskStatusInfoID FROM taskstatusinfo_initial WHERE TaskID=' . $taskID . ';';

                // Run the insert query
                $db->queryDB($sql, $userRow, "copy_initial_to_current_routing occurance 11");
                
                // Create a query to get the first status ID in execution order
                $sql='SELECT StatusID, TaskStatusInfoID FROM taskstatusinfo_current WHERE TaskID=' . $taskID . ' ORDER BY ExecutionOrder LIMIT 1;';

                // Run the select query
                $firstRoutingNodeRow=$db->queryDB($sql, $userRow, "copy_initial_to_current_routing occurance 12");
                
                // Ensure that the query came back well
                $firstTaskStatusInfoID=-1;
                if (mysqli_num_rows($firstRoutingNodeRow)==1){
                    // Get the query as an array
                    $firstRoutingNodeAssocRow = $firstRoutingNodeRow->fetch_assoc();
                
                    if ($returnValue!=""){
                        // Return the value
                        return $firstRoutingNodeAssocRow["StatusID"] . '::ABORT COPY INITIAL TO CURRENT ROUTING (copy_initial_to_current_routing)::' . $returnValue;
                    }
                    
                    // Create a query to update the task to the first routing node
                    $sql='UPDATE tasks ' .
                         'SET CurrentTaskStatusRoutingNodeID=' . $firstRoutingNodeAssocRow["TaskStatusInfoID"] . ' ' . 
                         'WHERE TaskID=' . $taskID .';';

                    // Run the update query
                    $db->queryDB($sql, $userRow, "copy_initial_to_current_routing occurance 12");
                    
                    // Create a query to update the current routing now to start the timer
                    $sql='UPDATE taskstatusinfo_current ' .
                         'SET TimerStartDate=NOW() ' . 
                         'WHERE TaskStatusInfoID=' . $firstRoutingNodeAssocRow["TaskStatusInfoID"] .';';

                    // Run the update query
                    $db->queryDB($sql, $userRow, "copy_initial_to_current_routing occurance 13");
                }
                else if (mysqli_num_rows($firstRoutingNodeRow)==0){
                    // Inform them that the current was cleared
                    return $firstRoutingNodeAssocRow["StatusID"] . '::COPY INITIAL TO CURRENT ROUTING INFO (copy_initial_to_current_routing)::Current routing was cleared of all routing nodes.';
                }
                else {
                    // Create the error string to return back to the caller
                    return '-1::ABORT COPY INITIAL TO CURRENT ROUTING (copy_initial_to_current_routing)::There was an uncaught error while trying get the current status for this task. Aborting...';
                }
            }
        } 
        catch (Exception $exc) {
            // Create the error string to return back to the caller
            return '-1::ABORT COPY INITIAL TO CURRENT ROUTING (copy_initial_to_current_routing)::There was an uncaught error while trying to copy initial to current routing for this task.  The exception is: ' . $exc->getMessage() . '. Aborting...';
        }
        
        // Determine if we managed to get the first routing node
        if ($firstRoutingNodeAssocRow!=null){
            // If we got here then assume success
            return $firstRoutingNodeAssocRow["StatusID"];
        }
        else {
            // If this query never returned a value, then cannot have been a success. send back a negative number
            return '-1';
            
        }
    }
    
    $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 COPY INITIAL TO CURRENT ROUTING (copy_initial_to_current_routing)::' .
             'Your session has expired. Refresh the page before cleaning this task.';
    }
    else {
        // Attempt to log in with this user
        $userRow = $currentUser->fetch_assoc();
        
        // Set defaults for the passed in variables
        $copyTaskID=-1;
        
        // check the passed in copy task ID
        if (isset($_GET['copyTaskID']) ){
            // get the passed in copy task ID
            $copyTaskID = $_GET['copyTaskID'];
        }

        // Attempt to clean the task of the task passed in.
        $returnString=copyInitialToCurrent($db, $userRow, $copyTaskID);

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