<?php    
function getPositionAsSelectOptions($selected, $name, $maxMachineSlots, $onChangeHTML, $allFieldsAccess=""){
    $result="";

    try {
        // Set disabled to be whatever was passed in
        $disableHTML=$allFieldsAccess;

        // Initialize the return with a non result
        $result='<select class="ToolPositionChild" name="' . $name . '" id="' . $name . '" onchange="' . 
                $onChangeHTML . '"' . $disableHTML . '>' . 
                '<option value="-1" selected>Machine Not Set</option>' .
                '</select>';

        // If there are rows then they are good to go.
        if ($maxMachineSlots <= 0){
            // Add this option to the select
            $result= '<option value="-1">Machine Not Set</option>' . $result;
        }
        else{
            // Re initialize the result
            $result = "";

            // Loop throught the results
            for ($i=1; $i<=$maxMachineSlots; $i++){
                // Determine if this is one that is to be selected
                $selectedText=-1;
                if (is_numeric($selected) != null and $selected==$i) {
                    // Create the selected html
                    $selectedText='selected';
                }

                // Add this option to the select
                $result=$result . '<option value="' . $i . '" ' . $selectedText . '>Slot ' . $i . '</option>';
            }

            // Add this option to the select
            $result= '<option value="0">Slot Not Set</option>' . $result;
            
            // Start the return with the beginning of the select
            $result='<select class="ToolPositionChild" name="' . $name . '" id="' . $name . '" onchange="' . 
                    $onChangeHTML . '"' . $disableHTML . '>' . $result . 
                    '</select>';
        }
    } catch (Exception $ex) {
        // Assign the output string as to what happened
        return $result;
    }

    // Return whatever we got
    return $result;
}

function retrieveCurrentTools($db, $userRow, $inTaskID, &$validationHTML=""){
    // Set the return result to nothing in case nothing is passed in for task number
    $result='';

    try {
        // Determine if this person is of the main company
        if ($userRow["CompanyID"]!=1){
            // Just leave
            return $result;
        }
        
        // Init necessary variables
        $taskID=$inTaskID;

        // Determine if I am supposed to check for current tools or not
        if ($taskID!=null && is_numeric($taskID)){
            // Create the query to get the the tools and the user that created the tools
            $sql = 'SELECT ttl.*, ' .
                   '       t.Name AS ToolName, t.Amount, ' .
                   '       tt.Name AS ToolTypeName, tt.RowColor AS ToolTypeRowColor, ' .
                   '       tmlm.MaxTools, t2.UserID, t2.StatusID, s.ProcessOrder  ' .
                   'FROM tooltotasklinker ttl ' . 
                   'LEFT JOIN tools t ON ttl.ToolID = t.ToolID ' .
                   'LEFT JOIN tooltype tt ON t.ToolTypeID = tt.ToolTypeID ' .
                   'LEFT JOIN tasktomachinelinker tml ON ttl.TaskID = tml.TaskID ' .
                   'LEFT JOIN machines tmlm ON tml.MachineID = tmlm.MachineID ' .
                   'LEFT JOIN tasks t2  ON ttl.TaskID = t2.TaskID ' . 
                   'LEFT JOIN status s  ON t2.StatusID = s.StatusID ' . 
                   'WHERE ttl.TaskID=' . $taskID . ' ' .
                   'ORDER BY ttl.ToolPosition;';
            
             // Attempt to get all of the tools for this task ID
            $rows = $db->queryDB($sql, $userRow, "tools_presentation Form occurance 5");

            // Determine if there were rows for the task(s)
            if ($rows != null && 
                mysqli_num_rows($rows)>0){
                // Init some variables
                $toolsIDArray=null;
                
                // Reset the validation HTML
                $validationHTML='';

                // Loop through the returned results
                while ($row=mysqli_fetch_array($rows)){
                    // Set the things we can
                    $toolToTaskLinkerID=$row["ToolToTaskLinkerID"];
                    $toolID = $row["ToolID"];
                    $toolPosition = $row["ToolPosition"];
                    $toolRequiredExposedLength = $row["ExposedLength"];
                    $toolNote = $row["Notes"];
                    $removeToolAfter = $row["RemoveAfterUse"];
                    $useNewTool = $row["UseNewTool"];
                    
                    $toolName = $row["ToolName"];
                    $toolTypeName = $row["ToolTypeName"];
                    $maxMachineTools = $row["MaxTools"];
                    $displayColor = $row["ToolTypeRowColor"];
                    
                    $removeAfterHTML = ($removeToolAfter==1)?'checked':'';
                    $useNewToolHTML = ($useNewTool==1)?'checked':'';
                    
                    // Start the display header row with basic stuff and add any basic stuff added
                    $displayHeaderRow =   
                            '<li id="editCellIDForHeader' . $toolToTaskLinkerID . '" name="editCellIDForHeader' . $toolToTaskLinkerID . '" 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" style="width: 40%;">
                                         <p><b>Type</b></p>
                                     </div>
                                </div>
                            </li>';
                
                    // Start the display header row with basic stuff and add any basic stuff added
                    $displayRow =   
                            '<li id="editCellIDFor' . $toolToTaskLinkerID . '" name="editCellIDFor' . $toolToTaskLinkerID . '" class="ui-state-default Table"> 
                                <div class="Row" style="background-color: '. $displayColor . ';">
                                     <div class="cell nameCell">
                                        <span>
                                            <p>' . trim($toolName) . '</p>
                                        </span>
                                     </div>
                                     <div class="cell assignedToolsTypeCell" style="width: 40%;">
                                        <span>
                                            <p>' . $toolTypeName . '</p>
                                        </span>
                                     </div>
                                </div>
                            </li>';

                    // Create a default html for the button to edit the task
                    $newToolButtonHTML = '<button type="button" title="Get a tool from the full list of tools to assign it to this position." onclick="javascript:toolSlotIDToModifyRow=' . $toolToTaskLinkerID . '; updatingtool=true; chooseTool(true);"/>New</button>';

                    // Determine if it is a tool with no quantity
                    $lowQuantityRowHTML='';
                    $lowQuantityTitle='';
                    if ($row["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.';
                    }

                    // Start adding the notes that are in the database
                    $result = $result . 
                                '<div id="currentTool' . $toolToTaskLinkerID . '" class="toolTable" name="currentTool' . $toolToTaskLinkerID . '" >   
                                    <table style="margin: 5px; width: 100%; border-top-style:dashed; border-width: 1px; display: inline-block; text-align: center;">
                                        <tr style="width: 100%; margin: 5px; vertical-align: middle; font-weight: bold;"> 
                                            <td style="width: 10%; align: center;">
                                                <label>Position</label>
                                            </td>
                                            <td style="width: 14%; align: center;">
                                                <label>Remove After</label>
                                            </td>
                                            <td style="width: 10%; align: center;">
                                                <label>Use New</label>
                                            </td>
                                            <td style="width: 14%; align: center;">
                                                <label>Req Exposed</label>
                                            </td>
                                            <td>
                                                <label>Notes</label>
                                            </td>
                                            <td style="width: 10%; align: center;">
                                                <label>Actions</label>
                                            </td>
                                            <td style="width: 10%; align: center;">
                                                <label>Remove</label>
                                            </td>
                                        </tr>
                                        <tr style="width: 100%; margin: 5px; vertical-align: middle;"> 
                                            <td style="align: center;">
                                                <div class="ToolPositionParent" title="' . $toolToTaskLinkerID . '">
                                                    <input id="previousToolPosition' . $toolToTaskLinkerID . '" name="previousToolPosition' . $toolToTaskLinkerID . '" class="PreviousToolPosition" type="hidden" value="' . $toolPosition . '"></input>
                                                    ' . getPositionAsSelectOptions($toolPosition, "toolPosition" . $toolToTaskLinkerID, $maxMachineTools, $onChangeHTML) . '
                                                </div>
                                            </td>
                                            <td style="align: center;">
                                                <input name="removeToolAfter' . $toolToTaskLinkerID . '" id="removeToolAfter' . $toolToTaskLinkerID . '" type="checkbox" ' . $removeAfterHTML . '>
                                            </td>
                                            <td style="align: center;">
                                                <input name="useNewTool' . $toolToTaskLinkerID . '" id="useNewTool' . $toolToTaskLinkerID . '" type="checkbox" ' . $useNewToolHTML . '>
                                            </td>
                                            <td style="align: center;">
                                                <textarea name="requiredExposedLength' . $toolToTaskLinkerID . '" id="requiredExposedLength' . $toolToTaskLinkerID . '" maxlength="15" class="intext" style="width: 50px; text-align: center; resize: none;" rows=1>' . $toolRequiredExposedLength . '</textarea>
                                            </td>
                                            <td>
                                                <textarea name="toolNote' . $toolToTaskLinkerID . '" id="toolNote' . $toolToTaskLinkerID . '" maxlength="1000" style="resize: vertical; max-width: 100%; max-height: 100%;" rows=1>' . $toolNote . '</textarea>
                                            </td>
                                            <td style="align: center;">
                                                ' 
                                                . 
                                                $newToolButtonHTML 
                                                . 
                                                '
                                            </td>
                                            <td style="align: center;">
                                                <input class="notinput" type="checkbox" id="removeTool' . $toolToTaskLinkerID . '" name="removeTool' . $toolToTaskLinkerID . '" title="This being checked on update will remove the tool." value="' . $toolToTaskLinkerID . '"></input>
                                            </td>
                                        </tr>
                                        
                                        <tr id="toolChoiceRow' . $toolToTaskLinkerID . '" name="toolChoiceRow' . $toolToTaskLinkerID . '" style="width: 100%; margin: 5px; vertical-align: middle; font-weight: bold;" class="' . $lowQuantityRowHTML . '" title="' . $lowQuantityTitle . '"> 
                                            <td id="toolChoiceCell' . $toolToTaskLinkerID . '" name="toolChoiceCell' . $toolToTaskLinkerID . '" colspan=7; style="width: 100%; margin: 5px; vertical-align: center;">
                                                <input id="toolChosenID' . $toolToTaskLinkerID . '" name="toolChosenID' . $toolToTaskLinkerID . '" type="hidden" class="taskToolID" value="' . $toolID . '"></input>
                                                <input id="previousToolChosenID' . $toolToTaskLinkerID . '" name="previousToolChosenID' . $toolToTaskLinkerID . '" class="PreviousTool" type="hidden" value="' . $toolID . '"></input>
                                                ' 
                                                . 
                                                $displayHeaderRow 
                                                . 
                                                $displayRow 
                                                . 
                                                '
                                            </td>
                                        </tr>
                                    </table>
                                </div>
                                ';


                    // Add something to the array list
                    $toolsIDArray = $toolsIDArray . $toolToTaskLinkerID . '|';
                    
                    // Add the validators for these
                    $validationHTML = $validationHTML . '
                                        frmvalidator.addValidation("requiredExposedLength' . $toolToTaskLinkerID . '",
                                                                   "req",
                                                                   "Please enter an exposed length for all tools.");
                                        frmvalidator.addValidation("requiredExposedLength' . $toolToTaskLinkerID . '",
                                                                   "num",
                                                                   "Please enter an exposed length for all tools as a number.");
                                        frmvalidator.addValidation("requiredExposedLength' . $toolToTaskLinkerID . '",
                                                                   "greaterthan=-.0000000001",
                                                                   "Please enter an exposed length for all tools as a number.");
                                        frmvalidator.addValidation("toolChosenID'. $toolToTaskLinkerID .'",
                                                                   "req",
                                                                   "There should be a tool chosen for all slots added.");
                                        frmvalidator.addValidation("toolChosenID'. $toolToTaskLinkerID .'",
                                                                   "greaterthan=-1",
                                                                   "There should be a tool chosen for all slots added.");
                                    ';
                    
                }
                
                // Add the hidden field to the form
                $result = 
                        '<label style="font-size: 20px;"><strong>Current Tools: </strong></label>
                         <div id="currentToolsDiv" style="">
                             <input type="hidden" name="currentToolsArray" id="currentToolsArray" value="' . $toolsIDArray . '"></input>
                             ' .
                             $result .
                        '</div>';
            }
        }
    } catch (Exception $ex) {
        // Assign the output string as to what happened
        return $result;
    }

    // Return the created HTML
    return $result;
}
    
function updateOldTools($db, $userRow, $taskID, $parentTaskNumber, &$goodPositions){
    // Set the duplicate values flag to false at first
    $duplicatePositions = false;

    // Determine if there are current tools to look at
    if (isset($_POST['currentToolsArray']) and $_POST['currentToolsArray']!=0){
        // Remove the last delimiter
        $currentToolsPSS = substr($_POST['currentToolsArray'], 0, -1);

        // Get the amount of current tools as a variable
        $currentToolNumsArray=explode('|', $currentToolsPSS);
        
        // Loop through and get all updatable tool elements
        foreach ($currentToolNumsArray as $loopToolToTaskLinkerID){
            // Get the value of the tool removal flag
            $removeTool=  (isset($_POST['removeTool'.$loopToolToTaskLinkerID])?1:0);
            
            // Determine if we are removing this note
            if ($removeTool){
                // Let's create a query to delete the tool
                $sql='DELETE FROM tooltotasklinker WHERE ToolToTaskLinkerID=' . $loopToolToTaskLinkerID . ';';
            }
            else {
                // Set the things we can
                $toolPosition = htmlspecialchars($_POST['toolPosition'.$loopToolToTaskLinkerID], ENT_QUOTES, 'UTF-8');
                $toolID = htmlspecialchars($_POST['toolChosenID'.$loopToolToTaskLinkerID], ENT_QUOTES, 'UTF-8');
                $toolRequiredExposedLength = htmlspecialchars($_POST['requiredExposedLength'.$loopToolToTaskLinkerID], ENT_QUOTES, 'UTF-8');
                $toolNote = $_POST['toolNote'.$loopToolToTaskLinkerID];
                $removeToolAfter = (isset($_POST['removeToolAfter'.$loopToolToTaskLinkerID])?1:0);
                $useNewTool = (isset($_POST['useNewTool'.$loopToolToTaskLinkerID])?1:0);
                
                // Determine if the position is a number and it is over zero
                if (is_numeric($toolPosition) && $toolPosition>0){
                    // Determine if it is in the array already
                    if (in_array($toolPosition, $goodPositions)){
                        // Set it to zero
                        $toolPosition=0;

                        // Set the flag to inform of duplicate values
                        $duplicatePositions = true;
                    }
                    else {
                        // Add this position to the array
                        array_push($goodPositions, $toolPosition);
                    }
                }
                else {
                    // Set it to zero
                    $toolPosition=0;
                }
                
                // Create the update query
                $sql='UPDATE tooltotasklinker SET ';
                $sql = $sql . ' ToolPosition=' . $toolPosition;
                if ($toolID!=null && is_numeric($toolID)) {$sql = $sql . ' ,ToolID=' . $toolID;}
                if ($toolRequiredExposedLength!=null && is_numeric($toolRequiredExposedLength)) {$sql = $sql . ' ,ExposedLength=' . $toolRequiredExposedLength;}
                $sql = $sql . ' ,Notes="' . $toolNote . '"';
                $sql = $sql . ' ,RemoveAfterUse=' . $removeToolAfter;
                $sql = $sql . ' ,UseNewTool=' . $useNewTool;
                $sql=$sql .' WHERE ToolToTaskLinkerID=' . $loopToolToTaskLinkerID . ';';
            }
            
            // Attempt to run the query and get the response
            if ($db->queryDB($sql, $userRow, "tools_presentation Form occurance 6.")){
            }
        }
    }
    
    // Return the value of duplicate positions
    return $duplicatePositions;
}

function addNewToolsToDB($db, $taskID, $userRow, $parentTaskNumber, &$goodPositions){
    // Set the duplicate values flag to false at first
    $duplicatePositions = false;

    // Determine if there are new tools
    if (isset($_POST['newToolNumbers']) && $_POST['newToolNumbers']!=0 &&
        $taskID != null && is_numeric($taskID)){
        // Get the amount of new tools as a variable
        $toolNumStrings=$_POST['newToolNumbers'];
        $toolNums=explode('|', $toolNumStrings);
        
        // Loop through and get all new note elements
        foreach ($toolNums as $loopNumber){
            // Set the things we can
            $toolPosition = htmlspecialchars($_POST['newToolPosition'.$loopNumber], ENT_QUOTES, 'UTF-8');
            $toolID = htmlspecialchars($_POST['newToolChosenID'.$loopNumber], ENT_QUOTES, 'UTF-8');
            $toolRequiredExposedLength = htmlspecialchars($_POST['newRequiredExposedLength'.$loopNumber], ENT_QUOTES, 'UTF-8');
            $toolNote = htmlspecialchars($_POST['newToolNote'.$loopNumber], ENT_QUOTES, 'UTF-8');
            $removeToolAfter = (isset($_POST['newRemoveToolAfter'.$loopNumber])?1:0);
            $useNewTool = (isset($_POST['newUseNewTool'.$loopNumber])?1:0);

            // Determine if the position is a number and it is over zero
            if (is_numeric($toolPosition) && $toolPosition>0){
                // Determine if it is in the array already
                if (in_array($toolPosition, $goodPositions)){
                    // Set it to zero
                    $toolPosition=0;

                    // Set the flag to inform of duplicate values
                    $duplicatePositions = true;
                }
                else {
                    // Add this position to the array
                    array_push($goodPositions, $toolPosition);
                }
            }
            else {
                // Set it to zero
                $toolPosition=0;
            }

            // Let's create the insert query off of what we have
            $sql='INSERT INTO tooltotasklinker (RemoveAfterUse, UseNewTool ';
            if ($taskID!=null) {$sql = $sql . ', TaskID';}
            if ($toolPosition!=null) {$sql = $sql . ', ToolPosition';}
            if ($toolID!=null) {$sql = $sql . ', ToolID';}
            if ($toolRequiredExposedLength!=null) {$sql = $sql . ', ExposedLength';}
            if ($toolNote!=null) {$sql = $sql . ', Notes';}
            $sql=$sql .') VALUES (' . $removeToolAfter . ', ' . $useNewTool;
            if ($taskID!=null) {$sql = $sql . ', ' . $taskID;}
            if ($toolPosition!=null) {$sql = $sql . ', ' . $toolPosition;}
            if ($toolID!=null) {$sql = $sql . ', ' . $toolID;}
            if ($toolRequiredExposedLength!=null) {$sql = $sql . ', ' . $toolRequiredExposedLength;}
            if ($toolNote!=null) {$sql = $sql . ', "' . $toolNote . '"';}
            $sql=$sql .');';
//echo '<script>alert("' . addslashes($sql) . '");</script>';

            // Attempt to run the query and get the response
            if ($db->queryDB($sql, $userRow, "tools_presentation Form occurance 7.")){
            }
        }
    }
    
    // Return the value of duplicate positions
    return $duplicatePositions;
}

function retrieveToolsDiv($db, $userRow, $inTaskID, &$validationHTML=null){
    // Get any current tools
    $results=retrieveCurrentTools($db, $userRow, $inTaskID, $validationHTML);
    
    // Determine if we added some tools
    $toolColorHtml = '';
    if ($results != '') {
        // Change the color of the Tools Title font
        $toolColorHtml = 'style="color:LimeGreen;"';
    }

    // Init all of the settings to the appropriate values
    $toolDiv = '   
                    <br><br>
                    <label style="font-size: 20px;"><strong>New Tools: </strong></label>
                    <div id="newTools" style="">
                    </div>
                    <p align="right" style="border-top-style:dashed; border-width: 1px; font-weight: bold;font-size: 12px;">
                        <input type="hidden" id="newToolNumbers" name="newToolNumbers" value="0"></input>
                        <button type="button" title="Select tools from the machine that it is currently selected. Quickens standard tool selection." onclick="javascript:chooseTool(false); if (typeof _isDirty !== \'undefined\' && _isDirty !== null) {_isDirty=true;};"/>Choose Setup Tools</button>
                        <button type="button" onClick="chooseTool(true); if (typeof _isDirty !== \'undefined\' && _isDirty !== null) {_isDirty=true;};" align="right">Add New Tool</button>
                    </p>' .
                    $results .
                    '
                ';

// toolSlotIDToModifyRow=' . $toolToTaskLinkerID . '; updatingtool=true; 


    
    // Return the result
    return $toolDiv;
}
?>   
