<?php    
    include '../database.php';
    
    function doesTaskHaveToolsToSetup ($db, $userRow, $taskID, $machineID){
        try {
            // Ensure the passed in variables are valid
            if (is_numeric($taskID) && $taskID>0 && 
                is_numeric($machineID) && $machineID>0){
                // Create the query to determine of there are tools to setup
                $sql = 'SELECT * FROM tooltotasklinker ' . 
                       'WHERE TaskID = ' . $taskID . ';';
                
                // Query the database for the tasks 
                $toolRows = $db->queryDB($sql, $userRow, "individual_machine_tasks Form occurance 1");

                // Determine if there are any rows before attempting to loop through them
                if ($toolRows != null && 
                    mysqli_num_rows($toolRows)>0){
                    // Loop through the returned results
                    while ($toolRow=mysqli_fetch_array($toolRows)){
                        // Determine if they have set the tool position on this tool
                        if ($toolRow["ToolPosition"] <= 0){
                            // If the tool position is not set, then this is cause for action.
                            return true;
                        }
                        
                        // Create a query to get the tool at this position on the machine
                        $sql = 'SELECT * FROM assignedtools ' .
                               'WHERE MachineID = ' . $machineID . ' ' . 
                               'AND Position = ' . $toolRow["ToolPosition"] . ';';

                        // Query the database for the tasks 
                        $assignedToolRow = $db->queryDB($sql, $userRow, "individual_machine_tasks Form occurance 2");

                        // Determine if there are any rows before attempting to loop through them
                        if ($assignedToolRow != null && 
                            mysqli_num_rows($assignedToolRow)>0){
                            // Attempt to get the assigned tool row
                            $assignedToolAssocRow = $assignedToolRow->fetch_assoc();

                            // Do my checks (Tools not assigned to positions, different tool in slot, exposed length not sufficient)
                            if ($toolRow["ToolID"] != $assignedToolAssocRow["CurrentToolID"] ||
                                ($toolRow["ExposedLength"] > 0 && $toolRow["ExposedLength"] != $assignedToolAssocRow["ExposedLength"] ) ){
                                // If any of these are true, then it will mean that there are tools that have to be setup.  We can return a true. No need to do any more checks.
                                return true;
                            }
                        }
                    }
                }
            }

            // If we got here, then that means the tools to setup are not necessary. Return a false.
            return false;
        } catch (Exception $ex) {
            // assume error means they need to look into things closely
            return true;
        }
    }

    function getSecondaryStatusBullets($isWaitingToBeReviewed,$amountPendingStock,
                                       $isPendingTools, $IsPendingApproval){
        $result='';
        
        // Determine if there are ANY that are true
        if ($isWaitingToBeReviewed || ($amountPendingStock!=null && $amountPendingStock>0) || $isPendingTools || $IsPendingApproval){
            // Start the cell
            $result='<td colspan=3 style="border: 1px solid black; text-align: right; vertical-align: middle;
                background: white repeating-linear-gradient(135deg,rgba(239, 255, 61, 1),rgba(239, 255, 61, 1) 3px,rgba(255, 5, 5, 1) 3px,rgba(255, 5, 5, 1) 6px);">';
            
            // Determine if it is waiting to be reviewed
            if ($isWaitingToBeReviewed){
                // Add this bullet to the results
                $result = $result . '<label title="This task is waiting to be reviewed." style="color: transparent;  text-shadow: 0 0 0 rgb(124, 252, 0); font-size: 11px;">⚫</label>';
            }

            // Determine if it is waiting to be reviewed
            if ($amountPendingStock>0){
                // Add this bullet to the results
                $result = $result . '<label title="This task is pending stock to be released." style="color: transparent;  text-shadow: 0 0 0 rgb(127, 0, 255); font-size: 11px;">⚫</label>';
            }

            // Determine if it is waiting to be reviewed
            if ($isPendingTools){
                // Add this bullet to the results
                $result = $result . '<label title="This task is pending tools to be released." style="color: transparent;  text-shadow: 0 0 0 rgb(0, 0, 255); font-size: 11px;">⚫</label>';
            }

            // Determine if it is waiting to be reviewed
            if ($IsPendingApproval){
                // Add this bullet to the results
                $result = $result . '<label title="This task is pending approval to be released." style="color: transparent;  text-shadow: 0 0 0 rgb(113, 121, 126); font-size: 11px;">⚫</label>';
            }
            
            // Finish the cell
            $result=$result . '</td>';
        }
            
        return $result;
    }
                        
    function getBlankStatus($db, $userRow, $inTaskID){
        $result='';
        
        // Let's do a query to see if there are blanks made for this task
        $sql = 'SELECT * FROM jobblanks WHERE TaskID = ' . $inTaskID . ';';
        
        // Query the database for the blanks 
        $rows = $db->queryDB($sql, $userRow, "individual_machine_tasks Form occurance 3");

        // Blank count and submitted will be negative if there are no rows
        $blankCount=-1;
        
        // Blanks submitted will start at zero
        $blanksSubmitted=0;
        
        // Determine if there are any rows before attempting to loop through them
        if ($rows != null && 
            mysqli_num_rows($rows)>0){
            // Status variables to use within the loop
            $blankCount=0;
            $blanksReadiedCount=0;
            
            // Loop through the blanks to see if all are submitted
            while ($row=mysqli_fetch_array($rows)){
                // Increase the amount of blanks
                $blankCount++;
                
                // Determine if the blank is ready
                if ($row["BlankReady"]==1){
                    // Increment the blank readied count
                    $blanksReadiedCount++;
                }
                
                // Determine if this blank has been submitted
                if ($row["Submitted"]==1){
                    // Increment the blank submitted counter
                    $blanksSubmitted++;
                }
            }
        }
        
        // Create an unhandled state in case I forget something
        $result='<td style="text-align: center; vertical-align: middle;" colspan=1 style="border: 1px solid black; text-align: right; vertical-align: middle;">
                      <label style="border: 1px solid black; background: white; display:block; width:30px;" title="This is an unhandled state for material status. Please let an EES IT person know. " style="color:black; font-size: 10px;"><b>???</b></label>
                 </td>';
        
        // Determine if there are any blanks submitted
        if ($blankCount==-1 || $blankCount==0){
            // Let them know that NO blanks have been submitted
            $result='<td style="text-align: center; vertical-align: middle;" colspan=1 style="border: 1px solid black; text-align: right; vertical-align: middle;">
                          <label style="border: 1px solid black; background: red; display:block; width:30px;" title="This task does not have any blanks submitted. Please ensure that the blanks have not been submitted in another way." style="color:black; font-size: 10px;"><b>!!!</b></label>
                     </td>';
        }
        else {
            // Determine if all blanks have been submitted
            if ($blanksSubmitted==$blankCount){
                // Determine if NONE of ALL blanks have been submitted and readied
                if ($blanksReadiedCount==0){
                    // Let them know that NOT ALL of blanks have been readied
                    $result='<td style="text-align: center; vertical-align: middle;" colspan=1 style="border: 1px solid black; text-align: right; vertical-align: middle;">
                                  <label style="border: 1px solid black; background: orange; display:block; width:30px;" title="This task has ' . $blankCount . ' blank type(s) submitted and NONE has been readied. Please ensure that ALL blanks are readied before starting job." style="color:black; font-size: 10px;"><b>???</b></label>
                             </td>';
                }
                // Determine if all are submitted but not all readied
                else if ($blanksReadiedCount<$blankCount){
                    // Let them know that NOT ALL of blanks have been submitted
                    $result='<td style="text-align: center; vertical-align: middle;" colspan=1 style="border: 1px solid black; text-align: right; vertical-align: middle;">
                                  <label style="border: 1px solid black; background: yellow; display:block; width:30px;" title="This task has ' . $blankCount . ' blank type(s) submitted and only ' . $blanksReadiedCount . ' has been readied. Please ensure that ALL blanks are readied before starting job." style="color:black; font-size: 10px;"><b>???</b></label>
                             </td>';
                }
                // Determine if all of the blanks have been submitted and readied
                else if ($blankCount==$blanksReadiedCount){
                    // Submit that we are good to go with blanks
                    $result='<td style="text-align: center; vertical-align: middle;" colspan=1 style="border: 1px solid black; text-align: right; vertical-align: middle;">
                                  <label style="border: 1px solid black; background: green; display:block; width:30px;" width:40px; title="This task has ' . $blankCount . ' blank type(s) submitted and all are ready." style="color:black; font-size: 10px;"><b>...</b></label>
                             </td>';
                }
            }
            else {
                // Determine if there are blanks not submitted 
                if ($blankCount>$blanksReadiedCount){
                    // Let them know that NOT ALL of blanks have been submitted
                    $result='<td style="text-align: center; vertical-align: middle;" colspan=1 style="border: 1px solid black; text-align: right; vertical-align: middle;">
                                  <label style="border: 1px solid black; background: pink; display:block; width:30px;" title="This task has ' . $blankCount . ' blank type(s) submitted, ' . $blanksReadiedCount . ' has been readied and ' . ($blankCount-$blanksReadiedCount) . ' has not been submitted. Please ensure that ALL blanks are submitted AND readied before starting job." style="color:black; font-size: 10px;"><b>!!!</b></label>
                             </td>';
                }
            }
        }
            
        return $result;
    }
                        
    function retrieveTasksWithinMachines($db, $userRow){
        // Init variables
        $updateableTaskRowCellHTML = '';
        
        // Initialize the header
        $headerResult = 
            '<li class="ui-state-default ui-state-disabled Table">
                <div class="Heading">
                    <div class="cell expediteCell">
                        <p><b>Rush</b></p>
                    </div>
                    <div class="cell titleCell">
                        <p><b>Title</b></p>
                    </div>
                    <div class="cell assignedToCell">
                        <p><b>Assigned To</b></p>
                    </div>
                    <div class="cell dueDateCell">
                        <p><b>Due Date</b></p>
                    </div>
                    <div class="cell fixtureCell">
                        <p><b>Fixture</b></p>
                    </div>
                    <div class="cell statusCell">
                        <p><b>Status</b></p>
                    </div>
                    <div class="cell taskIDCell">
                        <p><b>Task ID</b></p>
                    </div>
                    <div class="cell companyCell">
                        <p><b>Company</b></p>
                    </div>
                    <div class="cell updateCell">
                        <p><b>Edit</b></p>
                    </div>
                </div>
            </li>';

        try {
            $sql=
                'SELECT m.Name as MachineName, m.IsDown as MachineIsDown, m.MachineID as TheMachineID, m.Type as MachineType, ' .
                       'u.FirstName, u.LastName, u.UserID, ' . 
                       's.Name AS StatusName, s.StatusRowColor, ' .
                       'c.CompanyName AS CompanyName, c.CompanyRowColor, c.CompanyID, ' .
                       't.Title, t.TaskID, t.ParentID, t.Expedite, t.FixtureToUseID, t.DueDate, t.TypeID, t.CurrentTaskStatusRoutingNodeID, ' .
                       'tml.TheOrder, tml.IsWaitingToBeReviewed, tml.IsPendingTools, tml.IsPendingApproval, ' .
                       'tf.Title AS FixtureName, ss.SecondaryStatusID, ' .
                       'ss.RowColor AS SSRowColor, ss.Description AS SSDescription, ss.Name AS SSName, ' .
                       'usvl.ViewCategory, usvl.ViewCategory AS StatusViewCategory, ' .
                       'jbps.AmountPendingStock, ' .
                       'tsic.MainBranchID, tsic.ExecutionOrder ' .
                'FROM machines m ' .
                'LEFT JOIN tasktomachinelinker tml ON m.MachineID = tml.MachineID ' .
                'LEFT JOIN tasks t ON tml.TaskID = t.TaskID ' .
                'LEFT JOIN users u ON t.UserID = u.UserID ' .
                'LEFT JOIN tasks tf ON t.FixtureToUseID = tf.TaskID ' .
                'LEFT JOIN status s ON t.StatusID = s.StatusID ' .
                'LEFT JOIN companies c ON t.CompanyID = c.CompanyID ' . 
                'LEFT JOIN secondarystatuses ss ON t.SecondaryStatusID = ss.SecondaryStatusID ' .
                'LEFT JOIN taskstatusinfo_current tsic ON t.CurrentTaskStatusRoutingNodeID = tsic.TaskStatusInfoID ' .
                'LEFT JOIN (SELECT TaskID, SUM(IsPendingStock) AS AmountPendingStock FROM jobblanks GROUP BY TaskID) jbps ON t.TaskID = jbps.TaskID ' .
                'LEFT JOIN (SELECT * FROM usertostatusviewinglinker WHERE UserID=' . $userRow["UserID"] . ') usvl ON t.StatusID = usvl.StatusID ' .
                'LEFT JOIN (SELECT * FROM usertomachineviewinglinker WHERE UserID=' . $userRow["UserID"] . ') umvl ON m.MachineID = umvl.MachineID ' .
                'WHERE m.ShowOnWhiteboard=1 ' .
                'AND   umvl.ViewCategory IS NULL ' .
                'ORDER BY m.Type, m.Name, tml.TheOrder ';

//return 'ABORT WHITEBOARD POPULATE (individual_machine_tasks)::' . $sql;
            // Query the database for the tasks 
            $rows = $db->queryDB($sql, $userRow, "individual_machine_tasks Form occurance 3");

            // Determine if there are any rows before attempting to loop through them
            if ($rows != null && 
                mysqli_num_rows($rows)>0){
                // Loop through the returned results
                $currentMachineID=-1;
                $result="";
                $canChangeMachiningTask=false;
                $completeMachiningScript='';
                $openNonMachiningFirstBool='true';
                while ($row=mysqli_fetch_array($rows)){
                    // Determine if they are allowed to view this one
                    $rowVisibility='';
                    if ($row["StatusViewCategory"]=="NOT VIEWABLE"){
                        // Move onto the next row
                        continue;
                    }
                          
                    // Create a query to get appropriate sticky notes for this task
                    $sql = 'SELECT n.*, 
                                   (SELECT COUNT(*) FROM stickynoteusers WHERE MarkedAsRead=0 AND NoteID=n.NoteID) AS AmountNotReadByEveryone,
                                   (SELECT COUNT(*) FROM stickynoteusers WHERE MarkedAsRead=0 AND NoteID=n.NoteID AND SendToID=' . $userRow["UserID"] . ') AS AmountNotReadByMe
                            FROM notes n
                            WHERE n.AssociatedCategoryID=' . $row["TaskID"] . '
                            AND n.Category="TASK" 
                            AND n.IsSticky=1;';
                    
                    // Query the database for the the note count 
                    $stickyNoteRows = $db->queryDB($sql, $userRow, "individual_machine_tasks Form occurance 4");

                    // Init some count variables
                    $notesToOthersFromMe=0;
                    $notesToMeFromOthers=0;
                    $stickyNoteHTML='';

                    // Determine if there are any rows before attempting to loop through them
                    if ($stickyNoteRows != null && 
                        mysqli_num_rows($stickyNoteRows)>0){
                        // Loop through the returned results
                        while ($stickyNoteRow=mysqli_fetch_array($stickyNoteRows)){
                            // Determine if this sticky note should be counted because this
                            // person made the note and needs to keep track of who read it
                            if ($stickyNoteRow["EnteredByID"]==$userRow["UserID"] &&
                                $stickyNoteRow["AmountNotReadByEveryone"]>0){
                                // Increment the count of ones I made that have not been read by everyone
                                $notesToOthersFromMe++;
                            }

                            // Make this separate to count the ones I made that I want myself to reread
                            if ($stickyNoteRow["AmountNotReadByMe"]>0){
                                // Increment the count of ones I made that have not been read by everyone
                                $notesToMeFromOthers++;
                            }
                        }
                    }
                    
                    // Determine if there are notes to show them
                    if ($notesToOthersFromMe>0 || $notesToMeFromOthers>0){
                        $stickyNoteHTML=
                                '<div style="position: absolute; top: 10%; left:-75%;" onclick="popUp=popupWindow(\'view_sticky_notes.php?acid=' . $row["TaskID"] . '&c=TASK\', \'_blank\', window.parent, 700, 500);" 
                                                                                       onmouseover="document.body.style.cursor = \'pointer\';" 
                                                                                       onmouseout="document.body.style.cursor = \'default\';"
                                                                                       title="There are ' . $notesToMeFromOthers . ' notes to you that you have not read and ' . $notesToOthersFromMe . ' notes that you wrote that have not been read by all recipients.">
                                    <img src="images/post_it.png" alt="Sticky Notes" style="height:50px; transform:rotate(15deg);">
                                    <div style="position: absolute; top: 20%; left: 20%; transform:rotate(15deg);"><b><font style="color:red;">' . $notesToMeFromOthers . '</font>(<font style="color:green;">' . $notesToOthersFromMe . '</font>)</b></div>
                                 </div>';
                    }
                    
                    // Determine if the machine ID is different
                    if ($row["TheMachineID"]!=$currentMachineID){
                        // Assume that there is NOT a machining task on this machine
                        $openNonMachiningFirstBool='true';
                        
                        // Add a delimiter to denote a new machine
                        $result =  $result. '||||/*|*|*' . $row["TheMachineID"] . '*|*|*/' . $headerResult;

                        // Set the new machine ID
                        $currentMachineID=$row["TheMachineID"];
                        
                        // Determine if the top task is in machining and this user cannot modify machining
                        if ($row["StatusName"]=="Machining" &&
                            $row["ViewCategory"] == "NOT VIEWABLE" &&
                            $row["UserID"] != $userRow["UserID"]){
                            // set the flag that lets me know they cannot change the top machining task
                            $canChangeMachiningTask=false;
                        }
                        else {
                            // They can change it, so set that
                            $canChangeMachiningTask=true;
                        }
                        
                        // Reset the machining script to nothing, since we are on a new machine with the possibility of a new machining task
                        $completeMachiningScript='';

                        // Determine if the top task is machining
                        if ($row["StatusName"]=="Machining"){
                            // Set the fact that there is a machining task and should be opened first
                            $openNonMachiningFirstBool='false';
                        }
                    }
                    
                    // Determine if this is a machine WITH a task
                    if ($row["TaskID"]!=null){
                        // Determine what secondary statuses are and return the html
                        $secondaryStatusHTML = getSecondaryStatusBullets($row["IsWaitingToBeReviewed"],$row["AmountPendingStock"],
                                                                         $row["IsPendingTools"],$row["IsPendingApproval"]);
                        
//                        // Get HTNL to say if the blank is ready
//                        $blankStatusID='                                                    <td style="text-align: left; vertical-align: middle;" colspan=1>
//                                                          <label style="font-size:10px; font-weight: bold; color:Black;">child&nbsp;</label>
//                                                    </td>
//';
                        
                        $blankStatusID = getBlankStatus($db, $userRow, $row["TaskID"]);
                        
                        // create html to show them that this is a child
                        $relationshipTextHTML = '<tr>
                                                    ' . $blankStatusID . '
                                                    ' . $secondaryStatusHTML . '
                                                  </td>
                                              </tr>';
                                
                        // Create the visualized task orientation as though this IS the parent
                        $firstFour = str_pad($row["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 ($row["ParentID"] != 0){
                            // Create the visualized task orientation as though this IS the parent
                            $firstFour = str_pad($row["ParentID"],4,"0",STR_PAD_LEFT);
                            $lastFour = str_pad($row["TaskID"],4,"0",STR_PAD_LEFT);
                            
                            // create html to show them that this is a child
                            $relationshipTextHTML = '<tr>
                                                        ' . $blankStatusID . '
                                                        ' . $secondaryStatusHTML . '
                                                    </tr>';
                        }

                        // Set button defaults
                        $activateMachiningButtonHTML = '';
                        $moveToNextPhaseButtonHTML = '';
                        $resyncTaskToToolsButtonHTML = '';
                        $putTaskInQueueButtonHTML = '';
                        $taskEditButtonHTML = '<button type="button" style="font-size:9px;" title="Edit this task." onclick="javascript:window.open(\'updateTask.php?updateTaskID=' . $row["TaskID"] . '&parentTaskId=' . $row["ParentID"] .  '&cs=' . $row["CompanyID"] .  '&ts=' . $row["TypeID"] . '\', \'_blank\');">...</button>';
                        
                        // Determine if their allowed to see this task
                        if ($row["ViewCategory"] == "NOT VIEWABLE" &&
                            $row["UserID"] != $userRow["UserID"]){
                            // Set the button who's default was something to nothing
                            $taskEditButtonHTML = '';
                        }
                        else {
                            // Determine if this task has routing on it
                            $statusAssocRow=null;
                            
                            // Determine if this is the machining task
                            if ($row["StatusName"]=="Machining") {
                                // Create the machining script to be this
                                $completeMachiningScript='taskIDToComplete=' . $row["TaskID"] . '; getUserToAssignNextPhase();';
                                
                                // Create a buttone that will allow the user to resync the machining task with any new code
                                $resyncTaskToToolsButtonHTML = '<button type="button" style="font-size:9px;" name="ResyncMachiningButton_' . $row["TheMachineID"] . '" id="ResyncMachiningButton_' . $row["TheMachineID"] . '" title="Remove any currently suggested tools, recalculate tools for current GCode/Machine/Task and create a new machining packet." onclick="javascript:if (!detectPopupBlocker(true)) {taskIDToResync=' . $row["TaskID"] . '; machineIDResyncing=' . $row["TheMachineID"] . '; resyncToolsToTaskDialog();} else {return false;}">⟳</button>';

                                // Set the default machining button to be one without routing
                                $moveToNextPhaseButtonHTML = '<button type="button" style="font-size:9px;" name="FinishMachiningButton_' . $row["TheMachineID"] . '" id="FinishMachiningButton_' . $row["TheMachineID"] . '" title="Finish this machining task and move it down the line." onclick="javascript:' . $completeMachiningScript . '">✔</button>';
                               
                                // Determine if it has routing
                                if ($row["MainBranchID"]!=null){
                                    // Create a query to get the next status to go to
                                    $sql='SELECT StatusID FROM taskstatusinfo_current WHERE TaskID=' . $row["TaskID"] . ' AND ExecutionOrder>' . $row["ExecutionOrder"] . ' ORDER BY ExecutionOrder LIMIT 1;';

                                    // Run the query
                                    $statusRow = $db->queryDB($sql, $userRow, "individual_machine_tasks Form occurance 5");

                                    // Determine if we got back a next status for the route
                                    if (mysqli_num_rows($statusRow)==1){
                                        // Get the nask task routing row to work with as the assoc style
                                        $statusAssocRow = $statusRow->fetch_assoc();

                                        // Create the machining script to be this
                                        $completeMachiningScript='taskIDToComplete=' . $row["TaskID"] . '; moveRouting(' . $row["TaskID"] . ', ' . $row["CurrentTaskStatusRoutingNodeID"] . ', ' . $row["MainBranchID"] . ', 9999, \'usersDialog\', \'UsersMoveRoutingHeader\', ' . $statusAssocRow["StatusID"] . ',\'U_\');';

                                        // Change the move to next phase button to include routing logic
                                        $moveToNextPhaseButtonHTML = '<button type="button" style="font-size:9px;" name="FinishMachiningButton_' . $row["TheMachineID"] . '" id="FinishMachiningButton_' . $row["TheMachineID"] . '" title="Finish this machining task and move it down the line." onclick="javascript:' . $completeMachiningScript . '">✔</button>';
                                    }
                                    else {
                                        // This task has routing, but cannot get off of machining.  
                                        // standard route from here to be final inspection.
                                        $sql='SELECT StatusID FROM status WHERE Name="Final Inspection";';

                                        // Run the query
                                        $statusRow = $db->queryDB($sql, $userRow, "individual_machine_tasks Form occurance 5");

                                        // Determine if we have a final inspection ID
                                        if (mysqli_num_rows($statusRow)==1){
                                            // Get Final Inspection status ID
                                            $statusAssocRow = $statusRow->fetch_assoc();

                                            // Create the machining script to be this
                                            $completeMachiningScript='taskIDToComplete=' . $row["TaskID"] . '; moveRouting(' . $row["TaskID"] . ', ' . $row["CurrentTaskStatusRoutingNodeID"] . ', ' . $row["MainBranchID"] . ', 9999, \'usersDialog\', \'UsersMoveRoutingHeader\', ' . $statusAssocRow["StatusID"] . ',\'U_\');';

                                            // Change the move to next phase button to include routing logic
                                            $moveToNextPhaseButtonHTML = '<button type="button" style="font-size:9px;" name="FinishMachiningButton_' . $row["TheMachineID"] . '" id="FinishMachiningButton_' . $row["TheMachineID"] . '" title="Finish this machining task and move it down the line." onclick="javascript:' . $completeMachiningScript . '">✔</button>';
                                        }
                                    }
                                }
                            }
                            else {
                                // Determine if they can change the task that is on the machine as machining now
                                if ($canChangeMachiningTask) {
                                    // Button to set this task as the currently machining task
                                    $activateMachiningButtonHTML = '<button type="button" style="font-size:9px;" title="Make this the current machining job at the top of the list. This will move any active machining tasks to the next state." onclick="javascript:taskIDToMove=' . $row["TaskID"] . '; machineIDForNewMachining=' . $row["TheMachineID"] . '; if (!detectPopupBlocker(true)) {getUserToMachiningTask(' . $openNonMachiningFirstBool . '); ' . $completeMachiningScript . '} else {return false;}">▲</button>';
                                    
                                    // Determine if this task has routing on it
                                    if ($row["MainBranchID"]!=null){
                                        // Create a query to get the machining queue ID
                                        $sql='SELECT StatusID FROM status WHERE Name="Machining";';

                                        // Run the query
                                        $statusRow = $db->queryDB($sql, $userRow, "individual_machine_tasks Form occurance 5");

                                        // Determine if we got back the status in question
                                        if (mysqli_num_rows($statusRow)==1){
                                            // Get the current task row to work with as the assoc style
                                            $statusAssocRow = $statusRow->fetch_assoc();

                                            // Create a default html for the button to go to machining with routing logic
                                            $activateMachiningButtonHTML = '<button type="button" style="font-size:9px;" title="Make this the current machining job at the top of the list. This will move any active machining tasks to the next state." onclick="javascript:taskIDToMove=' . $row["TaskID"] . '; machineIDForNewMachining=' . $row["TheMachineID"] . '; if (!detectPopupBlocker(true)) {moveRouting(' . $row["TaskID"] . ', ' . $row["CurrentTaskStatusRoutingNodeID"] . ', ' . $row["MainBranchID"] . ', 9999, \'machiningUsersDialog\', \'MachiningMoveRoutingHeader\', ' . $statusAssocRow["StatusID"] . ',\'MU_\', ' . $openNonMachiningFirstBool . '); shallowCopyRouteGoToInfoStrings=[...routeGoToInfoStrings];' . $completeMachiningScript . '} else {return false;}">▲</button>';
                                        }
                                    }
                                }
                            }

                            // Determine if this task is already in the queue
                            if ($row["StatusName"]!="Machining Queue") {
                                // Create a default html for the button to go to the queue
                                $putTaskInQueueButtonHTML = '<button type="button" style="font-size:9px;" title="This will put this task onto this machines queue." onclick="javascript:taskIDToMove=' . $row["TaskID"] . '; getUserToMachiningQueueTask();">2Q</button>';

                                // Determine if this task has routing on it
                                if ($row["MainBranchID"]!=null){
                                    // Create a query to get the machining queue ID
                                    $sql='SELECT StatusID FROM status WHERE Name="Machining Queue";';

                                    // Run the query
                                    $statusRow = $db->queryDB($sql, $userRow, "individual_machine_tasks Form occurance 5");

                                    // Determine if we got back the status in question
                                    if (mysqli_num_rows($statusRow)==1){
                                        // Get the current task row to work with as the assoc style
                                        $statusAssocRow = $statusRow->fetch_assoc();

                                        // Create a default html for the button to go to the queue with routing logic
                                        $putTaskInQueueButtonHTML = '<button type="button" style="font-size:9px;" title="This will put this task onto this machines queue." onclick="javascript:taskIDToMove=' . $row["TaskID"] . '; moveRouting(' . $row["TaskID"] . ', ' . $row["CurrentTaskStatusRoutingNodeID"] . ', ' . $row["MainBranchID"] . ', 9999, \'2QUsersDialog\', \'2QMoveRoutingHeader\', ' . $statusAssocRow["StatusID"] . ',\'2Q_\');">2Q</button>';
                                    }
                                }
                            }
//return 'ABORT WHITEBOARD POPULATE (individual_machine_tasks)::' . $putTaskInQueueButtonHTML;
                        }
                        
                        // Determine if this one has any tools to setup
                        $hasToolsToSetup = doesTaskHaveToolsToSetup ($db, $userRow, $row["TaskID"], $row["TheMachineID"]);

                        // Determine if there are tools that need to be changed out and then set things up.
                        $updateCellStyle='';
                        if ($hasToolsToSetup){
                            // Setup the cell to have the correct background
                            $updateCellStyle='style="background: white repeating-linear-gradient(45deg,rgba(77, 77, 77, .5),rgba(77, 77, 77, .5) 10px,rgba(230, 230, 0, .5) 10px,rgba(230, 230, 0, .5) 20px);"';
                        }
                        
                        // Give the the update option
                        $updateableTaskRowCellHTML = '
                            <div class="cell updateCell" ' . $updateCellStyle . '>
                                <table>
                                    <tr>
                                        <td style="text-align: center; vertical-align: middle;" colspan=2 >
                                        ' .
                                        $taskEditButtonHTML
                                        . '
                                        ' .
                                        $moveToNextPhaseButtonHTML
                                        . '
                                        ' .
                                        $activateMachiningButtonHTML
                                        . '
                                        ' .
                                        $putTaskInQueueButtonHTML
                                        . '
                                        ' .
                                        $resyncTaskToToolsButtonHTML
                                        . '
                                        </td>
                                    </tr>
                                        <td colspan=2>
                                        </td>
                                    <tr>
                                    </tr>
                                    ' .
                                    $relationshipTextHTML
                                    . '
                                </table>
                            </div>
                            ';

                        // Show company column
                        $companyTaskRowCellHTML = '
                            <div class="cell companyCell" style="background-color: '. $row["CompanyRowColor"] . ';">
                                    <p>' . $row["CompanyName"] . '</p>
                            </div>
                            ';

                        // Set it to the color of the row state 
                        $color = '#' . $row["StatusRowColor"];

                        // Determine if there is a fixture name
                        $fixtureName='none';
                        if ($row["FixtureToUseID"] != -1){
                            // Set it to the name of that fixture
                            $fixtureName=$row["FixtureName"];
                        }
                        
                        // Determine if this is a manual machining status
                        $textColorHTML='';
                        if ($row["StatusName"]=="Manual Machining"){
                            // Set the text to white
                            $textColorHTML=' color:#FFFFFF;';
                        }

                        // Set the secondary status as a base 
                        $secondaryStatusTitle = 'Secondary Status: ' . $row["SSName"] . ' - ' . $row["SSDescription"];

                        // Determine if this is manual machining and of normal secondary status
                        $textSecondaryColor='';
                        if ($row["StatusName"]=="Manual Machining" && 
                            $row["SecondaryStatusID"]==-1){
                            // Set the text to black
                            $textSecondaryColor='color:#000000;';
                        }

                        // set them to be something
                        $secondaryStatusBorder='border-color: #' . $row["SSRowColor"] . '; border-style: outset; border-width: 5px;';

                        // Determine if this is expedite or not
                        $expediteCellColor = "background-color:#48D1CC; "; // Medium Turquoise
                        $expediteHTML = '';
                        if ($row["Expedite"]==1){
                            // Set it to a hot color
                            $expediteCellColor = "background-color:#FF007F; "; // Hot Pink
                            
                            // Change the checkbox to checked
                            $expediteHTML = '<font style="color:black; font-size:30px;">✔</font>';
                        }
                        
                        // Add this row to the result
                        $result = $result .
                            '<li id="TID_' . $row["TaskID"] . '" class="ui-state-default Table">
                                <div name="test" title="' . $secondaryStatusTitle . '" class="Row" style="background-color: '. $color . '; ' . $secondaryStatusBorder . ' ' . $rowVisibility . '" ondblclick="addStickyNoteDialog(' . $row["TaskID"] . ');">
                                    <div class="cell expediteCell" style="position:relative; '. $expediteCellColor . $secondaryStatusBorder . ' ">' .
                                    $stickyNoteHTML .
                                    $expediteHTML . '
                                    </div>
                                    <div class="cell"  style="' . $textColorHTML . '">
                                        <p>' . $row["Title"] . '</p>
                                    </div>
                                    <div class="cell assignedToCell"  style="' . $textColorHTML . '">
                                        <p>' . $row["FirstName"] . ' ' . $row["LastName"] . '</p>
                                    </div>
                                    <div class="cell dueDateCell" style="' . $textColorHTML . '">
                                        <p>' . $row["DueDate"] . '</p>
                                    </div>
                                    <div class="cell fixtureCell"  style="' . $textColorHTML . '">
                                        <p>' . $fixtureName . '</p>
                                    </div>
                                    <div class="cell statusCell"  style="' . $textColorHTML . $secondaryStatusBorder . '">
                                        <p>' . $row["StatusName"] . '</p>
                                    </div>
                                    <div class="cell taskIDCell"  style="' . $textColorHTML . '">
                                        <p>' . $firstFour . '-' . $lastFour . '</p>
                                    </div>' . 
                                    $companyTaskRowCellHTML . 
                                    $updateableTaskRowCellHTML . '
                                </div>
                            </div>
                            </li>';
                    }
                }
                
                // Check to see if we have a string yet
                if ($result!=""){
                    // Remove the beginning pipes
                    $result=substr($result, 4);
                }
            }
            else {
                // set the return to be nothing
                return "";
            }
        } catch (Exception $ex) {
            // Assign the output string as to what happened
            return "";
        }

        // Return whatever we got
        return $result;
    }
    
    $db = new Database();
    $db->setupTmsDB();

    $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);
    
    // Set the return as fail at first
    $return="Fail";

    // If there is only one result for a username/password combo, then they are good to go.
    if ($currentUser != null){
        // Attempt to get the user row
        $userRow = $currentUser->fetch_assoc();

        // Go and get the machines and all of their tasks
        $return = retrieveTasksWithinMachines($db, $userRow);
    }

//echo 'ABORT WHITEBOARD POPULATE (individual_machine_tasks)::' . $return;
    echo $return;
?>   
