<?php 
    include_once dirname(__FILE__) . '/../database.php';
    include_once dirname(__FILE__) . '/../global_functions.php';
    
    function routeCheckTaskWithDirection($db, $userRow, $taskNumber,
                                                        $currentTaskStatusRoutingNodeID,
                                                        $currentMainBranchID,
                                                        $direction,
                                                        $currentChosenStatusID) {
        // Initialize the return
        $returnString='';
        
        try {
            // Initialize return message parameters
            $verificationMessage='';
            $confirmedGotoStatusID=((int)$currentChosenStatusID);
            $confirmedGotoMainBranchID=((int)$currentMainBranchID);
            $confirmedGotoMergeToBranchID=-1;
            $confirmedGotoTaskStatusRoutingInfoID=((int)$currentTaskStatusRoutingNodeID);
            $confirmedGotoStatusNote="";
            $estimatedTime=0;
            $actualTime=0;
            
            // 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 'ABORT PRECHECK ROUTE MOVING (precheck_route_move)::The task number (' . $taskNumber . ') is not valid. Cannot check if the status is valid. Aborting...';
            }

            if ($direction===null || !is_numeric($direction) || ((int)$direction)<-1 || ((int)$direction) >1){
                // Return an error string to be reported to the user
                return 'ABORT PRECHECK ROUTE MOVING (precheck_route_move)::The direction (' . $direction . ') to move the status is not valid. Aborting...';
            }

            // Setup a variable for the next status ID that would be on the trunk and set it to a bogus number
            $nextTrunkStatusID=-1;
            $nextTrunkStatusInfoID=-1;
            
            // Setup a variable for the previous status ID that would be on the trunk and set it to a bogus number
            $previousTrunkStatusID=-1;
            $previousTrunkStatusInfoID=-1;
            
            // Create the array variables to hold previous and next rows
            $nextRowAssoc=null;
            $previousRowAssoc=null;
            
            // The only time that we do NOT need to know what the next status is would be if we are going backwards, so get it for everyone else
            if (((int)$direction)>-1){
                // Create a query to determine what the previous main branch ID would be
                $sql='SELECT * FROM taskstatusinfo_current ' . 
                     'WHERE TaskID=' . $taskNumber . ' ' . 
                     'AND StatusCompleted <> 1 ' . 
                     'AND TaskStatusInfoID <> ' . $currentTaskStatusRoutingNodeID . ' ' .
                     'AND MainBranchID=0 ' .
                     'ORDER BY ExecutionOrder ' . 
                     'LIMIT 1;';

                // Run the select query
                $previousRow = $db->queryDB($sql, $userRow, "precheck_route_move.php occurance 1");

                // If there is a row, then I need to get what the status would be next on the trunk
               if ($previousRow != null && mysqli_num_rows($previousRow)==1){
                    // Get the row
                    $nextRowAssoc = $previousRow->fetch_assoc();

                    // Set the status ID as the next status ID
                    $nextTrunkStatusID = $nextRowAssoc["StatusID"];

                    // Set the status INFO ID as the next status info ID
                    $nextTrunkStatusInfoID = $nextRowAssoc["TaskStatusInfoID"];
                }
            }
                    
            // The only time that we do NOT need to what the previous status is would be if we are going forwards, so get it for everyone else
            if (((int)$direction)<1){
                // Create a query to determine what the next main branch ID would be
                $sql='SELECT * FROM taskstatusinfo_current ' . 
                     'WHERE TaskID=' . $taskNumber . ' ' . 
                     'AND StatusCompleted = 1 ' . 
                     'AND TaskStatusInfoID <> ' . $currentTaskStatusRoutingNodeID . ' ' .
                     'ORDER BY ExecutionOrder DESC ' . 
                     'LIMIT 1;';

                // Run the select query
                $previousRow = $db->queryDB($sql, $userRow, "precheck_route_move.php occurance 2");

                // If there is a row, then I need to get what the status was before
               if ($previousRow !== null && mysqli_num_rows($previousRow)==1){
                    // Get the row
                    $previousRowAssoc = $previousRow->fetch_assoc();

                    // Set the status ID as the previous status ID
                    $previousTrunkStatusID = $previousRowAssoc["StatusID"];

                    // Set the status INFO ID as the previous status info ID
                    $previousTrunkStatusInfoID = $previousRowAssoc["TaskStatusInfoID"];
                }
            }
            
            // If we are on the main path and just moving forward, then there 
            // should be no verification asked of the user, so check for this
            if ((((int)$currentMainBranchID)===0 && ((int)$direction)===1) ||
                (((int)$currentMainBranchID)===0 && ((int)$direction)===0 && $nextTrunkStatusID==((int)$currentChosenStatusID))){
                // Set the verification message to none
                $verificationMessage='';
                
                // Set the values that we need to change if the user says yes (No question should be asked on this) 
                $confirmedGotoStatusID=$nextTrunkStatusID;
                $confirmedGotoMainBranchID=((int)$currentMainBranchID);
                $confirmedGotoTaskStatusRoutingInfoID=$nextTrunkStatusInfoID;
                $confirmedGotoStatusNote=$nextRowAssoc["StatusNotes"];
            }
            else {
                // Now let's determine if we are going forward, backward or off-path with the move
                switch ((int)$direction){
                    case 0:
                        // Determine if the user has selected the same route as the next trunk ID
                        if ($nextTrunkStatusID==((int)$currentChosenStatusID)){
                            // Set the verification message to ask if they would like to go back to trunk.
                            $verificationMessage='would be the next state on the tasks trunk branch. Would you like to merge back to the trunk?';

                            // Set the values that we need to change if the user says yes 
                            $confirmedGotoStatusID=$nextTrunkStatusID;
                            $confirmedGotoMainBranchID=0;
                            $confirmedGotoTaskStatusRoutingInfoID=$nextTrunkStatusInfoID;
                            $confirmedGotoStatusNote=$nextRowAssoc["StatusNotes"];
                        }
                        else if (((int)$currentMainBranchID)===0){
                            // Set the verification message to let the know that they are leaving the trunk.
                            $verificationMessage='would take you off of the task routing path. Do you want to continue?';

                            // Set the values that we need to change if the user says yes 
                            $confirmedGotoStatusID=$currentChosenStatusID;
                            $confirmedGotoMainBranchID=((int)$currentTaskStatusRoutingNodeID);
                            $confirmedGotoTaskStatusRoutingInfoID=-1;
                            $confirmedGotoMergeToBranchID=$nextTrunkStatusInfoID;
                            $confirmedGotoStatusNote='There are no status notes for this phase since we are off the beaten path.';
                        }
                        else{
                            // Set the verification message to let the know that they continue to be off the path.
                            $verificationMessage='keeps it this routed task off of its routing path. Do you want to continue?';

                            // Set the values that we need to change if the user says yes 
                            $confirmedGotoStatusID=((int)$currentChosenStatusID);
                            $confirmedGotoMainBranchID=((int)$currentMainBranchID);
                            $confirmedGotoTaskStatusRoutingInfoID=-1;
                            $confirmedGotoMergeToBranchID=$nextTrunkStatusInfoID;
                            $confirmedGotoStatusNote='There are no status notes for this phase since we are off the beaten path.';
                        }
                        
                        // Create a query to see what the current status ID is and determine if the user is trying to set it the same as it is now
                        $sql='SELECT * FROM tasks ' . 
                              'WHERE TaskID=' . $taskNumber . ';';
                        
                        // Run the select query
                        $currentRow = $db->queryDB($sql, $userRow, "precheck_route_move.php occurance 3");

                        // If there is a row, then I need to get what the status was before
                        $currentStatusID=-1;
                        if ($currentRow != null && mysqli_num_rows($currentRow)==1){
                            // Get the row
                            $currentRowAssoc = $currentRow->fetch_assoc();

                            // get the current status ID
                            $currentStatusID = $currentRowAssoc["StatusID"];
                        }
                        
                        // Determine if they are tryint to go to the same status ID as they are in right now
                        if ($confirmedGotoStatusID==$currentStatusID){
                            // Let them know they are moving to a state that is the same as current
                            $verificationMessage='that you are moving to is the same status as you currently are in. Are you sure you wish to do that?';
                        }
                        
                        break;
                    case 1:
                        // Set the verification message to ask if they would like to go back to trunk.
                        $verificationMessage='would merge this task to the next routing trunk state.  Would you like to do this?';
                        
                        // Set the values that we need to change if the user says yes 
                        $confirmedGotoStatusID=$nextTrunkStatusID;
                        $confirmedGotoMainBranchID=0;
                        $confirmedGotoTaskStatusRoutingInfoID=$nextTrunkStatusInfoID;
                        $confirmedGotoStatusNote=$nextRowAssoc["StatusNotes"];
                        
                        break;
                    case -1:
                        // Determine if there is a routing state to go back to
                        if ($previousTrunkStatusInfoID>0){
                            // Set the verification message to ask if they would like to go back to trunk.
                            $verificationMessage='would take this task to the previous routing trunk state. Are you sure you wish to do this?';

                            // Set the values that we need to change if the user says yes 
                            $confirmedGotoStatusID=$previousTrunkStatusID;
                            $confirmedGotoTaskStatusRoutingInfoID=$previousTrunkStatusInfoID;
                            $confirmedGotoMainBranchID=$previousRowAssoc["MainBranchID"];
                            $confirmedGotoMergeToBranchID=$previousRowAssoc["MergedToBranchID"];
                            $confirmedGotoStatusNote='You are coming back from the path less taken, but these are the status notes for that state previously: ' . $previousRowAssoc["StatusNotes"];
                        }
                        else{
                            // Let them know that there is no previous state to go to.
                            return 'ABORT PRECHECK ROUTE MOVING (precheck_route_move)::There is no previous state to go back to.  Aborting...';
                        }
                        
                        break;
                }
            }
            
            // Create a query to get info about the current node in order to send back info
            $sql='SELECT *, (ActualTime+(IF(TimerStartDate IS NULL, 0, time_to_sec(timediff(NOW(),TimerStartDate))/3600))) AS CalculatedActualTime ' . 
                 'FROM taskstatusinfo_current ' . 
                 'WHERE TaskStatusInfoID = ' . $currentTaskStatusRoutingNodeID . ';';
            
            // Run the select query
            $currentRow = $db->queryDB($sql, $userRow, "precheck_route_move.php occurance 4");

            // If there is a row, then I need to get info on current route node
           if ($currentRow != null && mysqli_num_rows($currentRow)==1){
                // Get the row
                $currentRowAssoc = $currentRow->fetch_assoc();

                // Set the Estimated Time
                $estimatedTime = $currentRowAssoc["EstimatedTime"];

                // Set the Sctual Time as a calculation
                $actualTime = $currentRowAssoc["CalculatedActualTime"];
            }
            
            // Create a query to get the name of the final status ID
            $sql='SELECT Name FROM status WHERE StatusID=' . $confirmedGotoStatusID . ';';
            
            // Run the select query
            $statusRow = $db->queryDB($sql, $userRow, "precheck_route_move.php occurance 4");

            // If there is a row, then I need to get info on current route node
            $confirmedGotoStatusName='';
            if ($statusRow != null && mysqli_num_rows($statusRow)==1){
                // Get the row
                $statusRowAssoc = $statusRow->fetch_assoc();
                
                // Set the name of the status
                $confirmedGotoStatusName= strtoupper($statusRowAssoc["Name"]);
                
                // Determine if we have a verification message
                if ($verificationMessage!=''){
                    // Add the state name to the message
                    $verificationMessage='The chosen status of "' . $confirmedGotoStatusName . '" ' . $verificationMessage;
                }
                else {
                    // Set the verification message to be a normal one
                    $verificationMessage='Move the task routing to the next routing state of "' . $confirmedGotoStatusName . '".';
                }
            }
           
            // Create the return string
            $returnString=$verificationMessage . '::' . $confirmedGotoStatusID . '::' . $confirmedGotoTaskStatusRoutingInfoID . '::' . $confirmedGotoMainBranchID . '::' . $confirmedGotoMergeToBranchID . '::' . $confirmedGotoStatusNote. '::' . $estimatedTime. '::' . $actualTime . '::' . $direction . '::' . $confirmedGotoStatusName;
        } 
        catch (Exception $exc) {
            // Create the error string to return back to the caller
            return 'ABORT PRECHECK ROUTE MOVING (precheck_route_move)::There was an uncaught error attempting to change status.  The exception is: ' . $exc->getMessage() . '. Aborting...';
        }
        
        // If we got here then assume success
        return $returnString;
    }
    
    // Attempt to see which direction that they plan to go on the route
    function guessRouteDirectionByStatus($db, $userRow, $taskNumber,
                                                        $currentTaskStatusRoutingNodeID,
                                                        $currentChosenStatusID,
                                                        &$direction) {
        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 'ABORT PRECHECK ROUTE MOVING (precheck_route_move)::The task number (' . $taskNumber . ') is not valid. Cannot guess the next route node without it. Aborting...';
            }

            // Determine if we have a CURRENT Task Status Routing Node ID to check on.
            if ($currentTaskStatusRoutingNodeID===null || !is_numeric($currentTaskStatusRoutingNodeID) || ((int)$currentTaskStatusRoutingNodeID)<1){
                // Return an error string to be reported to the user
                return 'ABORT PRECHECK ROUTE MOVING (precheck_route_move)::The CURRENT Task Status Routing Node ID (' . $currentTaskStatusRoutingNodeID . ') is not valid. Cannot guess the next route node without it. Aborting...';
            }

            // Determine if we have a status ID to work on
            if ($currentChosenStatusID===null || !is_numeric($currentChosenStatusID) || ((int)$currentChosenStatusID)<1){
                // Return an error string to be reported to the user
                return 'ABORT PRECHECK ROUTE MOVING (precheck_route_move)::The status ID (' . $currentChosenStatusID . ') is not valid. Cannot guess the next route node without it. Aborting...';
            }

            // Create a query to get the rows around to include the current status routing node
            $sql='SELECT tsi.* , tsi2.ExecutionOrder AS CurrentExecutionOrder ' .
                 'FROM taskstatusinfo_current tsi ' .
                 'LEFT JOIN (SELECT ExecutionOrder FROM taskstatusinfo_current WHERE TaskStatusInfoID=' . $currentTaskStatusRoutingNodeID . ') tsi2 ON 1=1 ' .
                 'WHERE tsi.TaskID=' . $taskNumber . ' ' .
                 'AND tsi.ExecutionOrder BETWEEN tsi2.ExecutionOrder-1 AND tsi2.ExecutionOrder+1 ' .
                 'ORDER BY tsi.ExecutionOrder;';
            
            // Query the database for the secondary statuses 
            $rows = $db->queryDB($sql, $userRow, "task_presentation occurance 30");

            // Determine if there are any rows before attempting to loop through them
            $rowNumber=0;
            if ($rows != null){
                $row1=null;
                $row2=null;
                $row3=null;
                // Determine if there is only the one row
                if (mysqli_num_rows($rows)==1){
                    // Loop through the one row
                    while ($row=mysqli_fetch_array($rows)){
                        // Set the middle row to be the row
                        $row2=$row;
                    }
                }
                // Determine if there are only two rows
                else if (mysqli_num_rows($rows)==2){
                    // Loop through the two rows
                    $amount=1;
                    $startLocation=1;
                    while ($row=mysqli_fetch_array($rows)){
                        switch ($amount) {
                            case 1:
                                // First thing is to determine if we are on the CURRENT Task Status Routing Node ID. 
                                // Means that the current status is at the beginning of the route.
                                if (((int)$currentTaskStatusRoutingNodeID) == $row["TaskStatusInfoID"]){
                                    // Set the middle row to be this row
                                    $row2=$row;
                                }
                                else{
                                    // Set the previous row to be this row
                                    $row1=$row;
                                }
                                
                                // Break out of the switch statement
                                break;
                            case 2:
                                // First thing is to determine if we are on the CURRENT Task Status Routing Node ID
                                // Means that the current status is at the end the route.
                                if (((int)$currentTaskStatusRoutingNodeID) == $row["TaskStatusInfoID"]){
                                    // Set the middle row to be this row
                                    $row2=$row;
                                }
                                // Means that the current status is at the beginning of the route.
                                else {
                                    // Set the next row to be this row
                                    $row3=$row;
                                }

                                // Break out of the switch statement
                                break;
                            default:
                                break;
                        }

                        // Increment the amount field
                        $amount++;
                    }
                }
                // Determine if there are three rows
                else if (mysqli_num_rows($rows)==3){
                    // Loop through the three rows
                    while ($row=mysqli_fetch_array($rows)){
                        // Increasethe row number
                        $rowNumber++;    
                        
                        // Check which row we are on 
                        switch ($rowNumber) {
                            case 1:
                                // Set the first row to be this row
                                $row1=$row;

                                // Break out of the switch statement
                                break;
                            case 2:
                                // Set the second row to be this row
                                $row2=$row;

                                // Break out of the switch statement
                                break;
                            case 3:
                                // Set the third row to be this row
                                $row3=$row;

                                // Break out of the switch statement
                                break;
                            default:
                                break;
                        }
                    }
                }
                
                // At this point, really all I have to determine if they want to and can go backwards
                // Otherwise, I just set the direction as 0 to be going towards the standard of forward.
                if (((int)$direction)<0 && $row1!=null && $row1["StatusID"]==((int)$currentChosenStatusID)){
                    // Set the direction to go backwards
                    $direction=-1;
                }
                if (((int)$direction)>0 && $row3!=null && $row3["StatusID"]==((int)$currentChosenStatusID)){
                    // Set the direction to go forwards
                    $direction=1;
                }
                else {
                    // Set the direction equal to zero in order to let it be decided as the system sees fit
                    $direction=0;
                }
//return 'ABORT PRECHECK ROUTE MOVING (precheck_route_move)::' . $direction . '---' . $currentChosenStatusID . '--' . $row1["StatusID"] . '-' . $row2["StatusID"] . '-' . $row3["StatusID"];
            }
            else {
                // Create the error string to return back to the caller
                return 'ABORT PRECHECK ROUTE MOVING (precheck_route_move)::There are no route nodes found for this task. Cannot guess the next route node without a route. Aborting...';
            }
        } 
        catch (Exception $exc) {
            // Create the error string to return back to the caller
            return 'ABORT PRECHECK ROUTE MOVING (precheck_route_move)::There was an uncaught error attempting to change status.  The exception is: ' . $exc->getMessage() . '. Aborting...';
        }
    }
    
    // attempt to copy all tasks inside of or this particular task to the task requested
    $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 PRECHECK ROUTE MOVING (precheck_route_move)::Your session has expired.  ' . 
             'Refresh the page before cleaning this task.';
    }
    else {
        // Attempt to log in with this user
        $userRow = $currentUser->fetch_assoc();
        
        // Set the return string to nothing
        $returnString='';
        
        // Set defaults for the passed in variables
        $taskNumber=-1;
        $currentTaskStatusRoutingNodeID=-1;
        $currentMainBranchID=0;
        $direction=null;
        $calculatedDirection=null;
        $currentChosenStatusID=-1;
                    
        // 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 Main Branch ID
        if (isset($_GET['currentMainBranchID']) ){
            // get the passed in Main Branch ID
            $currentMainBranchID = $_GET['currentMainBranchID'];
        }

        // 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 chosen status ID
        if (isset($_GET['currentChosenStatusID']) ){
            // get the passed in chosen Status ID
            $currentChosenStatusID = $_GET['currentChosenStatusID'];
        }

        // Determine if they want us to determine the direction. 
        // Negative is biased to the previous state. Positive is biased to the forward state.  NULL is don't care.
        if (abs($direction)==9999 || $direction===null){
            // They want us to figure out the direction, so try to figureit out for them.
            $returnString=guessRouteDirectionByStatus($db, $userRow, $taskNumber,
                                                                     $currentTaskStatusRoutingNodeID,
                                                                     $currentChosenStatusID,
                                                                     $direction);
        }
        
        // Ensure that we are good to go and that no errors are alread made from previous methods.
        if (trim($returnString)==''){
            // Attempt to clean the task of the task passed in.
            $returnString=routeCheckTaskWithDirection($db, $userRow, $taskNumber,
                                                                     $currentTaskStatusRoutingNodeID,
                                                                     $currentMainBranchID,
                                                                     $direction,
                                                                     $currentChosenStatusID);
        }
        
        // return the result
        echo $returnString;
    }
    
?>