<?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 modifyStatusInfoNode($db, $userRow, $taskID,
                                                 $taskStatusInfoID,
                                                 $taskStatusInfoMainBranchID,
                                                 $taskStatusInfoMergedToBranchID,
                                                 $statusID,
                                                 $statusInfoEstimatedTime,
                                                 $statusInfoActualTime,
                                                 $statusInfoCompletionFactor,
                                                 $statusInfoNote,
                                                 $executionOrder,
                                                 $statusInfoIsTemplate, 
                                                 $statusInfoRoutingTemplateName,
                                                 $autoAppendedNotes) {
        try {
            // Determine if we have an update task number to work on
            if ($statusInfoIsTemplate==0 && ($taskID==null || !is_numeric($taskID) || $taskID<1)){
                // Return an error string to be reported to the user
                return 'ABORT UPDATE STATUS INFO NODE (update_route_node)::The task number (' . $taskID . ') to add status info nodes is not valid.  Try a different TID. Aborting...';
            }

            // Determine if we have a template asked for without a name
            if ($statusInfoIsTemplate==1 && ($statusInfoRoutingTemplateName==null || $statusInfoRoutingTemplateName=="")){
                // Return an error string to be reported to the user
                return 'ABORT UPDATE STATUS INFO NODE (update_route_node)::Cannot save a template node without a template name. Aborting...';
            }

            // Determine if we have a status ID to work on
            if ($statusID==null || !is_numeric($statusID) || $statusID<1){
                // Return an error string to be reported to the user
                return 'ABORT UPDATE STATUS INFO NODE (update_route_node)::The status ID (' . $statusID . ') to add status info nodes is not valid.  Try a different Status ID. Aborting...';
            }

            // Determine if we have a valid status info ID to work on
            if ($taskStatusInfoID==null || !is_numeric($taskStatusInfoID) || $taskStatusInfoID<1){
                // This should mean that we are adding a status route node.  Now check for elements that need to be there to add
                if ($executionOrder==null || !is_numeric($executionOrder) || $executionOrder<1){
                    // Return an error string to be reported to the user
                    return 'ABORT UPDATE STATUS INFO NODE (update_route_node)::There must be an execution order to add a node. Try again. Aborting...';
                }
                
                // Determine if this is to be inserted as a template
                if ($statusInfoIsTemplate==1 && $statusInfoRoutingTemplateName!= null && $statusInfoRoutingTemplateName != ''){
                    // If there is already a task ID means it is a current template
                    if (((int)$taskID)<0){
                        // Set the SQL to the ID already in the table
                        $valuesSQL = 'SELECT ' . $taskID . ', ' . $statusID . ', ' . $executionOrder. ', 1, "' . $statusInfoRoutingTemplateName . '" ';
                        if ($statusInfoCompletionFactor!=null && $statusInfoCompletionFactor>0) {$valuesSQL = $valuesSQL . ', ' . $statusInfoCompletionFactor;}
                        if ($statusInfoEstimatedTime!=null && $statusInfoEstimatedTime>0) {$valuesSQL = $valuesSQL . ', ' . $statusInfoEstimatedTime;}
                        if ($statusInfoActualTime!=null && $statusInfoActualTime>0) {$valuesSQL = $valuesSQL . ', ' . $statusInfoActualTime;}
                        if ($taskStatusInfoMainBranchID!=null && $taskStatusInfoMainBranchID>0) {$valuesSQL = $valuesSQL . ', ' . $taskStatusInfoMainBranchID;}
                        if ($taskStatusInfoMergedToBranchID!=null && $taskStatusInfoMergedToBranchID>0) {$valuesSQL = $valuesSQL . ', ' . $taskStatusInfoMergedToBranchID;}
                        $valuesSQL = $valuesSQL . ', "' . $statusInfoNote . '";';
                    }
                    else {
                        // Determine if there was already a node added with this ID
                        
                        // Create a query to get the current template name ID
                        $sql = 'SELECT TaskID FROM taskstatusinfo_initial WHERE RoutingTitle= "' . $statusInfoRoutingTemplateName . '" GROUP BY TaskID;';

                        // Run the select query
                        $row = $db->queryDB($sql, $userRow, "updateTask Form occurance 1");

                        // If there is a row rows, then we need to get that ID and set that as the ID to use
                        $taskIDSQL='SELECT IF (MIN(TaskID)>-1, -1, MIN(TaskID)-1)';
                        if ($row != null && mysqli_num_rows($row)==1){
                            // Get the row
                            $rowAssoc = $row->fetch_assoc();
                            
                            // Set the task ID as the one with this name
                            $taskIDSQL = 'SELECT DISTINCT ' . $rowAssoc["TaskID"];
                        }
                        
                        // Create the values query as though we have to make an ID.
                        $valuesSQL=$taskIDSQL . ', ' . $statusID . ', ' . $executionOrder. ', 1, "' . $statusInfoRoutingTemplateName . '" ';
                        if ($statusInfoCompletionFactor!=null && $statusInfoCompletionFactor>0) {$valuesSQL = $valuesSQL . ', ' . $statusInfoCompletionFactor;}
                        if ($statusInfoEstimatedTime!=null && $statusInfoEstimatedTime>0) {$valuesSQL = $valuesSQL . ', ' . $statusInfoEstimatedTime;}
                        if ($statusInfoActualTime!=null && $statusInfoActualTime>0) {$valuesSQL = $valuesSQL . ', ' . $statusInfoActualTime;}
                        if ($taskStatusInfoMainBranchID!=null && $taskStatusInfoMainBranchID>0) {$valuesSQL = $valuesSQL . ', ' . $taskStatusInfoMainBranchID;}
                        if ($taskStatusInfoMergedToBranchID!=null && $taskStatusInfoMergedToBranchID>0) {$valuesSQL = $valuesSQL . ', ' . $taskStatusInfoMergedToBranchID;}
                        $valuesSQL = $valuesSQL . ', "' . $statusInfoNote . '" FROM taskstatusinfo_initial;';
                    }
                    
                    // Let's create the insert query off of what we have
                    $sql='INSERT INTO taskstatusinfo_initial (';
                    $sql = $sql . 'TaskID, StatusID, ExecutionOrder, IsRoutingTemplate, RoutingTitle ';
                    if ($statusInfoCompletionFactor!=null && $statusInfoCompletionFactor>0) {$sql = $sql . ', CompletionFactor';}
                    if ($statusInfoEstimatedTime!=null && $statusInfoEstimatedTime>0) {$sql = $sql . ', EstimatedTime';}
                    if ($statusInfoActualTime!=null && $statusInfoActualTime>0) {$sql = $sql . ', ActualTime';}
                    if ($taskStatusInfoMainBranchID!=null && $taskStatusInfoMainBranchID>0) {$sql = $sql . ', MainBranchID';}
                    if ($taskStatusInfoMergedToBranchID!=null && $taskStatusInfoMergedToBranchID>0) {$sql = $sql . ', MergedToBranchID';}
                    $sql = $sql . ', StatusNotes) ';
                    $sql = $sql . $valuesSQL;

                    // Run the insert query
                    $db->queryDB($sql, $userRow, "updateTask Form occurance 1");
                }
                else {
                    // Let's create the insert query off of what we have
                    $sql='INSERT INTO taskstatusinfo_initial (';
                    $sql = $sql . 'TaskID, StatusID, ExecutionOrder, IsRoutingTemplate';
                    if ($statusInfoCompletionFactor!=null && $statusInfoCompletionFactor>0) {$sql = $sql . ', CompletionFactor';}
                    if ($statusInfoEstimatedTime!=null && $statusInfoEstimatedTime>0) {$sql = $sql . ', EstimatedTime';}
                    if ($statusInfoActualTime!=null && $statusInfoActualTime>0) {$sql = $sql . ', ActualTime';}
                    if ($taskStatusInfoMainBranchID!=null && $taskStatusInfoMainBranchID>0) {$sql = $sql . ', MainBranchID';}
                    if ($taskStatusInfoMergedToBranchID!=null && $taskStatusInfoMergedToBranchID>0) {$sql = $sql . ', MergedToBranchID';}
                    $sql = $sql . ', StatusNotes';
                    $sql = $sql . ') ';
                    $sql = $sql . 'VALUES (' . $taskID . ', ' . $statusID . ', ' . $executionOrder . ', ' . $statusInfoIsTemplate;
                    if ($statusInfoCompletionFactor!=null && $statusInfoCompletionFactor>0) {$sql = $sql . ', ' . $statusInfoCompletionFactor;}
                    if ($statusInfoEstimatedTime!=null && $statusInfoEstimatedTime>0) {$sql = $sql . ', ' . $statusInfoEstimatedTime;}
                    if ($statusInfoActualTime!=null && $statusInfoActualTime>0) {$sql = $sql . ', ' . $statusInfoActualTime;}
                    if ($taskStatusInfoMainBranchID!=null && $taskStatusInfoMainBranchID>0) {$sql = $sql . ', ' . $taskStatusInfoMainBranchID;}
                    if ($taskStatusInfoMergedToBranchID!=null && $taskStatusInfoMergedToBranchID>0) {$sql = $sql . ', ' . $taskStatusInfoMergedToBranchID;}
                    $sql = $sql . ', "' . $statusInfoNote . '" ';
                    $sql = $sql . ');';

                    // Run the insert query
                    $db->queryDB($sql, $userRow, "updateTask Form occurance 2");
                }
            }
            else {
                // Get the current date string
                $currentDate = new DateTime();
                $currentDate->modify('-1 hour');
                $currentDateString = $currentDate->format('Y-m-d H:i:s');
                
                // Make an update to change modified characteristics
                $sql='UPDATE taskstatusinfo_initial SET ';
                $sql = $sql . 'TaskID=' . $taskID;
                $sql = $sql . ', StatusID=' . $statusID;
                if ($executionOrder!=null && $executionOrder>0) {$sql = $sql . ', ExecutionOrder=' . $executionOrder;}
                if ($statusInfoCompletionFactor!=null && $statusInfoCompletionFactor>0) {$sql = $sql . ', CompletionFactor=' . $statusInfoCompletionFactor;}
                if ($statusInfoEstimatedTime!=null && $statusInfoEstimatedTime>0) {$sql = $sql . ', EstimatedTime=' . $statusInfoEstimatedTime;}
                if ($statusInfoActualTime!=null && $statusInfoActualTime>0) {$sql = $sql . ', ActualTime=' . $statusInfoActualTime;}
                if ($taskStatusInfoMainBranchID!=null && $taskStatusInfoMainBranchID>0) {$sql = $sql . ', MainBranchID=' . $taskStatusInfoMainBranchID;}
                if ($taskStatusInfoMergedToBranchID!=null && $taskStatusInfoMergedToBranchID>0) {$sql = $sql . ', MergedToBranchID=' . $taskStatusInfoMergedToBranchID;}
                $sql = $sql . ', StatusNotes="' . trim($statusInfoNote) . '" ';
                if ($autoAppendedNotes!=null && $autoAppendedNotes!="") {$sql = $sql . ', AutoAppendedNotes=CONCAT(AutoAppendedNotes,"\n\n' . $currentDateString . ': ' . $autoAppendedNotes . '") ';}

                // Finish up with the where clause
                $sql=$sql .' WHERE TaskStatusInfoID=' . $taskStatusInfoID . ';';

                // Run the update query
                $db->queryDB($sql, $userRow, "updateTask Form occurance 3");
            }
        } 
        catch (Exception $exc) {
            // Create the error string to return back to the caller
            return 'ABORT UPDATE STATUS INFO NODE (update_route_node)::There was an uncaught error while cleaning 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 UPDATE STATUS INFO NODE (update_route_node)::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
        $updateTaskNumber=-1;
        $taskStatusInfoID=-1;
        $taskStatusInfoMainBranchID=0;
        $taskStatusInfoMergedToBranchID=-1;
        $infoStatusID=null;
        $statusInfoEstimatedTime=0;
        $statusInfoActualTime=0;
        $statusInfoIsTemplate=0;
        $statusInfoRoutingTemplateName=null;
        $statusInfoCompletionFactor=1;
        $statusInfoNote='';
        $executionOrder=-1;
        $autoAppendedNotes='';        
        // check the passed in update task ID
        if (isset($_GET['updateTaskNumber']) ){
            // get the passed in update task ID
            $updateTaskNumber = $_GET['updateTaskNumber'];
        }

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

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

        // check the passed in Merged To Branch ID
        if (isset($_GET['taskStatusInfoMergedToBranchID']) ){
            // get the passed in Merged To Branch ID
            $taskStatusInfoMergedToBranchID = $_GET['taskStatusInfoMergedToBranchID'];
        }

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

        // check the passed in Estimated Time
        if (isset($_GET['statusInfoEstimatedTime']) ){
            // get the passed in Estimated Time
            $statusInfoEstimatedTime = $_GET['statusInfoEstimatedTime'];
        }

        // check the passed in Actual Time
        if (isset($_GET['statusInfoActualTime']) ){
            // get the passed in Actual Time
            $statusInfoActualTime = $_GET['statusInfoActualTime'];
        }

        // check the passed in Completion Factor
        if (isset($_GET['statusInfoCompletionFactor'])){
            // get the passed in Completion Factor
            $statusInfoCompletionFactor = $_GET['statusInfoCompletionFactor'];
        }

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

        // check the passed in Execution Order
        if (isset($_GET['executionOrder']) ){
            // get the passed in Execution Order
            $executionOrder = $_GET['executionOrder'];
        }

        // check the passed in Template Status
        if (isset($_GET['isRoutingTemplate']) ){
            // get the passed in Template Status
            $statusInfoIsTemplate = $_GET['isRoutingTemplate'];
        }

        // check the passed in Template Title
        if (isset($_GET['routingTemplateName']) ){
            // get the passed in Template Title
            $statusInfoRoutingTemplateName = $_GET['routingTemplateName'];
        }

        // check the passed in Auto Appended Notes
        if (isset($_GET['autoAppendedNotes']) ){
            // get the passed in Auto Appended Notes
            $autoAppendedNotes = $_GET['autoAppendedNotes'];
        }

        // Attempt to clean the task of the task passed in.
        $returnString=modifyStatusInfoNode($db, $userRow,$updateTaskNumber,
                                                         $taskStatusInfoID,
                                                         $taskStatusInfoMainBranchID,
                                                         $taskStatusInfoMergedToBranchID,
                                                         $infoStatusID,
                                                         $statusInfoEstimatedTime,
                                                         $statusInfoActualTime,
                                                         $statusInfoCompletionFactor,
                                                         $statusInfoNote,
                                                         $executionOrder, 
                                                         $statusInfoIsTemplate, 
                                                         $statusInfoRoutingTemplateName,
                                                         $autoAppendedNotes);

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