<?php    
    include '../global_after_session.php';
    include '../database.php';
    include '../presentation.php';

    function retrieveAssignedToolsAsList($db, $userRow, $machineID){
        $editPrivilegesRowHTML = '';
        $machineNameRowHTML = '';
        $result='';

        // Initialize the return
        $result = $result .  
                'Type: ' .
                getToolTypeHTML($db, $userRow, 'typeForAssigned', -1, 1, 'javascript:displayCorrectTypesAssignedByClass();', 1) .
                '<br><br>                    
                <li id="Assigned_Tool_Header" class="ui-state-default ui-state-disabled Table"> 
                    <div class="Heading">
                        <div class="cell machineNameCell removeForTask">
                             <p><b>Machine</b></p>
                         </div>
                        <div class="cell assignedToolsPositionCell removeForTask">
                             <p><b>#</b></p>
                         </div>
                         <div class="cell nameCell">
                             <p><b>Name</b></p>
                         </div>
                         <div class="cell brandCell removeForTask">
                             <p><b>Brand</b></p>
                         </div>
                         <div class="cell pnCell removeForTask">
                             <p><b>Part Number</b></p>
                         </div>
                         <div class="cell assignedToolsDiameterCell removeForTask">
                             <p><b>Diameter</b></p>
                         </div>
                         <div class="cell assignedToolsCuttingLengthCell removeForTask">
                             <p><b>Cutting Length</b></p>
                         </div>
                         <div class="cell assignedToolsCornerRadiusCell removeForTask">
                             <p><b>Corner Radius</b></p>
                         </div>
                         <div class="cell assignedToolsAngleCell removeForTask">
                             <p><b>Angle</b></p>
                         </div>
                         <div class="cell assignedToolsFluteNumberCell removeForTask">
                             <p><b>Flute #</b></p>
                         </div>
                         <div class="cell assignedToolsTypeCell">
                             <p><b>Type</b></p>
                         </div>
                         <div class="cell assignedToolsExposedLengthCell removeForTask">
                             <p><b>Exposed Length</b></p>
                         </div>
                         <div class="cell toolUpdateCell removeForTask">
                             <p><b>Select</b></p>
                         </div>
                    </div>
                </li>';

        try {
                // Setup the query to get all assigned tools available
                $sql = 'SELECT at.*, t.*, m.Name as MachineName, tt.Name AS ToolTypeName, tt.RowColor AS ToolTypeRowColor, tt.CategoryName ' . 
                       'FROM assignedtools at ' . 
                       'LEFT JOIN tools t ON at.CurrentToolID = t.ToolID ' .
                       'LEFT JOIN machines m ON at.MachineID = m.MachineID ' .
                       'LEFT JOIN tooltype tt ON t.ToolTypeID = tt.ToolTypeID ' .
                       'WHERE CurrentToolID != -1 '. 
                       'AND at.machineID = ' . $machineID . ' ' .
                       'ORDER BY MachineName, Position, ToolTypeName ASC;';

            // Query the database for the tools 
            $topLevelRows = $db->queryDB($sql, $userRow, "assigned_toollist Form occurance 1");

            // Set the order to start with at 1
            $order=1;

            // Determine if there were rows returned
            if (mysqli_num_rows($topLevelRows)!=0) {
                // Loop through the returned results
                while ($topLevelRow=mysqli_fetch_array($topLevelRows)){
                    // init variables
                    $exposedLengthHTML = '';
                    $rowClass='';

                    // Determine if there is an exposed length
                    if ($topLevelRow["ExposedLength"]!=0) {
                        // Color the exposed length
                        $exposedLengthHTML = 'style="background-color: Yellow;"';
                    }

                    // Set the color of the main row
                    $color = $topLevelRow["ToolTypeRowColor"];
                    
                    // assume the update cell is meant to be the same color as the main row
                    $toolUpdateCellStyleCSS = 'style="background-color: ' . $color . ';"';

                    // Determine if this will have a suggested class or not
                    if ($topLevelRow["SuggestedChangeNewToolID"]>0){
                        // This one is suggested only
                        $rowClass=' suggestedBackground';
                        
                        // White is a good color
                        $toolUpdateCellStyleCSS = 'style="background-color: white;"';
                    }

                    // Determine if this is a common tool
                    if ($topLevelRow["CommonTool"]==1){
                        // This one is common
                        $rowClass=' commonToolBackground';

                        // White is a good color
                        $toolUpdateCellStyleCSS = 'style="background-color: white;"';
                    }

                    // Setup the border color and title
                    $updateStyle = $toolUpdateCellStyleCSS;
                    $borderTitle = '';

                    // Determine if We are supposed to remove after use
                    if ($topLevelRow["RemoveAfterUse"]!=0) {
                        // Color the button
                        $updateStyle = 'border: 4px solid Black; ' . $updateStyle;

                        // Change the text
                        $borderTitle = 'This tool will be removed after use. ' .
                                       'Realize this when assigning it for your job.';
                    }

                    // They have edit privileges and this is for the selecting
                    $machineNameRowHTML = 
                            '        <div class="cell machineNameCell removeForTask">
                                        <span>
                                            <p>' . $topLevelRow["MachineName"] . '</p>
                                        </span>
                                    </div>';

                    // They have edit privileges and this is for the selecting
                    $editPrivilegesRowHTML = 
                            '        <div class="cell toolUpdateCell' . $rowClass . ' removeForTask" ' . $toolUpdateCellStyleCSS . '>
                                        <span>
                                            <table>
                                                <tr>
                                                    <td>
                                                        <input class="selectTool" type="checkbox" style="width:25px;height:25px;">
                                                    </td>
                                                </tr>
                                            </table>
                                        </span>
                                    </div>';

                    
                    // Setup the result to send back to the user
                    $result = $result .
                        '<li id="Assigned_Tool_' . $order . '" class="toolrow type_' . $topLevelRow["ToolTypeID"] . ' ui-state-default Table" Title="' . $borderTitle . '" style="' . $updateStyle . '">
                            <input type="hidden" name="displayedToolID' . $order . '" id="displayedToolID' . $order . '" value="' . $topLevelRow["CurrentToolID"] . '"/>
                            <input type="hidden" name="displayedAssignedToolMachinePosition' . $order . '" id="displayedAssignedToolMachinePosition' . $order . '" value="' . $topLevelRow["Position"] . '"/>
                            <input type="hidden" name="displayedAssignedToolNotes' . $order . '" id="displayedAssignedToolNotes' . $order . '" value="' . $topLevelRow["Notes"] . '"/>
                            <input type="hidden" name="displayedAssignedToolRemoveAfter' . $order . '" id="displayedAssignedToolRemoveAfter' . $order . '" value="' . $topLevelRow["RemoveAfterUse"] . '"/>
                            <input type="hidden" name="displayedUseNewTool' . $order . '" id="displayedUseNewTool' . $order . '" value="' . $topLevelRow["UseNewTool"] . '"/>
                            <div class="Row" style="background-color: '. $color . ';">' 
                                .
                                $machineNameRowHTML 
                                .
                                '<div class="cell assignedToolsPositionCell removeForTask">
                                    <span>
                                        <p>' . $topLevelRow["Position"] . '</p>
                                    </span>
                                </div>
                                <div class="cell nameCell">
                                    <span>
                                        <p>' . trim($topLevelRow["Name"]) . '</p>
                                    </span>
                                </div>
                                <div class="cell brandCell removeForTask">
                                    <span>
                                        <p>' . trim($topLevelRow["Brand"]) . '</p>
                                    </span>
                                </div>
                                <div class="cell pnCell removeForTask">
                                    <span>
                                        <p>' . $topLevelRow["PartNumber"] . '</p>
                                    </span>
                                </div>
                                <div class="cell assignedToolsDiameterCell removeForTask">
                                    <span>
                                        <p>' . $topLevelRow["Diameter"] . '</p>
                                    </span>
                                </div>
                                <div class="cell assignedToolsCuttingLengthCell removeForTask">
                                    <span>
                                        <p>' . $topLevelRow["CuttingLength"] . '</p>
                                    </span>
                                </div>
                                <div class="cell assignedToolsCornerRadiusCell removeForTask">
                                    <span>
                                        <p>' . $topLevelRow["Radius"] . '</p>
                                    </span>
                                </div>
                                <div class="cell assignedToolsAngleCell removeForTask">
                                    <span>
                                        <p>' . $topLevelRow["Angle"] . '</p>
                                    </span>
                                </div>
                                <div class="cell assignedToolsFluteNumberCell removeForTask">
                                    <span>
                                        <p>' . $topLevelRow["FluteNumber"] . '</p>
                                    </span>
                                </div>
                                <div class="cell assignedToolsTypeCell">
                                    <span>
                                        <p>' . $topLevelRow["ToolTypeName"] . '</p>
                                    </span>
                                </div>
                                <div class="cell assignedToolsExposedLengthCell removeForTask" ' . $exposedLengthHTML . '>
                                    <span>
                                        <p>' . $topLevelRow["ExposedLength"] . '</p>
                                        <input type="hidden" name="displayedAssignedToolExposedLength' . $order . '" id="displayedAssignedToolExposedLength' . $order . '" value="' . $topLevelRow["ExposedLength"] . '"/>
                                    </span>
                                </div>'
                                .
                                $editPrivilegesRowHTML 
                                .
                            '</div>
                        </li>';

                        // Increment the order
                        $order=$order+1;
                }
            }
            else {
                // Set up an error message for the exception
                $result = 'ABORT ASSIGN (assigned_toollist)::There were no tools found ' . 
                          'assigned to machines.  Ensure the machines have tools.';
            }

        } catch (Exception $ex) {
            // Set up an error message for the exception
            $result = 'ABORT ASSIGN (assigned_toollist)::There was an error trying to get the ' . 
                      'list of tools assigned to machines.\n\n The error is: ' . $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 ASSIGN (assigned_toollist)::Your session has expired.  ' . 
             'Refresh the page before assigning tools.';
    }
    else {
        // Set defaults for the passed in variables
        $machineID=-1;

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

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

        // Go and get the machines and all of their tasks
        echo retrieveAssignedToolsAsList($db, $userRow, $machineID);
    }
    
?>   

