<?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 moveRouteAsDirected($db, $userRow, $taskNumber,
                                                $currentTaskStatusRoutingNodeID,
                                                $direction,
                                                $completionFeedbackNotes,
                                                $autoAppendedNotes,
                                                $gotoStatusID,
                                                $gotoTaskStatusRoutingInfoID,
                                                $gotoMainBranchID,
                                                $gotoMergeToBranchID) {
        // Initialize the return to be the goto status ID
        $returnString=$gotoStatusID;
        
        try {
            // Determine if we have a task number to work on
            if ($taskNumber==null || !is_numeric($taskNumber) || $taskNumber<1){
                // Return an error string to be reported to the user
                return '-1::ABORT MOVE ROUTE ONWARDS (move_route_onwards)::The task number (' . $taskNumber . ') is not valid. Cannot check if the status is valid. Aborting move...';
            }

            // Determine if we have a current status info node to work on
            if ($currentTaskStatusRoutingNodeID==null || !is_numeric($currentTaskStatusRoutingNodeID) || $currentTaskStatusRoutingNodeID<1){
                // Return an error string to be reported to the user
                return '-1::ABORT MOVE ROUTE ONWARDS (move_route_onwards)::The current status info node (' . $currentTaskStatusRoutingNodeID . ') is not valid. Cannot move if not valid. Aborting move...';
            }

            // Determine if we have a valid go to status ID to work on
            if ($gotoStatusID==null || !is_numeric($gotoStatusID) || $gotoStatusID<1){
                // Return an error string to be reported to the user
                return '-1::ABORT MOVE ROUTE ONWARDS (move_route_onwards)::The status to go to is not valid. Cannot move if not valid. Aborting move...';
            }

            // Determine if we have a valid go to main branch to work on
            if ($gotoMainBranchID==null || !is_numeric($gotoMainBranchID) || $gotoMainBranchID<0){
                // Return an error string to be reported to the user
                return '-1::ABORT MOVE ROUTE ONWARDS (move_route_onwards)::The main branch routing node (' . $gotoMainBranchID . ') is not valid. Cannot move if not valid. Aborting move...';
            }

            // Determine if we have a valid merge to branch ID to work on
            if ($gotoMergeToBranchID==null || !is_numeric($gotoMergeToBranchID) || $gotoMergeToBranchID<-1){
                // Return an error string to be reported to the user
                return '-1::ABORT MOVE ROUTE ONWARDS (move_route_onwards)::The merge to branch routing node (' . $gotoMergeToBranchID . ') is not valid. Cannot move if not valid. Aborting move...';
            }

            // Determine if we have an appropriate direction
            if ($direction==null || !is_numeric($direction) || $direction<-1 || $direction >1){
                // Return an error string to be reported to the user
                return '-1::ABORT MOVE ROUTE ONWARDS (move_route_onwards)::The direction to move the status is not valid. Aborting move...';
            }
            
            // Define some variables to be used later
            $newCurrentTaskStatusRoutingNodeID=$gotoTaskStatusRoutingInfoID;
            
            // Get the current date string
            $currentDate = new DateTime();
            $currentDate->modify('-1 hour');
            $currentDateString = $currentDate->format('Y-m-d H:i:s');

            // Determine if the route is going backwards
            $currentCompletedSQL='1';
            if ($direction==-1){
                // Ensure this one is NOT completed
                $currentCompletedSQL='0';
            }
            
            // Get the current routing node that we are for reference
            $sql='SELECT *, ExecutionOrder+0.001 AS NewExecutionOrder FROM taskstatusinfo_current WHERE TaskStatusInfoID=' . $currentTaskStatusRoutingNodeID . ';';
            
            // Run the select query
            $currentRow = $db->queryDB($sql, $userRow, "move_route_onwards occurance 2");

            // Get the row
            $currentRowAssoc = $currentRow->fetch_assoc();

            // Make a query to close the current routing node
            $sql='UPDATE taskstatusinfo_current ' .
                  'SET ActualTime=ActualTime+(IF(TimerStartDate IS NULL, 0, time_to_sec(timediff(NOW(),TimerStartDate))/3600)), StatusCompleted=' . $currentCompletedSQL . ', TimerStartDate=NULL ';
            if ($completionFeedbackNotes!=null && $completionFeedbackNotes!="") {$sql = $sql . ', CompletionFeedbackNotes=CONCAT(CompletionFeedbackNotes, "\n\n' . $currentDateString . ': ' . $completionFeedbackNotes . '") ';}
            if ($autoAppendedNotes!=null && $autoAppendedNotes!="") {$sql = $sql . ', AutoAppendedNotes=CONCAT(AutoAppendedNotes, "\n\n' . $currentDateString . ': ' . $autoAppendedNotes . '") ';}
            $sql=$sql . 'WHERE TaskStatusInfoID=' . $currentTaskStatusRoutingNodeID . ';';

//return '-1::ABORT MOVE ROUTE ONWARDS (move_route_onwards)::' . $sql;
            // Run the update query
            $db->queryDB($sql, $userRow, "move_route_onwards occurance 1");
            
            // Now determine if we are making a new task
            if ($gotoTaskStatusRoutingInfoID==-1){
                // Create a SQL to insert the new row
                $sql = 'INSERT INTO taskstatusinfo_current (';
                $sql = $sql . 'TaskID, StatusID, ExecutionOrder, TimerStartDate ';
                if ($gotoMainBranchID!=null && $gotoMainBranchID>0) {$sql = $sql . ', MainBranchID';}
                if ($gotoMergeToBranchID!=null && $gotoMergeToBranchID>0) {$sql = $sql . ', MergedToBranchID';}
                if ($autoAppendedNotes!=null && $autoAppendedNotes!="") {$sql = $sql . ', AutoAppendedNotes';}
                $sql = $sql . ') ';
                $sql = $sql . 'VALUES (' . $taskNumber . ', ' . $gotoStatusID . ', ' . $currentRowAssoc["NewExecutionOrder"] . ', NOW() ';
                if ($gotoMainBranchID!=null && $gotoMainBranchID>0) {$sql = $sql . ', ' . $gotoMainBranchID;}
                if ($gotoMergeToBranchID!=null && $gotoMergeToBranchID>0) {$sql = $sql . ', ' . $gotoMergeToBranchID;}
                if ($autoAppendedNotes!=null && $autoAppendedNotes!="") {$sql = $sql . ', CONCAT(AutoAppendedNotes, "' . $currentDateString . ': ' . $autoAppendedNotes . '") ';}
                $sql = $sql . ');';

                // Attempt to run the query and evaluate the response
                if (!$db->queryDB($sql, $userRow,  "move_route_onwards occurance 3")){
                    // Let them know we are unable to insert the new routing node
                    return '-1::ABORT MOVE ROUTE ONWARDS (move_route_onwards)::Unable to add the new routing node off the beaten path. Aborting move...';
                }
                else {
                    // Get the most recent ID (company)
                    $newCurrentTaskStatusRoutingNodeID = mysqli_insert_id($db->getDBConnection());
                }
            }
            else {
                // Make an update to change modified characteristics
                $sql='UPDATE taskstatusinfo_current SET ';
                $sql = $sql . '	StatusCompleted=0, TimerStartDate=NOW()';
                if ($autoAppendedNotes!=null && $autoAppendedNotes!="") {$sql = $sql . ', AutoAppendedNotes=CONCAT(AutoAppendedNotes,"\n\n' . $currentDateString . ': ' . $autoAppendedNotes . '")';}
                $sql=$sql .' WHERE TaskStatusInfoID=' . $gotoTaskStatusRoutingInfoID . ';';

                // Run the update query
                $db->queryDB($sql, $userRow, "updateTask Form occurance 4");
            }
            
            // Create the query to update the task with the appropriate info
            $sql='UPDATE tasks ' . 
                 'SET CurrentTaskStatusRoutingNodeID=' . $newCurrentTaskStatusRoutingNodeID . ', ' . 
                     'LastUpdatedByID=' . $userRow["UserID"] . ', ' . 
                     'LastUpdated=NOW() ' . 
                 'WHERE TaskID=' . $taskNumber . ';';
            
            // Run the update query
            $db->queryDB($sql, $userRow, "updateTask Form occurance 4");
            
            if ($returnValue!=""){
                // Return the value
                return '-1::ABORT MOVE ROUTE ONWARDS (move_route_onwards)::' . $returnValue;
            }
        } 
        catch (Exception $exc) {
            // Create the error string to return back to the caller
            return '-1::ABORT MOVE ROUTE ONWARDS (move_route_onwards)::There was an uncaught error attempting to change status.  The exception is: ' . $exc->getMessage() . '. Aborting...';
        }
        
        // If we got here then assume success
        return $returnString;
    }
    
    $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 '-1::ABORT MOVE ROUTE ONWARDS (move_route_onwards)::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
        $taskNumber=-1;
        $currentTaskStatusRoutingNodeID=-1;
        $direction=null;
        $gotoStatusID=-1;
        $gotoTaskStatusRoutingInfoID=-1;
        $gotoMainBranchID=-1;
        $gotoMergeToBranchID=-2;
        $completionFeedbackNotes=null; 
        $autoAppendedNotes=null;
                    
        // check the passed in task ID
        if (isset($_GET['taskNumber']) ){
            // get the passed in task ID
            $taskNumber = $_GET['taskNumber'];
        }

        // check the passed in routing node info
        if (isset($_GET['currentTaskStatusRoutingNodeID']) ){
            // get the passed in routing node info
            $currentTaskStatusRoutingNodeID = $_GET['currentTaskStatusRoutingNodeID'];
        }

        // check the passed in direction they are wanting to go
        if (isset($_GET['direction']) ){
            // get the passed in direction they are wanting to go
            $direction = $_GET['direction'];
        }

        // check the passed in completion notes
        if (isset($_GET['completionFeedbackNotes']) ){
            // get the passed in completion notes
            $completionFeedbackNotes=$_GET['completionFeedbackNotes'];
        }

        // check the passed in GoTo Status Info ID
        if (isset($_GET['gotoStatusID']) ){
            // get the passed in GoTo Status Info ID
            $gotoStatusID = $_GET['gotoStatusID'];
        }

        // check the passed in GoTo Task Status Info ID
        if (isset($_GET['gotoTaskStatusRoutingInfoID']) ){
            // get the passed in GoTo Task Status Info ID
            $gotoTaskStatusRoutingInfoID = $_GET['gotoTaskStatusRoutingInfoID'];
        }

        // check the passed in GoTo Main Status Info ID
        if (isset($_GET['gotoMainBranchID']) ){
            // get the passed in GoTo Main Status Info ID
            $gotoMainBranchID = $_GET['gotoMainBranchID'];
        }

        // check the passed in GoTo Merged Status Info ID
        if (isset($_GET['gotoMergeToBranchID']) ){
            // get the passed in GoTo Merged Status Info ID
            $gotoMergeToBranchID = $_GET['gotoMergeToBranchID'];
        }

        // check the passed in auto appended notes
        if (isset($_GET['autoAppendedNotes']) ){
            // get the passed in auto appended notes
            $autoAppendedNotes=$_GET['autoAppendedNotes'];
        }

//echo 'ABORT MOVE ROUTE ONWARDS (move_route_onwards)::' . $completionFeedbackNotes . '--' . $autoAppendedNotes;
        // Attempt to clean the task of the task passed in.
        $returnString=moveRouteAsDirected($db, $userRow, $taskNumber,
                                                         $currentTaskStatusRoutingNodeID,
                                                         $direction,
                                                         $completionFeedbackNotes,
                                                         $autoAppendedNotes,
                                                         $gotoStatusID,
                                                         $gotoTaskStatusRoutingInfoID,
                                                         $gotoMainBranchID,
                                                         $gotoMergeToBranchID);

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