<?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:black; 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:#A28FF4; 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:#8065F8; 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:#5E3CF6; font-size: 11px;">⚫</label>';
            }
            
            // Finish the cell
            $result=$result . '</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>Expedite</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, ' .
                       '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 ' .
                '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 (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 ';

            // 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;
                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){
                        // 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;
                        }
                    }
                    
                    // 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"]);
                        
                        // create html to show them that this is a child
                        $relationshipTextHTML = '<tr>
                                                    <td style="text-align: left; vertical-align: middle;" colspan=1>
                                                          <label style="font-size:10px; font-weight: bold; color:Black;">parent&nbsp;</label>
                                                    </td>
                                                    ' . $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 parent
                            $relationshipTextHTML = '<tr>
                                                        <td style="text-align: left; vertical-align: middle;" colspan=1>
                                                            <label style="font-size:10px; font-weight: bold; color:Black;">child&nbsp;&nbsp;&nbsp;&nbsp;</label>
                                                        </td>
                                                        ' . $secondaryStatusHTML . '
                                                    </tr>';
                        }

                        // Set button defaults
                        $activateMachiningButtonHTML = '';
                        $moveToNextPhaseButtonHTML = '<button type="button" style="font-size:9px;" title="Finish this machining task and move it down the line." onclick="javascript:taskIDToComplete=' . $row["TaskID"] . '; getUserToAssignNextPhase();">✔</button>';
                        $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 two buttons who's default was something to nothing
                            $moveToNextPhaseButtonHTML = '';
                            $taskEditButtonHTML = '';
                        }
                        else {
                            // Determine if this is the machining task
                            if ($row["StatusName"]!="Machining") {
                                // 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();} else {return false;}">▲</button>';
                                }

                                // If it is not the machining task, then no need for this
                                $moveToNextPhaseButtonHTML = '';
                            }

                            // Determine if this task is already in the queue
                            if ($row["StatusName"]!="Machining Queue") {
                                // Create a default html for the button to finish machining job
                                $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 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
                                        . '
                                        </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 $return;
?>   
