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

    function retrieveAllToolsAsList($db, $userRow){
        $editPrivilegesRowHTML = '';
        
        // Initialize the return
        $result = 
            'Type: ' .
            getToolTypeHTML($db, $userRow, 'typeForAll', $type, 1, 'javascript:displayCorrectTypesAll();', 1) .
            '<br><br>
            <li id="New_Tool_Header" class="ui-state-default ui-state-disabled Table">
                <div class="Heading">
                    <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 toolsDiameterCell removeForTask">
                        <p><b>Diameter</b></p>
                    </div>
                    <div class="cell toolsCuttingLengthCell removeForTask">
                        <p><b>Cutting Length</b></p>
                    </div>
                    <div class="cell toolsCornerRadiusCell removeForTask">
                        <p><b>Corner Radius</b></p>
                    </div>
                    <div class="cell toolsAngleCell removeForTask">
                        <p><b>Angle</b></p>
                    </div>
                    <div class="cell toolsFluteNumberCell removeForTask">
                        <p><b>Flute #</b></p>
                    </div>
                    <div class="cell toolsTypeCell">
                        <p><b>Type</b></p>
                    </div>
                    <div class="cell updateCell removeForTask">
                        <p><b>Select</b></p>
                    </div>
                </div>
            </li>';

        try {
            // Setup the query to get all tools available
            $sql='SELECT t.* , tt.Name AS ToolTypeName, tt.RowColor AS ToolTypeRowColor, tt.CategoryName ' . 
                 'FROM tools t ' . 
                 'LEFT JOIN tooltype tt ON t.ToolTypeID = tt.ToolTypeID ' .
                 'LEFT OUTER JOIN ' . 
                 '( SELECT count(*) AS AmountAssignedTo, CurrentToolID FROM assignedtools ' . 
                    'GROUP BY CurrentToolID ) ct ON t.ToolID = ct.CurrentToolID ' . 
                    'WHERE tt.CategoryName="TOOL" ' .
                    'ORDER BY ToolTypeName ASC, t.Diameter, t.CuttingLength, t.FluteNumber, t.Brand;';
//return $sql;            
            // Query the database for the tools 
            $rows = $db->queryDB($sql, $userRow, "all_toollist Form occurance 1");

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

            //Set the current type to nothing
            $loopToolType='';

            // Determine if there were rows returned
            if (mysqli_num_rows($rows)!=0) {
                // Loop through the returned results
                while ($row=mysqli_fetch_array($rows)){
                    // Set the color to be whatever is set for this particular type of tool
                    $color=$row["ToolTypeRowColor"];

                    // They have edit privileges and this is for the selecting
                    $editPrivilegesRowHTML = 
                            '        <div class="cell updateCell removeForTask">
                                        <span>
                                            <table>
                                                <tr>
                                                    <td>
                                                        <button type=button onclick="javascript: newToolSelectedForTask(' . $order . ', ' . $row["ToolID"] . ');" title="Choose a this tool as the selected tool for the position.">Select</button>
                                                    </td>
                                                </tr>
                                            </table>
                                        </span>
                                    </div>';
                    
                    // Determine if the loop type is different than the last one
                    if ($loopToolType!=$row["ToolTypeID"]){
                        // Determine if this is NOT the first type
                        if ($loopToolType!=''){
                            // Finish the last type div
                            $result = $result . '</DIV>';
                        }

                        // Set the type we are keeping track of as the new type
                        $loopToolType=$row["ToolTypeID"];

                        // set the ID to have underscores where spaces are
                        $id = str_replace(" ", "_", $loopToolType);

                        // Set the name of the new type as the ID
                        $result = $result . '<DIV id="' . $id . '">';
                    }

                    // Setup the result to send back to the user
                    $result = $result .
                                '<li id="New_Tool_' . $order . '" class="ui-state-default Table">
                                    <div class="Row" style="background-color: '. $color . ';">
                                <div class="cell nameCell">
                                    <span>
                                        <p>' . $row["Name"] . '</p>
                                    </span>
                                </div>
                                <div class="cell brandCell removeForTask">
                                    <span>
                                        <p>' . $row["Brand"] . '</p>
                                    </span>
                                </div>
                                <div class="cell pnCell removeForTask">
                                    <span>
                                        <p>' . $row["PartNumber"] . '</p>
                                    </span>
                                </div>
                                <div class="cell toolsDiameterCell removeForTask">
                                    <span>
                                        <p>' . $row["Diameter"] . '</p>
                                    </span>
                                </div>
                                <div class="cell toolsCuttingLengthCell removeForTask">
                                    <span>
                                        <p>' . $row["CuttingLength"] . '</p>
                                    </span>
                                </div>
                                <div class="cell toolsCornerRadiusCell removeForTask">
                                    <span>
                                        <p>' . $row["Radius"] . '</p>
                                    </span>
                                </div>
                                <div class="cell toolsAngleCell removeForTask">
                                    <span>
                                        <p>' . $row["Angle"] . '</p>
                                    </span>
                                </div>
                                <div class="cell toolsFluteNumberCell removeForTask">
                                    <span>
                                        <p>' . $row["FluteNumber"] . '</p>
                                    </span>
                                </div>
                                <div class="cell toolsTypeCell">
                                    <span>
                                        <p>' . $row["ToolTypeName"] . '</p>
                                    </span>
                                </div>'
                                .
                                $editPrivilegesRowHTML 
                                .
                            '</div>
                        </li>';

                    // Determine if the loop type is different than the last one
                    if ($loopToolType!=$row["ToolTypeID"]){
                        // End the DIV Set the name of the type as the ID
                        $result = $result . '<DIV id="' . $loopToolType . '"';
                    }

                    // Increment the order
                    $order=$order+1;
                }
            }
            else {
                // Set up an error message for the exception
                $result = 'ABORT ASSIGN (all_toollist)::There were no tools found. ' . 
                          'Ensure there are tools in the TMS.';
            }

            // Determine if the loop did the loopty loop
            if ($loopToolType!=''){
                // Finish the last type div
                $result = $result . '</DIV>';
            }


        } catch (Exception $ex) {
            // Set up an error message for the exception
            $result = 'ABORT ASSIGN (all_toollist)::There was an error trying to get a ' . 
                      'list of tools in the TMS.\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 (all_toollist)::Your session has expired.  ' . 
             'Refresh the page before assigning tools.';
    }
    else {
        // Attempt to get the user row
        $userRow = $currentUser->fetch_assoc();

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

