<?php    
    // continue the session
    session_start();

    include_once dirname(__FILE__) . '/../global_after_session.php';
    include_once dirname(__FILE__) . '/../database.php';
    include_once dirname(__FILE__) . '/../global_functions.php';

    function finishMachiningTask($db, $currentUser, $inTaskID, $inAssignToUserID=-1){
        $result = "";
        
        // Set up what the user posted at first, to be changed with logic.
        $taskID = $inTaskID;
        $assignToUserID = $inAssignToUserID;
        
        try {
            // Attempt to get the user row
            $userRow = $currentUser->fetch_assoc();

            // Ensure that we have a task to work on
            if ($taskID>0){
                // Create a query to get the machine ID of the task that is to be operated on
                $sql = 'SELECT * 
                        FROM tasktomachinelinker tml
                        LEFT JOIN tasks t ON tml.TaskID = t.TaskID 
                        LEFT JOIN status s ON t.StatusID = s.StatusID 
                        WHERE tml.TaskID = ' . $taskID . ' 
                        AND s.Name="Machining";';

                // run the query to get the machine ID
                $taskInMachining = $db->queryDB($sql, null, "finish_machining_task php occurance 1");

                // Attempt to run the query and evaluate the response
                if (mysqli_num_rows($taskInMachining)==1){
                    // Get the values from the query
                    $taskInMachiningAssoc = $taskInMachining->fetch_assoc();
                    
                    // Create a query to get the next phase after machining
                    $sql = 'SELECT * FROM status WHERE ProcessOrder>' . $taskInMachiningAssoc["ProcessOrder"] . ' ORDER BY ProcessOrder LIMIT 1;';

                    // run the query to get the next status
                    $nextStatusQuery = $db->queryDB($sql, null, "finish_machining_task php occurance 2");
            
                    // Attempt to run the query and evaluate the response
                    if (mysqli_num_rows($nextStatusQuery)==1){
                        // Get the values from the query
                        $nextStatusQueryAssoc = $nextStatusQuery->fetch_assoc();
                        
                        // We have all we need, lets write the query to move it to the next phase and assign it
                        $sql = 'UPDATE tasks SET LastUpdatedByID=' . $userRow["UserID"] . 
                                              ', StatusID = ' . $nextStatusQueryAssoc["StatusID"] . 
                                              ', UserID = ' . $assignToUserID . 
                              ' WHERE TaskID = ' . $taskID . ';';
                        
                        // Attempt to run the query
                        $db->queryDB($sql, $userRow, "finish_machining_task php occurance 3");
                       
                        // Delete the old task from this machine and in all machines of the 
                        $sql = 'DELETE FROM tasktomachinelinker WHERE TaskID = ' . $taskID . ';';
                        
                        // Attempt to run the query
                        $db->queryDB($sql, $userRow, "finish_machining_task php occurance 4");
                        
                        // Time to move all tasks up on this machine that was after the task moving off of the machine
                        $sql = 'UPDATE tasktomachinelinker SET TheOrder=TheOrder-1 ' .
                               'WHERE TheOrder >= 2 ' . 
                               'AND TheOrder < 99999 ' .
                               'AND MachineID = ' . $taskInMachiningAssoc["MachineID"] . ';'; 

                        // Attempt to run the query
                        $db->queryDB($sql, $userRow, "finish_machining_task php occurance 5");
                        
                        // Get the task updated, so I can get the parent ID and other information
                        $sql = 'SELECT t.*, s.Name AS ParentNameBefore, s.StatusID AS ParentStatusIDBefore, 
                                pt.Title AS ParentTitle, c.CompanyName
                                FROM tasks t 
                                LEFT JOIN tasks pt ON t.ParentID=pt.TaskID
                                LEFT JOIN status s ON pt.StatusID=s.StatusID
                                LEFT JOIN companies c ON t.CompanyID=c.CompanyID 
                                WHERE t.TaskID=' .  $taskID . ';';

                        // run the query to get the next status
                        $updatedTaskQuery = $db->queryDB($sql, $userRow, "finish_machining_task php occurance 6");

                        // Attempt to run the query and evaluate the response
                        if (mysqli_num_rows($updatedTaskQuery)==1){
                            // Get the values from the query
                            $updatedTaskQueryAssoc = $updatedTaskQuery->fetch_assoc();

                            // Get the parent information
                            $parentTaskNumber = $updatedTaskQueryAssoc["ParentID"];
                            $parentStatusIDBefore = $updatedTaskQueryAssoc["ParentStatusIDBefore"];
                            $parentStatusNameBefore = $updatedTaskQueryAssoc["ParentNameBefore"];
                            $parentTitle = $updatedTaskQueryAssoc["ParentTitle"];

                            // This is an update, so start making the update query
                            $sql='UPDATE taskstatus SET ';
                            $sql = $sql . 'EndDate=CURRENT_TIMESTAMP';
                            $sql = $sql . ', Comment="Change in status happening at machines page by ' . 
                                   $userRow["FirstName"] . ' ' . $userRow["LastName"] . 
                                   ' from myself."';
                            $sql = $sql . ', CompletingUserID=' . $userRow["UserID"];
                            $sql = $sql . ', Current=0';
                            $sql=$sql .' WHERE TaskID=' . $taskID . ' ';
                            $sql=$sql .' AND ParentID=' . $parentTaskNumber . ' ';
                            $sql=$sql .' AND Current=1;';

                            // Update any old task status row.  Not concerned with failure
                            $db->queryDB($sql, $userRow, "finish_machining_task php occurance 7");

                            // Insert a new task status 
                            $sql='INSERT INTO taskstatus (TaskID, ParentID, StatusID, Comment, StartingUserID, Current, AssignedToUserID) ' .  
                                 'VALUES (' . $taskID . ',' . $parentTaskNumber . ',' . $nextStatusQueryAssoc["StatusID"] . 
                                          ', "Change in status happening by ' . $userRow["FirstName"] . ' ' . $userRow["LastName"] . 
                                          ' from myself.",' . $userRow["UserID"] . ', 1, ' . $assignToUserID . ');';

                            // Update any old task status row.  Not concerned with failure
                            $db->queryDB($sql, $userRow, "finish_machining_task php occurance 8");

                            // Create the visualized task orientation as though this IS the parent
                            $firstFour = str_pad($taskID,4,"0",STR_PAD_LEFT);
                            $lastFour = '0000';

                            // Determine if this is a parent or a child so we can make all of the status changes to the children as well.
                            if ($parentTaskNumber == 0){
                                // This is an update, so start making the update query
                                $sql='UPDATE taskstatus SET ';
                                $sql = $sql . 'EndDate=CURRENT_TIMESTAMP';
                                $sql = $sql . ', Comment="Change in status happening by ' . 
                                       $userRow["FirstName"] . ' ' . $userRow["LastName"] . 
                                       ' from my parent."';
                                $sql = $sql . ', CompletingUserID=' . $userRow["UserID"];
                                $sql = $sql . ', Current=0';
                                $sql=$sql .' WHERE ParentID=' . $taskID . ' ';
                                $sql=$sql .' AND Current=1;';

                                // Update any old task status row.  Not concerned with failure
                                $db->queryDB($sql, $userRow, "finish_machining_task php occurance 9");

                                // This is an insert, so start making the insert query
                                $sql='INSERT INTO taskstatus (TaskID, ParentID, StatusID, Comment, StartingUserID, Current, AssignedToUserID) ' .  
                                     'SELECT TaskID,' . $taskID . ', ' . $nextStatusQueryAssoc["StatusID"] . ', ' . 
                                            '"Change in status happening by ' . $userRow["FirstName"] . ' ' . $userRow["LastName"] . 
                                            ' from my parent.",' . $userRow["UserID"] . ', 1, ' . $assignToUserID . 
                                     ' FROM tasks WHERE ParentID = ' . $taskID . ';';

                                // Insert a new task status row.  Not concerned with failure
                                $db->queryDB($sql, $userRow, "finish_machining_task php occurance 10");
                            }
                            else {
                                // Create the visualized task orientation as though this IS the parent
                                $firstFour = str_pad($parentTaskNumber,4,"0",STR_PAD_LEFT);
                                $lastFour = str_pad($taskID,4,"0",STR_PAD_LEFT);

                                // Create the query to get the correct the parent status
                                $sql =  'SELECT t.*, s.Name as StatusName ' . 
                                        '  FROM tasks t ' . 
                                        '  JOIN status s on t.StatusID = s.StatusID ' . 
                                        '  WHERE t.ParentID = ' . $parentTaskNumber . ' ' .
                                        '  ORDER BY s.ProcessOrder ASC ' . 
                                        '  LIMIT 1';

                                // Get the minimum status currently
                                $currentRollupRow = $db->queryDB($sql, $userRow, "finish_machining_task php occurance 11");

                                // Ensure that the query came back well
                                if (mysqli_num_rows($currentRollupRow)==1){
                                    $currentAssocRollupRow = $currentRollupRow->fetch_assoc();

                                    // Save the status that we are changing to to this
                                    $parentStatusIDAfter = $currentAssocRollupRow["StatusID"];
                                    $parentStatusNameAfter = $currentAssocRollupRow["StatusName"];

                                    // Determine if the parent status is changing
                                    if ($parentStatusIDBefore != $parentStatusIDAfter){
                                        // Create the query to update the parent status
                                        $sql =  'UPDATE tasks SET LastUpdatedByID=' . $userRow["UserID"] . 
                                                               ', StatusID=' . $parentStatusIDAfter . 
                                               ' WHERE TaskID = ' . $parentTaskNumber . ';';

                                        // Update the parent status and check that it changed
                                        if ($db->queryDB($sql, $userRow, "finish_machining_task php occurance 12")){
                                            // Since successful, notify everyone who wants to know.
                                            // Let's create and get the users to inform.
                                            $sql='SELECT * 
                                                  FROM users u
                                                  LEFT JOIN (SELECT NotificationCategory, UserID FROM usertostatuslinker 
                                                             WHERE StatusID=' . $parentStatusIDAfter . ') usl ON u.UserID = usl.UserID
                                                  WHERE u.UserID<>' . $userRow["UserID"] . '
                                                  AND u.UserTemplateOnly=0 
                                                  AND u.AccountStatus="Active"
                                                  AND u.SilenceAllTaskNotifications<>1 
                                                  AND ((u.CompanyID = ' . $updatedTaskQueryAssoc["CompanyID"] . ') 
                                                       OR (u.CompanyID = 1 AND u.SUEmployee=1) 
                                                       OR (u.UserID = ' . $assignToUserID . '));';

                                            // Make the query
                                            $usersToNotify = $db->queryDB($sql, $userRow, "finish_machining_task php occurance 13");

                                            // Loop through the returned results
                                            while ($userToNotify=mysqli_fetch_array($usersToNotify)){
                                                // Determine if this user is the same as the one adding it
                                                if ($userRow["UserID"]!=$userToNotify["UserID"]) {
                                                    // Init the message
                                                    $messageToSend='';

                                                    // Determine if they care about status change or in packaging notifications. 
                                                    //  Also if they are in the SU company and task is being 
                                                    //  assigned to them.  The last is forced.)
                                                    if (($userToNotify["NotificationCategory"]=="PARENT") || 
                                                        ($userToNotify["NotificationCategory"]=="ALL") || 
                                                        ($updatedTaskQueryAssoc["CompanyID"]==1 &&
                                                         $userToNotify["UserID"]==$assignToUserID)){
                                                        // Create the message to add for this
                                                        $messageToSend="<br>  ++ The Status has been changed from " .
                                                                       $parentStatusNameBefore . 
                                                                       " to " . $parentStatusNameAfter . ".<br>";
                                                    }

                                                    // First determine if they care about any changes
                                                    if ($messageToSend!="" && 
                                                        preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i", $userToNotify["EMail"])){

                                                        // Set subscribed to as the default
                                                        $messageToType = " that is under a category that you are currently monitoring.";
                                                        $subjectToType = "EES Subscription Message: ";

                                                        // Determine if this person is assigned to this task or not
                                                        if ($userToNotify["UserID"]==$assignToUserID){
                                                            // Change it to an assigned to message
                                                            $messageToType = " that you are ASSIGNED TO.";
                                                            $subjectToType = "EES ASSIGNED TO Message: ";
                                                        }

                                                        // Create the entire message
                                                        $messageToSend= 'There have been changes made by ' . $userRow['FirstName'] . 
                                                                ' ' . $userRow['LastName'] . ' to a child task status ' . 
                                                                'that changed the parent task status' . $messageToType . 
                                                                '<br><br>COMPANY: "' . $updatedTaskQueryAssoc['CompanyName'] . '"' .
                                                                '<br>Parent Task Title: "' . $parentTitle . '"' .
                                                                '<br>Parent TID: ' . $firstFour . '-0000<a href="https://www.eestms.com/' . 
                                                                getTMSHome() . '/updateTask.php?updateTaskID=' . $firstFour . 
                                                                '&parentTaskId=0">  (Click To View)</a>' .
                                                                '<br>Child Task Title: "' . $updatedTaskQueryAssoc["Title"] . '"' .
                                                                '<br>Child TID: ' . $firstFour . '-' . $lastFour . '<a href="https://www.eestms.com/' .
                                                                getTMSHome() . '/updateTask.php?updateTaskID=' . $lastFour . 
                                                                '&parentTaskId=' . $firstFour . '">  (Click To View)</a>.' . '<br><br>Changes Made:' . 
                                                                $messageToSend;

                                                        // Add a little more message to this notification
                                                        $messageToSend = $messageToSend . '<br><br>If you need help with your user name or password, ' .
                                                                'you can reply to this e-mail or call us at (720)552-7997.<br><br>' .
                                                                'Regards, <br><br>Evolve Engineering and Software Support Team<br>' .
                                                                '(720)552-7997';

                                                        // Decode the quotes to be shown as quotes.  Not weirdness
                                                        $messageToSend = htmlspecialchars_decode ($messageToSend, ENT_COMPAT | ENT_HTML401);

                                                        // Create the subject
                                                        $subject = htmlspecialchars_decode ($subjectToType . "Status change Made to '" . 
                                                                                            $parentTitle . "' via changing " . 
                                                                                            "child task status for company '" . 
                                                                                            $updatedTaskQueryAssoc["CompanyName"] . "'.");
                                                        
                                                        $headers = "From: EES Mail Admin"." <admin@eestms.com>\r\n"; 
                                                        $headers .= "MIME-Version: 1.0\r\n";
                                                        $headers .= "Content-type: text/html; charset=iso-8859-1\r\n";

                                                        try {
                                                            // Attempt to mail it
                                                            mail($userToNotify["EMail"],$subject,$messageToSend,$headers);
                                                        } 
                                                        catch (Exception $e) {
                                                            return 'INFO MESSAGE (finish_machining_task)::Notification was not sent to ' . 
                                                                   $userToNotify["EMail"] . ' because of an error.';
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }

                            // Determine if this is a parent or not
                            if ($parentTaskNumber == 0){
                                // Let's create and get the users to inform
                                $sql='SELECT * ' . 
                                     'FROM users u ' . 
                                     'LEFT JOIN (SELECT NotificationCategory, UserID FROM usertostatuslinker ' . 
                                     '           WHERE StatusID=' . $nextStatusQueryAssoc["StatusID"] . ') usl ON u.UserID = usl.UserID ' . 
                                     'WHERE u.UserID<>' . $userRow["UserID"] . ' ' .
                                     'AND u.UserTemplateOnly=0 ' .
                                     'AND u.SilenceAllTaskNotifications<>1 ' .
                                     'AND u.AccountStatus="Active" ' . 
                                     'AND ((u.CompanyID = ' . $updatedTaskQueryAssoc["CompanyID"] . ') ' . 
                                     '     OR (u.CompanyID = 1 AND u.SUEmployee=1) ' . 
                                     '     OR (u.UserID = ' . $assignToUserID . '));';
                            }
                            else{
                                // Determine if the creator and the assigned to are the same person
                                if ($userRow["UserID"] == $assignToUserID){
                                    // Exclude this user since they created it
                                    $sql='AND u.UserID<>' . $userRow["UserID"] . ';';
                                }
                                else {
                                    // Include this user because they did not created this and they are assigned it.
                                    $sql='OR u.UserID = ' . $assignToUserID . ';';
                                }

                                // Let's create and get the users to inform
                                $sql='SELECT * ' . 
                                     'FROM users u ' . 
                                     'LEFT JOIN (SELECT NotificationCategory, UserID FROM usertostatuslinker ' . 
                                     '           WHERE StatusID=' . $nextStatusQueryAssoc["StatusID"] . ') usl ON u.UserID = usl.UserID ' . 
                                     'WHERE u.CompanyID = 1 ' . 
                                     'AND u.UserTemplateOnly=0 ' .
                                     'AND u.SilenceAllTaskNotifications<>1 ' .
                                     'AND u.SUEmployee=1 ' . 
                                     'AND u.AccountStatus="Active" ' . 
                                     $sql;
                            }

                            // Make the query
                            $usersToNotify = $db->queryDB($sql, $userRow, "finish_machining_task php occurance 14");

                            // Loop through the returned results
                            while ($userToNotify=mysqli_fetch_array($usersToNotify)){
                                // Determine if this user is the same as the one adding it
                                if ($userRow["UserID"]!=$userToNotify["UserID"]) {
                                    // Init the message
                                    $textMessageToSend='';

                                    // Determine if they care about ANY status changing 
                                    // (Receive status change or in packaging notifications. 
                                    //  Also if they are in the SU company and task is being 
                                    //  assigned to them.  The last is forced.)
                                    if (($userToNotify["NotificationCategory"]=="CHILD" && $parentTaskNumber>0) || 
                                        ($userToNotify["NotificationCategory"]=="PARENT" && $parentTaskNumber==0) || 
                                        ($userToNotify["NotificationCategory"]=="ALL") || 
                                        ($userToNotify["CompanyID"]==1 &&
                                         $userToNotify["UserID"]==$assignToUserID)){
                                        // Create the message to add for this
                                        $textMessageToSend="<br>  ++ The Status has been changed from Machining" .
                                                       " to " . $nextStatusQueryAssoc["Name"] . ".<br>";
                                    }

                                    // Determine if this user is the user it is assigned to and they are from the primary company
                                    // and if a change that is tracked has NOT been made
                                    if ($userToNotify["CompanyID"]==1 &&
                                        $userToNotify["UserID"]==$assignToUserID &&
                                        $textMessageToSend==''){
                                        // Create the message to add for this
                                        $textMessageToSend='<br> ++ Untracked Changes.<br>';
                                    }

                                    // First determine if there has been a message made
                                    if ($textMessageToSend!="" && 
                                        preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i", $userToNotify["EMail"])){

                                        // Set subscribed to as the default
                                        $messageToType = " that is under a category that you are currently monitoring.";
                                        $subjectToType = "EES Subscription Message: ";

                                        // Create a variable for attachments and set it to NULL for now
                                        $zipName = '';

                                        // Determine if this person is assigned to this task or not
                                        if ($userToNotify["UserID"]==$assignToUserID){
                                            // Change it to an assigned to message
                                            $messageToType = " that you are ASSIGNED TO.";
                                            $subjectToType = "EES ASSIGNED TO Message: ";
                                        }

                                        // Create the entire message
                                        $textMessageToSend= 'There have been changes made by ' . $userRow['FirstName'] . 
                                                ' ' . $userRow['LastName'] . ' to a task' . $messageToType .
                                                '<br><br>COMPANY: "' . $updatedTaskQueryAssoc['CompanyName'] . '"' .
                                                '<br>Task Title: "' . $updatedTaskQueryAssoc['Title'] . '"' . 
                                                '<br>TID: ' . $firstFour . '-' . $lastFour . '<a href="https://www.eestms.com/' .
                                                getTMSHome() . '/updateTask.php?updateTaskID=' . $taskID . 
                                                '&parentTaskId=' . $parentTaskNumber . '">  (Click To View)</a>.<br><br>Changes Made:' . 
                                                $textMessageToSend;

                                        // Add a little more message to this notification
                                        $textMessageToSend = $textMessageToSend . '<br><br>If you would like to check ' .
                                                'on the task, you can do so at <a href="https://www.eestms.com/' . 
                                                getTMSHome() . '/updateTask.php?updateTaskID=' . $taskID . 
                                                '&parentTaskId=' . $parentTaskNumber . '">www.eestms.com/' . 
                                                getTMSHome() . '</a>.<br><br>If you need help with your user ' .
                                                'name or password, you can reply to this e-mail or call us at ' .
                                                '(720)552-7997.<br><br>Regards, <br><br>Evolve Engineering and Software ' .
                                                'Support Team<br>(720)552-7997';

                                        // Decode the quotes to be shown as quotes.  Not weirdness
                                        $textMessageToSend = htmlspecialchars_decode ($textMessageToSend, ENT_COMPAT | ENT_HTML401);

                                        // Create the subject
                                        $subject = htmlspecialchars_decode ($subjectToType . "Change Made to task '" . $updatedTaskQueryAssoc['Title'] . 
                                                                            "' for company '" . $updatedTaskQueryAssoc["CompanyName"] . "'.");

                                        try {
                                            // Sender 
                                            $from = 'admin@eestms.com'; 

                                            // Header for sender info 
                                            $headers = "From: EES Mail Admin"." <".$from.">\n"; 

                                            // Preparing attachment 
                                            if($zipName != '' && !empty($zipName) > 0){ 
                                                // Boundary  
                                                $semi_rand = md5(time());  
                                                $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";  

                                                // Headers for attachment  
                                                $headers .= "MIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\""; 

                                                // Multipart boundary  
                                                $message = "--{$mime_boundary}\n" . "Content-Type: text/html; charset=\"UTF-8\"\n" . 
                                                "Content-Transfer-Encoding: 7bit\n\n" . $textMessageToSend . "\n\n";  

                                                // Ensure there is a file there
                                                if(is_file($zipName)){ 
                                                    // Setup the message for the attachment
                                                    $message .= "--{$mime_boundary}\n"; 
                                                    $fp =    fopen($zipName,"rb"); 
                                                    $data =  fread($fp,filesize($zipName)); 

                                                    fclose($fp); 
                                                    $data = chunk_split(base64_encode($data)); 
                                                    $message .= "Content-Type: application/octet-stream; name=\"".basename($zipName)."\"\n" .  
                                                    "Content-Description: ".basename($zipName)."\n" . 
                                                    "Content-Disposition: attachment;\n" . " filename=\"".basename($zipName)."\"; size=".filesize($zipName).";\n" .  
                                                    "Content-Transfer-Encoding: base64\n\n" . $data . "\n\n"; 
                                                } 
                                                $message .= "--{$mime_boundary}--"; 
                                                $returnpath = "-f" . $from; 

                                                // Send email 
                                                $mail = mail($userToNotify["EMail"], $subject, $message, $headers, $returnpath);  

                                                // Run the query
                                                $currentTaskAttachments = $db->queryDB($sql, $userRow, "finish_machining_task Form occurance 16");

                                                // Determine if we got something in the query for attachments
                                                if ($currentTaskAttachments != null){
                                                    // Loop through the returned results
                                                    while ($currentTaskAttachment=mysqli_fetch_array($currentTaskAttachments)){
                                                        // Remove the file
                                                        unlink('./temp/' . $currentTaskAttachment["Title"]);
                                                    }
                                                }

                                                // Remove the file
                                                unlink($zipName);
                                            } 
                                            else
                                            {
                                                // Setup the e-mail for no attachments
                                                $headers .= "MIME-Version: 1.0\r\n";
                                                $headers .= "Content-type: text/html; charset=iso-8859-1\r\n";

                                                // Attempt to mail it
                                                mail($userToNotify["EMail"],$subject,$textMessageToSend,$headers);
                                            }
                                        } 
                                        catch (Exception $e) {
                                            return 'INFO MESSAGE (finish_machining_task)::Notification was not sent to ' . 
                                                   $userToNotify["EMail"] . ' because of an error.';
                                        }
                                    }
                                }
                            }
                        }

                        // Create a query to remove all suggested tools from this machine
                        $sql = 'UPDATE assignedtools ' . 
                               'SET SuggestedChangeNewToolID=-1, SuggestedRemoveToolAfterUse=0, ' .
                                   'SuggestedExposedLength=0, SuggestedNote="", SuggestedUseNewTool=0 ' . 
                               'WHERE MachineID = ' . $taskInMachiningAssoc["MachineID"] . ';'; 

                        // Run the update query
                        $db->queryDB($sql, $userRow, "finish_machining_task Form occurance 17");

                        // Call the function to determine if there are any tools to remove
                        $result = checkForToolsToRemove($db, $userRow, $taskInMachiningAssoc["MachineID"]);
                    }
                    else {
                        // Send and error message back
                        return 'ABORT MOVE (finish_machining_task)::Cannot get ' . 
                                  'the next status to move the task to. Aborted.';
                    }
                }
                else {
                    // Send and error message back
                    return 'ABORT MOVE (finish_machining_task)::There is no task ' . 
                              'in the machining phase to move on to the next phase. Aborted.';
                }
            }
            else {
                // Send and error message back
                return 'ABORT MOVE (finish_machining_task)::There is no task ' . 
                          'to change to the next phase. Aborted.';
            }
        } catch (Exception $ex) {
            // Set up an error message for the exception
            return 'ABORT MOVE (finish_machining_task)::There was an error ' . 
                      'trying to move the task ID ' . $taskID . ' on to the next phase. ' . 
                      '\n\n The error is: \n' . $ex->getMessage();
        }

        // Return whatever we got
        return $result;
    }
    
    $db = new Database();
    $db->setupTmsDB();
    
    // Set defaults for the passed in variables
    $taskID=-1;
    $assignToUserID=-1;
    $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 MOVE (finish_machining_task)::Your session has expired.  ' . 
             'Refresh the page before finishing the task.';
    }
    else {
        // Check for the task ID
        if (isset($_GET['taskID']) ){
            // Hold on to the task ID
            $taskID = $_GET['taskID'];
        }

        // Check for the assigned to user id
        if (isset($_GET['assignToUserID']) ){
            // Hold on to the assigned to user ID
            $assignToUserID = $_GET['assignToUserID'];
        }

        // Go and get the machines and all of their tasks
        echo finishMachiningTask($db, $currentUser, $taskID, $assignToUserID);
    }
    
    exit;
?>   

