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

    function getAssociatedPosition($specificTool, $specificToolNamesWithPositions){
        // Set the return position to nothing at first
        $returnPosition=-1;
        
        // Create an array of the tools and positions requested
        $toolsAndPositions = explode("\n", $specificToolNamesWithPositions);

        // Loop through them to create the tool names string to query
        foreach ($toolsAndPositions as $toolAndPosition){
            // separate the position and tool
            $arr = explode('-', $toolAndPosition, 2);

            // Determine if it is more than one 
            if (count($arr)>1){
                // Determine if this one has the tool passed in
                if ($arr[1]==$specificTool){
                    // The first one should be the position
                    $returnPosition = trim(str_replace("T", "", $arr[0]));
                    
                    // Found it so leave the loop
                    break;
                }
            }
        }
        
        // Return whatever we found
        return $returnPosition;
    }

    function getToolsNotInDatabase($toolsReturnedFromDatabase, $specificToolNamesWithPositions){
        // Set the return position to nothing at first
        $returnNotFoundTools="";
        
        // Create an array of the tools and positions requested
        $toolsAndPositions = explode("\n", $specificToolNamesWithPositions);

        // Loop through them to create the tool names string to query
        foreach ($toolsAndPositions as $toolAndPosition){
            // separate the position and tool to get the tool alone.
            $arr = explode('-', $toolAndPosition, 2);

            // Determine if it is more than one 
            if (count($arr)>1){
                // Determine if the tool (arr[2]) is NOT in the database tools string
                if (strpos($toolsReturnedFromDatabase, trim($arr[1]))===false){
                    // This tool is NOT in there, so add it to the return string
                    $returnNotFoundTools = $returnNotFoundTools . trim($arr[1]). ",";
                }
            }
        }
        
        // Determine if there are tools that were NOT in the database
        if ($returnNotFoundTools!=""){
            // Remove the last comma
            $returnNotFoundTools= substr($returnNotFoundTools, 0, -1);
        }
        
        // Return whatever we found
        return $returnNotFoundTools;
    }

    function retrieveSpecificToolsAsList($db, $userRow, $specificToolNamesWithPositions){
        try {
            $result='';
            $toolIDsAndPositions='';

            // Check that there is a deliniator, if not they will get the whol;e database.
            if ($specificToolNamesWithPositions==null || $specificToolNamesWithPositions==""){
                // Set up an error message for the exception
                $result = 'ABORT ASSIGN (tools_in_gcode)::There are no tools in your gcode. ' . 
                          'Cannot query for an unlimited amount of tools. If there was a previous ' .
                          'G-Code it has been removed. To reverse this and get old G-Code back, ' .
                          'just refresh the task instead of update.';
            }
            else {
                // Create an array of the tools and positions requested
                $toolsAndPositions = explode("\n", $specificToolNamesWithPositions);
                
                // Loop through them to create the tool names string to query
                $specificToolNamesForQuery = "";
                foreach ($toolsAndPositions as $toolAndPosition){
                    $comma="";
                    // Determine if this is not the first one
                    if ($specificToolNamesForQuery!=""){
                        // There will need to be a comma added
                        $comma=",";
                    }
                    
                    // separate the position and tool, remove the position and grab 
                    // all others as the tool (incase there are more dashes).
                    $arr = explode('-', $toolAndPosition, 2);
                    unset($arr[0]);
                    $specificToolNamesForQuery = $specificToolNamesForQuery . $comma . '\'' . trim(implode('-', $arr)) . '\'';
                }
                
                // Initialize the return
                $result = $result .  
                        '<li id="GCode_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 assignedToolsTypeCell">
                                     <p><b>Type</b></p>
                                 </div>
                            </div>
                        </li>';

                // Setup the query to get all assigned tools available
//                    $sql = 'SELECT t.*, asst.*, tt.Name AS ToolTypeName, tt.RowColor AS ToolTypeRowColor, tt.CategoryName ' . 
                $sql = 'SELECT t.*, tt.Name AS ToolTypeName, tt.RowColor AS ToolTypeRowColor, tt.CategoryName ' . 
                       'FROM tools t ' .
//                           'LEFT JOIN assignedtools asst ON t.ToolID = asst.CurrentToolID ' .
                       'LEFT JOIN tooltype tt ON t.ToolTypeID = tt.ToolTypeID ' .
                       'WHERE t.Name in ('. $specificToolNamesForQuery . ') ' .
                       'ORDER BY ToolTypeName ASC;';

                // Query the database for the tools 
                $topLevelRows = $db->queryDB($sql, $userRow, "tools_in_gcode 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) {
                    // Create a string to hold all names that were returned
                    $toolsReturnedFromDatabase="";
                    
                    // Loop through the returned results
                    while ($topLevelRow=mysqli_fetch_array($topLevelRows)){
                        // Determine if it is a tool with no quantity
                        $lowQuantityRowHTML='';
                        $lowQuantityTitle='';
                        if ($topLevelRow["Amount"]<=0){
                            // This one is common
                            $lowQuantityRowHTML=' expediteTaskBackground';

                            // Setup the title
                            $lowQuantityTitle='This tool has a zero quantity in the database.  Please check to ensure this is in stock before issuing the job.';
                        }
                        
                        // Set the color of the main row
                        $color = $topLevelRow["ToolTypeRowColor"];

                        // Setup the result to send back to the user
                        $result = $result .
                            '<li id="GCode_Tool_' . $topLevelRow["ToolID"] . '" class="queriedtoolrow type_' . $topLevelRow["ToolTypeID"] . ' ui-state-default Table ' . $lowQuantityRowHTML . '">
                                <div class="Row" style="background-color: '. $color . ';" title="' . $lowQuantityTitle . '">
                                    <div class="cell nameCell">
                                        <span>
                                            <p>' . trim($topLevelRow["Name"]) . '</p>
                                        </span>
                                    </div>
                                    <div class="cell assignedToolsTypeCell">
                                        <span>
                                            <p>' . $topLevelRow["ToolTypeName"] . '</p>
                                        </span>
                                    </div>
                                </div>
                            </li>';

                            // Add the tool to the string I will pass
                            $toolIDsAndPositions = $toolIDsAndPositions . $topLevelRow["ToolID"] . ':' .
                                    getAssociatedPosition(trim($topLevelRow["Name"]), $specificToolNamesWithPositions) . ',';
                                    
                            // Add this tool name to the string
                            $toolsReturnedFromDatabase=$toolsReturnedFromDatabase . " " . trim($topLevelRow["Name"]);
                            
                            // Increment the order
                            $order=$order+1;
                    }
                    
                    // Remove the last comma
                    $toolIDsAndPositions = $toolIDsAndPositions==""?$toolIDsAndPositions:substr($toolIDsAndPositions, 0, -1);
                    
                    // Add the tools to the result
                    $result = $toolIDsAndPositions . '~~||***||~~' . $result; 
                    
                    // Get any tools that were NOT returned by the query
                    $toolsNotInDatabase = getToolsNotInDatabase($toolsReturnedFromDatabase, $specificToolNamesWithPositions);
                    
                    // Determine if there are tools that are NOT in the database
                    if ($toolsNotInDatabase!=""){
                        // Add the tools not in the database to the result
                        $result = $result . '~~||***||~~' . $toolsNotInDatabase; 
                    }
                }
                else {
                    // Set up an error message for the exception
                    $result = 'ABORT ASSIGN (tools_in_gcode)::There were no tools found ' . 
                              'in the database for the query of tools from the GCode. \\n\\n' . 
                              'The tools used in the query were "' . $specificToolNamesForQuery . '" ' . 
                              'If there was a previous G-Code it has been removed. To reverse this ' .
                              'and get old G-Code back, just refresh the task instead of update.';
                }
            }
        } catch (Exception $ex) {
            // Set up an error message for the exception
            $result = 'ABORT ASSIGN (tools_in_gcode)::There was an error trying to get the ' . 
                      'tools set from the GCode.\n\n The error is: ' . $ex->getMessage() . 
                      'If there was a previous G-Code it has been removed. To reverse this ' .
                      'and get old G-Code back, just refresh the task instead of update.';
        }

        // 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 (tools_in_gcode)::Your session has expired.  ' . 
             'Refresh the page before modifying tools.' . 
             'If there was a previous G-Code it has been removed. To reverse this ' .
             'and get old G-Code back, just refresh the task instead of update.';
    }
    else {
        // Set defaults for the passed in variables
        $specificToolNames=-1;

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

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

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





