<?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 copyCurrentToInitial($db, $userRow, $taskID) {
        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 'ABORT COPY CURRENT TO INITIAL ROUTING (copy_current_to_initial_routing)::The task number (' . $taskID . ') to copy from current to initial is not valid.  Try a different TID. Aborting...';
            }

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

            // Attempt to run the delete query and evaluate the response
            if (!$db->queryDB($sql, $userRow, "copy_current_to_initial_routing occurance 10")){
                // Return an error string to be reported to the user
                return 'ABORT COPY CURRENT TO INITIAL ROUTING (copy_current_to_initial_routing)::Cannot delete the TID (' . $taskID . ') from the initial 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_initial ' .
                     '(TaskID, StatusID, ExecutionOrder, CompletionFactor, EstimatedTime, StatusNotes) ' .
                     'SELECT TaskID, StatusID, ROW_NUMBER() OVER() AS ExecutedOrder, CompletionFactor, EstimatedTime, StatusNotes FROM taskstatusinfo_current WHERE TaskID=' . $taskID . ' AND UseForInitialRouting = 1 ORDER BY ExecutionOrder;';

//return 'ABORT COPY CURRENT TO INITIAL ROUTING (copy_current_to_initial_routing)::' . $sql;
                // Run the insert query
                $db->queryDB($sql, $userRow, "copy_current_to_initial_routing occurance 11");
                
                // Let's create the update query to reset the flag query off of what we have
                $sql='UPDATE taskstatusinfo_current ' .
                     'SET UseForInitialRouting=0 ' .
                     'WHERE TaskID=' . $taskID . ';';

                // Run the update query
                $db->queryDB($sql, $userRow, "copy_current_to_initial_routing occurance 12");
            }
        } 
        catch (Exception $exc) {
            // Create the error string to return back to the caller
            return 'ABORT COPY CURRENT TO INITIAL ROUTING (copy_current_to_initial_routing)::There was an uncaught error while trying to copy initial to current routing for this task.  The exception is: ' . $exc->getMessage() . '. Aborting...';
        }
        
        // If we got here then assume success
        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 COPY CURRENT TO INITIAL ROUTING (copy_current_to_initial_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=copyCurrentToInitial($db, $userRow, $copyTaskID);

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