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

    function moveTaskToMachining($db, $userRow, $inTaskID, $inMachinineID, $inAssignToUserID=-1){
        $result = "";
        
        // Set up what the user posted at first, to be changed with logic.
        $taskID = $inTaskID;
        $machinineID = $inMachinineID;
        $assignToUserID = $inAssignToUserID;
        
        try {
            // Ensure that we have a task and machine to work on
            if ($taskID>0 && 
                $machinineID>0){
                $currentSuccess=true;
                $duplicateToolsString="";
                hasDuplicateToolsInTaskSetups($db, $userRow, $currentSuccess, $duplicateToolsString, $inTaskID);
                // Determine if we have duplicates.  If so, fail to move the task forward.
                if ($duplicateToolsString!==""){
                    // Send and error message back
                    return "ABORT MOVE (move_task_into_machining)::There are duplicate tools in G-Code of some setups copied. Information on those setups are as follows:\n" . $duplicateToolsString . "\n\n";
                }
                
                // Create a query to determine if there are any new tools suggested on this machine currently
                $sql = 'SELECT COUNT(*) AS AmountOfSuggestedNewTools ' . 
                       'FROM assignedtools ' . 
                       'WHERE MachineID = ' . $machinineID . ' ' .
                       'AND (SuggestedChangeNewToolID > 0 ' .
                       '     OR SuggestedUseNewTool > 0);';
                
                // Run the query
                $toolsSuggestedSQL = $db->queryDB($sql, null, "move_task_into_machining Form occurance 1");
                
                // Check the results of the queries.  If either returns a row, then that could be cause for abort
                if (mysqli_num_rows($toolsSuggestedSQL)>0){
                    // Get the assoc row
                    $toolsSuggestedAssocRow = $toolsSuggestedSQL->fetch_assoc();

                    // Determine if there are any unassigned tools
                    if ($toolsSuggestedAssocRow["AmountOfSuggestedNewTools"]>0){
                        // return a message for not allowing this to happen
                        return 'ABORT MOVE (move_task_into_machining)::There are ' . 
                               $toolsSuggestedAssocRow["AmountOfSuggestedNewTools"] . 
                               ' tools waiting to be accepted on this machine currently. ' . 
                               'Those tools need to be dealt with before task can be ' . 
                               'put into the machining phase.';
                    }
                }
                
                // Create a query to determine if there are any tools unassigned
                $sql = 'SELECT COUNT(*) AS AmountOfToolsUnassigned ' . 
                       'FROM tooltotasklinker ' . 
                       'WHERE TaskID = ' . $taskID . ' ' .
                       'AND ToolPosition <= 0;';
                
                // Run the query
                $toolsUnassignedSQL = $db->queryDB($sql, null, "move_task_into_machining Form occurance 2");
                
                // Create a query to determine if this is a machine that we currently handle.
                $sql='SELECT m.Type ' . 
                     'FROM tasktomachinelinker ttml ' . 
                     'LEFT JOIN machines m ON ttml.MachineID=m.MachineID ' .
                     'WHERE TaskID=' . $taskID . ';';

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

                // Get the assoc row
                $machineTypeAssocRow = $machineType->fetch_assoc();
                
                // Check the results of the queries.  If either returns a row, then that could be cause for abort
                if (mysqli_num_rows($toolsUnassignedSQL)>0){
                    // Get the assoc row
                    $taskOnMachineAssocRow = $toolsUnassignedSQL->fetch_assoc();

                    // Determine if there are any unassigned tools
                    if ($taskOnMachineAssocRow["AmountOfToolsUnassigned"]>0 && 
                        ($machineTypeAssocRow["Type"] != null && $machineTypeAssocRow["Type"] == 'MILL')){
                        // return a message for not allowing this to happen
                        return 'ABORT MOVE (move_task_into_machining)::Cannot move this ' . 
                               'task into machining because there are ' . 
                               $taskOnMachineAssocRow["AmountOfToolsUnassigned"] . ' ' .
                               'tools assigned to this task that do NOT have a position ' .
                               'defined.';
                    }
                }
                
                // Determine if the machine it is going on to already has a machining task
                // and it is NOT this task ID. So we can run this for the current machining
                // task. This should have been checked already, but doing a double check.
                $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.MachineID = ' . $machinineID . ' 
                        AND tml.TaskId <> ' . $taskID . '
                        AND s.Name = "Machining";';

                // run the query to get the task ID
                $machingMovingToHasMachingSQL = $db->queryDB($sql, null, "move_task_into_machining Form occurance 3");

                // Check the results of the queries.  If either returns a row, then that could be cause for abort
                if (mysqli_num_rows($machingMovingToHasMachingSQL)>0){
                    // return a message for not allowing this to happen
                    return 'ABORT MOVE (move_task_into_machining)::Cannot move this ' . 
                           'task into machining, since this machine already has a machining ' . 
                           'task.';
                }
                
                // Get the row that we will be moving to machining
                $sql = 'SELECT * FROM tasktomachinelinker WHERE TaskID=' . $taskID . ';'; 
                
                // run the query to get the task on the machine
                $taskOnMachineQuery = $db->queryDB($sql, null, "move_task_into_machining Form occurance 4");

                // Determine if there is that task in the machine to task linker table
                $taskOnMachineAssocRow=null;
                if (mysqli_num_rows($taskOnMachineQuery)>0){
                    // Get the task row on the machine
                    $taskOnMachineAssocRow = $taskOnMachineQuery->fetch_assoc();
                    
                    // Change the order down for the old machine after this one to fill the gap
                    $sql = 'UPDATE tasktomachinelinker SET TheOrder=TheOrder-1 ' .
                           'WHERE TheOrder >= ' . $taskOnMachineAssocRow["TheOrder"] . ' ' . 
                           'AND TheOrder < 99999 ' .
                           'AND MachineID = ' . $machinineID . ';'; 

                    // Attempt to run the query
                    $db->queryDB($sql, $userRow, "move_task_into_machining Form occurance 5");
                }
                
                // Make a hole at the top for this task to become the machining task
                $sql = 'UPDATE tasktomachinelinker SET TheOrder=TheOrder+1 ' .
                       'WHERE TheOrder >= 1 ' . 
                       'AND TheOrder < 99999 ' .
                       'AND MachineID = ' . $machinineID . ';'; 

                // Attempt to run the query
                $db->queryDB($sql, $userRow, "move_task_into_machining Form occurance 6");
                
                // Update this one to be at the top now
                $sql = 'UPDATE tasktomachinelinker SET TheOrder=1 ' .
                       'WHERE MachineID = ' . $machinineID . ' ' . 
                       'AND TaskID = ' . $taskID . ';'; 
                
                // Attempt to run the query
                $db->queryDB($sql, $userRow, "move_task_into_machining Form occurance 7");
                
                // Create a query to remove all suggested tools before I put any new suggested tools into the system
                $sql = 'UPDATE assignedtools ' . 
                       'SET SuggestedChangeNewToolID=-1, SuggestedRemoveToolAfterUse=0, ' .
                           'SuggestedExposedLength=0, SuggestedNote="", SuggestedUseNewTool=0 ' . 
                       'WHERE MachineID = ' . $machinineID . ';'; 
                
                // Run the update query
                $db->queryDB($sql, $userRow, "move_task_into_machining Form occurance 8");
                
                // Only set tools for approved machines
                if ($machineTypeAssocRow["Type"] != null && $machineTypeAssocRow["Type"] == "MILL"){
                    // Setup the result to give information about the move, if necessary
                    $result = setTaskToolsAsSuggested($db, $userRow, $taskID, $machinineID);
                }
                // TODO: Currently we are only handling Mills for the tools. Update this as we handle more.
                else if ($machineTypeAssocRow["Type"]!=null && $machineTypeAssocRow["Type"] != "MILL"){
                    // Send a message back to lewt them know we are not handling this type of machine
                    $result = 'INFO MESSAGE (move_task_into_machining)::This is an unknown machine. No tools were touched...';

                    // Determine if we have a value.
                    if ($machineTypeAssocRow["Type"]!=null){
                        // Send a message back to lewt them know we are not handling this SPECIFIC type of machine
                        $result = 'INFO MESSAGE (move_task_into_machining)::We do not currently handle tool modifications for machine type ' . $machineTypeAssocRow["Type"] . '. No tools were touched...';
                    }
                }

                // Create a query to clear out the hold flags
                $sql = 'UPDATE tasktomachinelinker SET IsPendingApproval=0, ' . 
                       'IsPendingTools=0, IsWaitingToBeReviewed=0 ' .
                       'WHERE MachineID = ' . $machinineID . ' ' . 
                       'AND TaskID = ' . $taskID . ';'; 

                // Run the update query
                $db->queryDB($sql, $userRow, "move_task_into_machining Form occurance 9");
                
                // Create a query to clear out the material hold flags on all job blanks for this task
                $sql = 'UPDATE jobblanks SET IsPendingStock=0 ' .
                       'WHERE TaskID = ' . $taskID . ';'; 

                // Run the update query
                $db->queryDB($sql, $userRow, "move_task_into_machining Form occurance 10");
            }
            else {
                // Send and error message back
                return 'ABORT MOVE (move_task_into_machining)::There is no task ' . 
                          'or machine to change to the machining. Aborted.';
            }
            
            // Ensure that we have a task to work on
            if ($taskID>0){
                // Get the task to be updated, so I can get the parent ID and other information. 
                // I need to run this before task is updated in order to get previous task info.
                $sql = 'SELECT t.*, ps.Name AS ParentNameBefore, ps.StatusID AS ParentStatusIDBefore, 
                        pt.Title AS ParentTitle, c.CompanyName, s.Name AS PreviousStatusName,
                        (SELECT StatusID FROM status WHERE Name="Machining") AS MachiningQueueStatusID
                        FROM tasks t 
                        LEFT JOIN tasks pt ON t.ParentID=pt.TaskID
                        LEFT JOIN status s ON t.StatusID=s.StatusID
                        LEFT JOIN status ps ON pt.StatusID=ps.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, "move_task_into_machining php occurance 11");

                // We have all we need, lets write the query to move it into machining
                $sql = 'UPDATE tasks ' .
                       'SET LastUpdatedByID=' . $userRow["UserID"] . 
                         ', StatusID = (SELECT StatusID FROM status WHERE Name="Machining"), ' . 
                       'UserID = ' . $assignToUserID . ' ' . 
                       'WHERE TaskID = ' . $taskID . ';';

                // Attempt to run the query
                $db->queryDB($sql, $userRow, "move_task_into_machining Form occurance 12");
                
                // 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"];
                    $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, "move_task_into_machining php occurance 13");

                    // Insert a new task status 
                    $sql='INSERT INTO taskstatus (TaskID, ParentID, StatusID, Comment, StartingUserID, Current, AssignedToUserID) ' .  
                         'VALUES (' . $taskID . ',' . $parentTaskNumber . ',' . $updatedTaskQueryAssoc["MachiningQueueStatusID"] . 
                                  ', "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, "move_task_into_machining php occurance 14");

                    // 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, "move_task_into_machining php occurance 15");

                        // This is an insert, so start making the insert query
                        $sql='INSERT INTO taskstatus (TaskID, ParentID, StatusID, Comment, StartingUserID, Current, AssignedToUserID) ' .  
                             'SELECT TaskID,' . $taskID . ', ' . $updatedTaskQueryAssoc["MachiningQueueStatusID"] . ', ' . 
                                    '"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, "move_task_into_machining php occurance 16");
                    }
                    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, "move_task_into_machining php occurance 17");

                        // 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, "move_task_into_machining php occurance 18")){
                                    // 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, "move_task_into_machining php occurance 19");

                                    // 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 " .
                                                               $updatedTaskQueryAssoc["PreviousStatusName"] . 
                                                               " to Machining.<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) {
                                                    echo("The 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=' . $updatedTaskQueryAssoc["MachiningQueueStatusID"] . ') 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 . '));';
                    }
                    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=' . $updatedTaskQueryAssoc["MachiningQueueStatusID"] . ') 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, "move_task_into_machining php occurance 20");

                    // 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 " . 
                                               $updatedTaskQueryAssoc["PreviousStatusName"] .
                                               " to Machining.<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, "move_task_into_machining Form occurance 21");

                                        // 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 (move_task_into_machining)::Notification was not sent to ' . 
                                           $userToNotify["EMail"] . ' because of an error.';
                                }
                            }
                        }
                    }
                }
            }
            else {
                // Send and error message back
                return 'ABORT MOVE (move_task_into_machining)::There is no task ' . 
                          'to move into machining.';
            }
        } catch (Exception $ex) {
            // Set up an error message for the exception
            return 'ABORT MOVE (move_task_into_machining)::There was an error ' . 
                      'trying to move the task ID ' . $taskID . ' to machining. ' . 
                      '\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
    $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 (move_task_into_machining)::Your session has expired.  ' . 
             'Refresh the page before moving this task into machining.';
    }
    else {
        // Set defaults for the passed in variables
        $taskID=-1;
        $machinineID=-1;
        $assignToUserID=-1;

        // Check for the task ID
        if (isset($_GET['taskID']) ){
            // Hold on to the task ID
            $taskID = $_GET['taskID'];
        }

        // Check for the machine ID
        if (isset($_GET['machineID']) ){
            // Hold on to the machine ID
            $machinineID = $_GET['machineID'];
        }

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

        // Attempt to get the user row
        $userRow = $currentUser->fetch_assoc();

        // Move this task into machining. This will include moving tools into the state to get ready.
        echo moveTaskToMachining($db, $userRow, $taskID, $machinineID, $assignToUserID);
    }
?>   

