<?php    
function checkThenGetChildNotesDiv($db, $userRow, $inAssociatedCategoryID, $inCategoryType, $inNameLabel="", &$validationHTML=""){
    // Init all of the settings to the appropriate values
    $noteDiv = '';

    // Determine if the user is of the main company and appropriate level
    if ($userRow["CompanyID"]==1 &&
            ($userRow["UserLevel"]=="SU" ||
             $userRow["UserLevel"]=="EXECUTIVE" ||
             $userRow["UserLevel"]=="MANAGEMENT" ||
             $userRow["UserLevel"]=="MID-MANAGEMENT" ||
             $userRow["UserLevel"]=="TYPICAL")
        )
        {
            // get the div
            $noteDiv = retrieveChildNotesDiv($db, $userRow, $inAssociatedCategoryID, $inCategoryType, $inNameLabel, $validationHTML);
        }

    // Return the result
    return $noteDiv;
}

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

    try {
        // Init necessary variables
        $taskID=$inTaskID;

        // Determine if I am supposed to check for current blanks or not
        if ($taskID!=null && is_numeric($taskID)){
            // Create the query to get the the setups and the user that created the blanks
            $sql = 'SELECT ms.*, t.UserID, t.StatusID, s.ProcessOrder, u.LastName AS VerifiedByLastName, u.FirstName AS VerifiedByFirstName ' . 
                   'FROM machiningsetups ms ' . 
                   'LEFT JOIN users u  ON ms.LastVerifiedByID = u.UserID ' . 
                   'LEFT JOIN tasks t  ON ms.TaskID = t.TaskID ' . 
                   'LEFT JOIN status s  ON t.StatusID = s.StatusID ' . 
                   'WHERE ms.TaskID=' . $taskID . ' ' .
                   'ORDER BY ms.SetupOrder ';

            // Attempt to get all of the setups for this category type and ID
            $rows = $db->queryDB($sql, $userRow, "setup_presentation Form occurance 1");

            // Determine if there were rows for the task(s)
            if ($rows != null && 
                mysqli_num_rows($rows)>0){
                // Init some variables
                $setupsIDArray=null;

                // Reset the validation HTML
                $validationHTML='';

                // Loop through the returned results
                $amount=0;
                while ($row=mysqli_fetch_array($rows)){
                    // Increment the amount
                    $amount++;
                    
                    // Reset the validation for the notes
                    $noteChildValidationHTML='';

                    // Set the things we can
                    $machiningSetupID = $row["MachiningSetupID"];
                    $lastVerifiedByID = $row["LastVerifiedByID"];
                    $lastVerifiedByFirstName = $row["VerifiedByFirstName"];
                    $lastVerifiedByLastName = $row["VerifiedByLastName"];
                    $setupOrder = $row["SetupOrder"];
                    $setupByID = $row["SetupByID"];
                    $setupCheckedByID = $row["SetupCheckedByID"];
                    $side = $row["Side"];
                    $coordinateSystem = $row["CoordinateSystem"];
                    $hasM00 = $row["hasM00"];
                    $holdBy = $row["HoldBy"];
                    $orientation = $row["Orientation"];
                    $xZeroLocation = $row["xZeroLocation"];
                    $yZeroLocation = $row["yZeroLocation"];
                    $zZeroLocation = $row["zZeroLocation"];
                    $gCodeFileName = $row["GCodeFileName"];
                    $gCodeFileLinesOfCode = $row["GCodeFileLinesOfCode"];
                    $gCodeRuntime = $row["GCodeRuntime"];
                    $gCodeFileType = $row["GCodeFileType"];
                    $gCodeFileSize = $row["GCodeFileSize"];
                    $gCode = $row["GCode"];
                    $toolDetails = $row["ToolDetails"];
                    $moddedToolDetails = $row["ModdedToolDetails"];
                    $toolStart = $row["ToolStart"];
                    
                    // Determine if we have values for the M00 flag
                    $hasM00HTML='';
                    if ($hasM00){
                        // Set it to what we got in
                        $hasM00HTML = 'checked';
                    }
                    
                    // Determine if there is a tool start
                    $displayToolStart='';
                    if ($toolStart==null || $toolStart==''){
                        // set it to not be displayed
                        $displayToolStart=' display:none;';
                    }
                    
                    // Determine if there is a GCode
                    $displayGCode=' display:none;';
                    $displayGCodeLabel='<label id="removeGCodeLabel' . $machiningSetupID . '" style="display:none;">Replace GCode</label>';
                    $gcodeCellContents='';
                    if ($gCode!=null || $gCode!=''){
                        // Add the label
                        $displayGCodeLabel='<label id="removeGCodeLabel' . $machiningSetupID . '" style="display:block;">Replace GCode</label>';
                        
                        // set it to not be displayed
                        $displayGCode=' display:block;';
                        
                        // CGode Cell
                        $gcodeCellContents = '
                                Type=' . $gCodeFileType . '  
                                <br> 
                                Size=' . $gCodeFileSize . ' KB
                                <br>
                                <a href="php_only_scripts/show_blob.php?id=' . $machiningSetupID . '&tbl=machiningsetups&idf=MachiningSetupID&bf=GCode&tyf=GCodeFileType&nmf=GCodeFileName&szf=GCodeFileSize" onclick="return confirm(\'Downloading G-Code this way is not normally meant to work directly in the CNC machines.  Clicking the sync button on the machines page is recommended instead if the code is being downloaded to be used in the CNC machines for proper tool syncing.\n\nAre you sure you want to download this way?\')">Download Original GCode</a>
                            ';
                        
                    }
                    
                    // Get the tool details amount of rows
                    $toolDetailsRowCount = substr_count($toolDetails,"\n")+1;
                    
                    // Start adding the setups that are in the database
                    $result = $result . 
                                '   
                                    <table id=setupDiv' . $machiningSetupID . ' name=setupDiv' . $machiningSetupID . ' style = "margin-top:10px; border-top-style:dashed; border-width: 1px; text-align: center;">
                                        <tr>
                                            <td colspan=6 align="right">
                                                <label id="removeSetupLabel' . $machiningSetupID . '" style="color:LimeGreen;">Remove Setup</label>
                                                <input type="checkbox" class="notinput" id="removeSetup' . $machiningSetupID . '" name="removeSetup' . $machiningSetupID . '" title="This being checked on update will remove the setup on update." onchange="javascript:savedSetupMarkedForRemoval(' . $machiningSetupID . ', sessionID);" value="' . $machiningSetupID . '"></input>
                                                <br>
                                            </td>
                                        </tr>
                                        <tr style="width: 100%; margin: 5px; vertical-align: middle;">
                                            <td style="text-align: center;" colspan=6>
                                                <label style="font-weight:bold;">General</label>
                                            </td>
                                        </tr>
                                        <tr style="width: 100%; margin: 5px; vertical-align: middle;">
                                            <td style="text-align: right;" colspan=1>
                                                <label>Order:</label>
                                            </td>
                                            <td style="text-align: left;" colspan=1>
                                                <input name="order' . $machiningSetupID . '" id="order' . $machiningSetupID . '" type="text" maxlength="150" class="ASetupOrder" value="' . $setupOrder . '" style="width:90px;"/>
                                            </td>
                                            <td style="text-align: right;" colspan=1>
                                                <label>Setup By:</label>
                                            </td>
                                            <td style="text-align: left;" colspan=1>
                                                <input name="oldSetupBy' . $machiningSetupID .'" id="oldSetupBy' . $machiningSetupID .'" type="hidden" class="SetupByID" value="' . $setupByID . '">
                                                <div id="setupByDiv' . $machiningSetupID .'">
                                                </div>
                                            </td>
                                            <td style="text-align: right;" colspan=1>
                                                <label>Checked By:</label>
                                            </td>
                                            <td style="text-align: left;" colspan=1>
                                                <input name="oldCheckedBy' . $machiningSetupID .'" id="oldCheckedBy' . $machiningSetupID .'" type="hidden" class="SetupCheckedByID" value="' . $setupCheckedByID . '">
                                                <div id="checkedByDiv' . $machiningSetupID .'">
                                                </div>
                                            </td>
                                        </tr>
                                        <tr style="width: 100%; margin: 5px; vertical-align: middle;">
                                            <td style="text-align: right;" colspan=1>
                                                <label>Side:</label>
                                            </td>
                                            <td style="text-align: left;" colspan=1>
                                                <input name="side' . $machiningSetupID . '" id="side' . $machiningSetupID . '" type="text" maxlength="11" value="' . $side . '" style="width:90px;"/>
                                            </td>
                                            <td style="text-align: right;" colspan=1>
                                                <label>Coordinate ID:</label>
                                            </td>
                                            <td style="text-align: left;" colspan=1>
                                                <input name="coordinateID' . $machiningSetupID . '" id="coordinateID' . $machiningSetupID . '" type="text" maxlength="40" value="' . $coordinateSystem . '" style="width:90px;"/>
                                            </td>
                                            <td style="text-align: right;" colspan=1>
                                                <label>M00:</label>
                                            </td>
                                            <td style="text-align: left;" colspan=1>
                                                <input name="m00' . $machiningSetupID . '" id="m00' . $machiningSetupID . '" type="checkbox" ' . $hasM00HTML . '>
                                            </td>
                                        </tr>
                                        <tr style="width: 100%; margin: 5px; vertical-align: middle;">
                                            <td style="text-align: right;" colspan=1>
                                                <label>Hold By:</label>
                                            </td>
                                            <td style="text-align: left;" colspan=5>
                                                <textarea name="holdBy' . $machiningSetupID . '" id="holdBy' . $machiningSetupID . '" maxlength="150" style="width: 100%; overflow: auto; resize: vertical;">' .
                                                $holdBy .
                                                '</textarea>
                                            </td>
                                        </tr>
                                        <tr style="width: 100%; margin: 5px; vertical-align: middle;">
                                            <td style="text-align: right;" colspan=1>
                                                <label>Orientation:</label>
                                            </td>
                                            <td style="text-align: left;" colspan=5>
                                                <textarea name="orientation' . $machiningSetupID . '" id="orientation' . $machiningSetupID . '" maxlength="150" style="width: 100%; overflow: auto; resize: vertical;">' .
                                                $orientation .
                                                '</textarea>
                                            </td>
                                        </tr>
                                        <tr name="toolStartRow' . $machiningSetupID . '" id="toolStartRow' . $machiningSetupID . '" style="width: 100%; margin: 5px; vertical-align: middle;">
                                            <td style="text-align: right;" colspan=1>
                                                <label>Tool Start:</label>
                                            </td>
                                            <td style="text-align: left;" colspan=3>
                                                <input name="isRemoveTool' . $machiningSetupID .'" id="isRemoveTool' . $machiningSetupID .'" type="hidden" value="0">
                                                <input name="toolStartAttachment' . $machiningSetupID . '" id="toolStartAttachment' . $machiningSetupID . '" type="file" accept="image/gif, image/jpeg, image/png, image/tiff, image/bmp" onChange="onToolStartFileChange(' . $machiningSetupID . ', false);" style="width:90px;">
                                                <br>
                                                <button name="removeImage' . $machiningSetupID . '" id="removeImage' . $machiningSetupID . '" type="button" onClick="removeImage(' . $machiningSetupID . ', false)" style="' . $displayToolStart . '">Remove</button>
                                            </td>
                                            <td style="text-align: center;" colspan=2>
                                                <img name="toolStartImage' . $machiningSetupID . '" id="toolStartImage' . $machiningSetupID . '" src="php_only_scripts/show_blob.php?id=' . $machiningSetupID . '&tbl=machiningsetups&idf=MachiningSetupID&bf=ToolStart" onClick="modifySize(this)" style="width:150px;' . $displayToolStart . '"/>
                                            </td>
                                        </tr>
                                        <tr style="width: 100%; margin: 5px; vertical-align: middle;">
                                            <td style="text-align: center;" colspan=6>
                                                <label style="font-weight:bold;">Zero Locations</label>
                                            </td>
                                        </tr>
                                        <tr style="width: 100%; margin: 5px; vertical-align: middle;">
                                            <td style="text-align: right;" colspan=1>
                                                <label>X Zero:</label>
                                            </td>
                                            <td style="text-align: left;" colspan=1>
                                                <input name="xLocation' . $machiningSetupID . '" id="xLocation' . $machiningSetupID . '" type="text" maxlength="40" value="' . $xZeroLocation . '" style="width:130px;"/>
                                            </td>
                                            <td style="text-align: right;" colspan=1>
                                                <label>Y Zero:</label>
                                            </td>
                                            <td style="text-align: left;" colspan=1>
                                                <input name="yLocation' . $machiningSetupID . '" id="yLocation' . $machiningSetupID . '" type="text" maxlength="40" value="' . $yZeroLocation . '" style="width:130px;"/>
                                            </td>
                                            <td style="text-align: right;" colspan=1>
                                                <label>Z Zero:</label>
                                            </td>
                                            <td style="text-align: left;" colspan=1>
                                                <input name="zLocation' . $machiningSetupID . '" id="zLocation' . $machiningSetupID . '" type="text" maxlength="40" value="' . $zZeroLocation . '" style="width:130px;"/>
                                            </td>
                                        </tr>
                                        <tr style="width: 100%; margin: 5px; vertical-align: middle;">
                                            <td style="text-align: center;" colspan=6>
                                                <label style="font-weight:bold;">Program Info</label>
                                            </td>
                                        </tr>
                                        <tr name="gCodeRow' . $machiningSetupID . '" id="gCodeRow' . $machiningSetupID . '" style="width: 100%; margin: 5px; vertical-align: middle;">
                                            <td style="text-align: right;" colspan=1>
                                                <label>G-Code File:</label>
                                            </td>
                                            <td style="text-align: left;" colspan=3>
                                                ' . $displayGCodeLabel . '
                                                <input name="gCodeAttachment' . $machiningSetupID . '" id="gCodeAttachment' . $machiningSetupID . '" type="file" accept=".nc,.NC,.tap,.TAP" onChange="onNewGCodeSelected(' . $machiningSetupID . ', false, sessionID);" style="width:90px;">
                                                <br>
                                                <button name="removeGCode' . $machiningSetupID . '" id="removeGCode' . $machiningSetupID . '" type="button" onClick="removeGCode(' . $machiningSetupID . ', false)" style="' . $displayGCode . '">Remove</button>
                                            </td>
                                            <td id="gCodeDescCell' . $machiningSetupID . '" name="gCodeDescCell' . $machiningSetupID . '" style="text-align: left;" colspan=2>
                                            ' .
                                            $gcodeCellContents
                                            . '
                                            </td>
                                        </tr>
                                        <tr style="width: 100%; margin: 5px; vertical-align: middle;">
                                            <td style="text-align: right;" colspan=1>
                                                <label>Name:</label>
                                                <input name="gCodeFileType' . $machiningSetupID .'" id="gCodeFileType' . $machiningSetupID .'" type="hidden" value="' . $gCodeFileType . '">
                                                <input name="gCodeFileSize' . $machiningSetupID .'" id="gCodeFileSize' . $machiningSetupID .'" type="hidden" value="' . $gCodeFileSize . '">
                                            </td>
                                            <td style="text-align: left;" colspan=1>
                                                <input name="programName' . $machiningSetupID . '" id="programName' . $machiningSetupID . '" class="disableaslabel" type="text" value="' . $gCodeFileName . '"/>
                                            </td>
                                            <td style="text-align: right;" colspan=1>
                                                <label>Lines:</label>
                                            </td>
                                            <td style="text-align: left;" colspan=1>
                                                <input name="amountProgramLines' . $machiningSetupID . '" id="amountProgramLines' . $machiningSetupID . '" class="disableaslabel" type="text" maxlength="11" value="' . $gCodeFileLinesOfCode . '"/>
                                            </td>
                                            <td style="text-align: right;" colspan=1>
                                                <label>Run Time:</label>
                                            </td>
                                            <td style="text-align: left;" colspan=1>
                                                <input name="programRunTime' . $machiningSetupID . '" id="programRunTime' . $machiningSetupID . '" class="disableaslabel" type="text" maxlength="15" value="' . $gCodeRuntime . '"/>
                                            </td>
                                        </tr>
                                        <tr style="width: 100%; margin: 5px; vertical-align: middle;">
                                            <td style="text-align: right;" colspan=1>
                                                <label>Verified By:</label>
                                                <input name="lastVerifiedByID' . $lastVerifiedByID .'" id="lastVerifiedByID' . $lastVerifiedByID .'" type="hidden" value="' . $gCodeFileType . '">
                                            </td>
                                            <td style="text-align: left;" colspan=5>
                                                <label style="color:green;">' . $lastVerifiedByFirstName . '&nbsp;&nbsp;' . $lastVerifiedByLastName . '</label>
                                            </td>
                                        </tr>
                                        <tr style="width: 100%; margin: 5px; vertical-align: middle;">
                                            <td style="text-align: center;" colspan=3>
                                                <label style="font-weight:bold;">Original Tool Details</label>
                                            </td>
                                            <td style="text-align: center;" colspan=3>
                                                <label style="font-weight:bold;">Modified Tool Details</label>
                                            </td>
                                        </tr>
                                        <tr style="width: 100%; margin: 5px; vertical-align: middle;">
                                            <td style="text-align: left;" colspan=3>
                                                <textarea name="toolDetails' . $machiningSetupID . '" id="toolDetails' . $machiningSetupID . '" maxlength="1000" class="setupToolDetailsView" rows=' . $toolDetailsRowCount . ' readonly style="height:auto; width: 100%; overflow: auto; resize: vertical; text-align: center;">' .
                                                $toolDetails .
                                                '</textarea>
                                            </td>
                                            <td style="text-align: left;" colspan=3>
                                                <textarea name="moddedToolDetails' . $machiningSetupID . '" id="moddedToolDetails' . $machiningSetupID . '" maxlength="1000" class="setupToolDetails setupToolDetailsView" rows=' . $toolDetailsRowCount . ' readonly style="height:auto; width: 90%; overflow: auto; resize: vertical; text-align: center;">' .
                                                $moddedToolDetails .
                                                '</textarea>
                                            </td>
                                        </tr>
                                        <tr style="width: 100%; margin: 5px; vertical-align: middle;">
                                            <td style="text-align: center;" colspan=6>
                                                ' 
                                                .
                                                checkThenGetChildNotesDiv($db, $userRow, $machiningSetupID, 'SETUP_M00', 'M00 Instruction', $noteChildValidationHTML)
                                                .
                                                '
                                            </td>
                                        </tr>
                                        <tr style="width: 100%; margin: 5px; vertical-align: middle;">
                                            <td style="text-align: center;" colspan=6>
                                                ' 
                                                .
                                                checkThenGetChildNotesDiv($db, $userRow, $machiningSetupID, 'SETUP_NOTE', 'Setup Note', $noteChildValidationHTML)
                                                .
                                                '
                                            </td>
                                        </tr>
                                        <tr style="width: 100%; margin: 5px; vertical-align: middle;">
                                            <td style="text-align: center;" colspan=6>
                                                ' 
                                                .
                                                checkThenGetChildNotesDiv($db, $userRow, $machiningSetupID, 'OPERATOR_FEEDBACK_NOTE', 'Operator Feedback Note', $noteChildValidationHTML)
                                                .
                                                '
                                            </td>
                                        </tr>
                                    </table>
                                ';
                    
                    // Add something to the array list
                    $setupsIDArray = $setupsIDArray . $machiningSetupID . '|';
                    
                    // Add the validators for these
                    $validationHTML = $validationHTML . '
                                    frmvalidator.addValidation("order' . $machiningSetupID . '",
                                                               "req",
                                                               "Please enter an order of operations for all setups.");
                                    frmvalidator.addValidation("order' . $machiningSetupID . '",
                                                               "num",
                                                               "Please enter an order of operations for all setups as a number.");
                                    frmvalidator.addValidation("order' . $machiningSetupID . '",
                                                               "greaterthan=-.0000000001",
                                                               "The order of operations for all setups should be greater than 0.");
                                    frmvalidator.addValidation("side' . $machiningSetupID . '",
                                                               "req",
                                                               "Please enter which side for all setups.");
                                    frmvalidator.addValidation("side' . $machiningSetupID . '",
                                                               "num",
                                                               "Please enter which side for all setups as a number.");
                                    frmvalidator.addValidation("side' . $machiningSetupID . '",
                                                               "greaterthan=-.0000000001",
                                                               "The which side for all setups should be greater than 0.");
                                    frmvalidator.addValidation("coordinateID' . $machiningSetupID . '",
                                                               "req",
                                                               "Please enter a coordinate system for all setups.");
                                    frmvalidator.addValidation("xLocation' . $machiningSetupID . '",
                                                               "req",
                                                               "Please enter the X zero for all setups.");
                                    frmvalidator.addValidation("yLocation' . $machiningSetupID . '",
                                                               "req",
                                                               "Please enter the Y zero for all setups.");
                                    frmvalidator.addValidation("zLocation' . $machiningSetupID . '",
                                                               "req",
                                                               "Please enter the Z zero for all setups.");
                                    frmvalidator.addValidation("toolDetails' . $machiningSetupID . '",
                                                               "req",
                                                               "Please enter tool details all setups.");
                                    ';
                }

                // Add the hidden field to the form
                $result = 
                        '<label  style="font-size: 20px;"><strong>Current Setups: </strong></label>
                         <div id="currentSetupsDiv" style="">
                             <input type="checkbox" id="syncSetups" name="syncSetups" title="This will attempt to sync GCodes on update."></input>
                             <strong><label for="expedite">Sync Setups with GCode</label></strong>
                             <input type="hidden" name="currentSetupsArray" id="currentSetupsArray" value="' . $setupsIDArray . '"></input>
                             <input type="hidden" name="deleteCurrentSetups" id="deleteCurrentSetups" value=""></input>
                             ' .
                             $result .
                        '</div>';
            }
        }
    } catch (Exception $ex) {
        // Assign the output string as to what happened
        return $result;
    }

    // Return the created HTML
    return $result;
}

function syncSetupGCodeWithTask($db, $userRow, $oldSetupInfoAssocRow, $setupID, $setupOrder, $toolDetails){
    // Create a return that will only indicates warnings/errors
    $returnString='';
    
    // Init Primary variables
    $tid = -1;
    $gcode = null;
    $gcodeFileSize = 0;
    
    // Determine if the database object is there
    if ($oldSetupInfoAssocRow!=null){
        // Set main variables from the database row
        $tid = $oldSetupInfoAssocRow["TaskID"];
        $gcode = $oldSetupInfoAssocRow["GCode"];
        $gcodeFileSize = $oldSetupInfoAssocRow["GCodeFileSize"];
    }
    
    // Create string for the different types of problems that could happen
    $toolInDatabaseMissingString = '';
    $toolInToolToTaskTableMissingString = '';
    $setupDetailsMissingString = '';
    
    try {
        // Determine if there is any GCode first
        if ($gcode != null && strlen($gcode)>0 && $gcodeFileSize>0){
            // Determine if the are tool details missing for this setup
            if ($toolDetails==null || $toolDetails==''){
                // Create a string to let them know that we will try to fix this problem
                $setupDetailsMissingString = 'There are no tool details for setup number ' . 
                        $setupOrder . '. Attempting to fix this issue. Please check the ' . 
                        'tool details and tools after fix. ';
            }

            // Determine if the TID is one greater than 0
            if ($tid!==null && $tid>0){
                // Split the gcode on end line characters
                $lines = explode("\r\n", $gcode);
                
                // Create a string to hold the Original and Modified Tool Details.
                $originalToolDetails = '';
                
                // Create a variable to determine if there are tools that are in the GCode, but not the tooltotasklinker table. Assume they match.
                $doToolsMatch = true;

                // Loop through the file looking for end line characters
                for ($i = 0; $i<count($lines); $i++) {
                    // Get the current line of the file
                    $currentLine=$lines[$i];

                    // Check to see if this is a tool line
                    if (strpos($currentLine,"(/-/)")!==FALSE) {
                        // Remove the end and beginning
                        $currentLine = str_replace("(/-/)(","", trim($currentLine, "'"));
                        $currentLine = str_replace(")(/-/)", "", trim($currentLine, "'"));

                        // Add to the original tool details for this setup
                        $originalToolDetails .= $currentLine . '\r\n';
                        
                        // Split the string on the tool name and number
                        $toolInfo = explode("-", $currentLine, 2);

                        // Ensure we get two values
                        if (count($toolInfo)!==2){
                            // Let them know there is a tool line in the GCode that is not standard
                            $returnString = 'There is a tool line in the GCode that is not standard and cannot ' . 
                                            'be parsed for setup number ' . $setupOrder . '. Fix this before ' . 
                                            'continuing.\r\n \r\n Line: ' . $currentLine . ' GCode Sync Aborted.';
                            
                            // Break out of this loop
                            break;
                        }

                        // Create a query to get the tool as it stands in the TMS (New Position).
                        $sql = 'SELECT ttl.ToolPosition, t.Name ' .
                               'FROM tooltotasklinker ttl ' .
                               'LEFT JOIN tools t on ttl.ToolID = t.ToolID ' .
                               'WHERE ttl.TaskID = ' . $tid . ' ' .
                               'AND t.Name = "' . trim($toolInfo[1]) . '"; ';

                        // Get the new tool position
                        $newToolInfo = $db->queryDB($sql, $userRow, "setup_presentation occurance 2");

                        // Determine if the query did not come back with a row
                        if (mysqli_num_rows($newToolInfo)<1){
                            // Start a string stating that the tool was not in tht tool to task linker table
                            $toolInToolToTaskTableMissingString .= 'Tool ' . trim($toolInfo[1]) . ' is missing from ' .
                                    'setup ' . $setupOrder . ' tool table. This tool was ';
                            
                            // Get the readable row
                            $newToolInfoAssocRow = $newToolInfo->fetch_assoc();

                            // Set that they do not match
                            $doToolsMatch = false;
                            
                            // Have to check that the tool is in the database
                            $sql = 'SELECT ToolID FROM tools WHERE Name="' . $toolInfo[1] . '";';
                            
                            // Get the new tool position
                            $toolIDInDatabase = $db->queryDB($sql, $userRow, "setup_presentation occurance 3");
                            
                            // Determine if the query did not come back with ONE row
                            if (mysqli_num_rows($toolIDInDatabase)==1){
                                // Get the readable row
                                $toolIDInDatabaseAssocRow = $toolIDInDatabase->fetch_assoc();

                                // Create a query to add the tool to the table with a negative tool number
                                $sql = 'INSERT INTO tooltotasklinker (TaskID, ToolID, Notes) ' .
                                       'VALUES (' . $tid . ', ' . $toolIDInDatabaseAssocRow["ToolID"];
                                
                                // Attempt to add the row 
                                if ($db->queryDB($sql, $userRow, "setup_presentation occurance 4")!==FALSE){
                                    // Add information that this tool was added
                                    $toolInToolToTaskTableMissingString .= 'added.\r\n';
                                }
                                else {
                                    // Add information that this tool was NOT added
                                    $toolInToolToTaskTableMissingString .= 'NOT added.\r\n';
                                }
                            }
                            else {
                                // Add information that this tool was NOT added
                                $toolInToolToTaskTableMissingString .= 'NOT added.\r\n';
                                
                                // Create information about the tool not being in the database
                                $toolInDatabaseMissingString .= trim($toolInfo[1]) . '\r\n';
                            }
                        }
                        else if (mysqli_num_rows($newToolInfo)>1){
                            // Return information about having two tools associated with this task.
                            $returnString = 'There are two or more of the same tool associated with this task. ' .
                                            'The tool in GCode cannot be matched to a single one. \r\n\r\n The ' . 
                                            'tool is (' . $newToolInfoAssocRow["Name"] . '). GCode Sync Aborted.';
                            
                            // Break out of the loop
                            break;
                        }
                    }
                    // Determine if we are at the start of the real GCode yet
                    else if (strpos($lines[$i],"G00 G17 G20 G40 G80 G90 G94")!==FALSE) {
                        // If we are here, then we are done getting tools from the GCode. Break out of the loop.
                        break;
                    }
                }
                
                // Determine if the tool details missing for this setup and if we made new details
                if ($toolDetails==null || $toolDetails=='' && $originalToolDetails!=''){
                    // Create a query to update the database with the tool details added 
                    $sql = 'UPDATE machiningsetups SET ToolDetails="' . $originalToolDetails . '" ' .
                           'WHERE MachiningSetupID=' . $setupID . ';';
                    
                    // Attempt to update the row 
                    if ($db->queryDB($sql, $userRow, "setup_presentation occurance 5")!==FALSE){
                        // Add information that the details were updated
                        $setupDetailsMissingString .= ' Tool Details update was successful.';
                    }
                    else {
                        // Add information that the details were NOT updated
                        $setupDetailsMissingString .= ' Tool Details update was NOT successful.';
                    }
                }
                else if ($toolDetails==null || $toolDetails=='' && $originalToolDetails==''){
                    // Add information that the details were NOT updated
                    $setupDetailsMissingString .= ' No Tool Details found in GCode. Update not performed.';
                }

                
                // Determine if there were tools in the GCode that are not in the database
                if ($toolInDatabaseMissingString != ''){
                    // Remove the last two characters
                    trim(substr($toolInDatabaseMissingString, 0, -2));

                    // Create a string to be returned to the user
                    $toolInDatabaseMissingString = 'There are tools in the GCode that are ' .
                            'not in the database for setup ' . $setupOrder . '. Tools are:\r\n\r\n' .
                            $toolInDatabaseMissingString . '\r\nCheck the GCode and/or Tool DB.';
                }
                
                // Determine if there were ANY warnings/errors
                if ($toolInToolToTaskTableMissingString != ''){
                    // Create the return string off of all strings possible
                    $toolInToolToTaskTableMissingString = 'There were tools missing from task setup number ' . 
                            $setupOrder . ' in the tool tab that the system attempted to fix: \r\n\r\n' . 
                            $toolInToolToTaskTableMissingString . '\r\nPlease check the setup tool table.';
                }
                
                // Determine if there were ANY warnings/errors
                if ($toolInToolToTaskTableMissingString != '' ||
                    $setupDetailsMissingString != ''){
                    // Create the return string off of all strings possible
                    $returnString = $toolInToolToTaskTableMissingString . 
                                    '\r\n---------------------------------\r\n' .
                                    $toolInToolToTaskTableMissingString .
                                    '\r\n---------------------------------\r\n' .
                                    $setupDetailsMissingString;
                }
            }
            else {
                // let them know there is not a TID for this setup
                $returnString = 'There is no TID associated with the setup number ' . $setupOrder . 
                                '. Please check the task or let system admin know to fix. ' . 
                                'GCode Sync Aborted.';
            }
        }
        else {
            // return the fact that there is no GCode for this setup
            $returnString = 'There is no GCode for setup number ' . $setupOrder . ' ' .
                            '\r\n \r\nCheck the setup and ensure that there is a GCode ' . 
                            'associated with the setup. GCode Sync Aborted.';
        }
    } catch (Exception $exc) {
        // Create the error string to return back to the caller
        $returnString = 'There is an uncaught error while modifying database for the tools in setup ' . 
                        $setupOrder . '. The exception is: ' . $exc->getMessage() . '. GCode Sync Aborted.';
    }
    finally {
        // Return what could be an error string
        return $returnString;
    }
}

function updateOldSetups($db, $userRow, $syncOldCode, $machineID=-1){
    // Create a variable to allow us to reset this task back to start
    $returnStatusBack=false;
    
    try {
        // Determine if there are current setups to look at
        if (isset($_POST['currentSetupsArray']) and $_POST['currentSetupsArray']!=0){
            // Remove the last delimiter
            $numbersToRemoveAsString = substr($_POST['currentSetupsArray'], 0, -1);

            // Get the amount of current setups as a variable
            $setupsNums=explode('|', $numbersToRemoveAsString);

            // Loop through and get all new setup elements
            foreach ($setupsNums as $setupNumber){
                // Get the value of the not removal flag
                $removeSetup = (isset($_POST['removeSetup'.$setupNumber])?1:0);

                // Determine if we are removing this note
                if ($removeSetup){
                    // Let's create a query to delete the note
                    $sql='DELETE FROM machiningsetups WHERE MachiningSetupID=' . $setupNumber . ';';
                }
                else {
                    // Get the posted items that I am worried about
                    $order=htmlspecialchars($_POST['order'.$setupNumber], ENT_QUOTES, 'UTF-8');
                    $setupByID=htmlspecialchars($_POST['setupBy'.$setupNumber], ENT_QUOTES, 'UTF-8');
                    $setupCheckedByID=htmlspecialchars($_POST['checkedBy'.$setupNumber], ENT_QUOTES, 'UTF-8');
                    $side=htmlspecialchars($_POST['side'.$setupNumber], ENT_QUOTES, 'UTF-8');
                    $coordinateID=htmlspecialchars($_POST['coordinateID'.$setupNumber], ENT_QUOTES, 'UTF-8');
                    $m00 = (isset($_POST['m00'.$setupNumber])?1:0);
                    $holdBy=htmlspecialchars($_POST['holdBy'.$setupNumber], ENT_QUOTES, 'UTF-8');
                    $orientation=htmlspecialchars($_POST['orientation'.$setupNumber], ENT_QUOTES, 'UTF-8');
                    $xLocation=htmlspecialchars($_POST['xLocation'.$setupNumber], ENT_QUOTES, 'UTF-8');
                    $yLocation=htmlspecialchars($_POST['yLocation'.$setupNumber], ENT_QUOTES, 'UTF-8');
                    $zLocation=htmlspecialchars($_POST['zLocation'.$setupNumber], ENT_QUOTES, 'UTF-8');
                    $toolDetails=htmlspecialchars($_POST['toolDetails'.$setupNumber], ENT_QUOTES, 'UTF-8');
                    $moddedToolDetails=htmlspecialchars($_POST['moddedToolDetails'.$setupNumber], ENT_QUOTES, 'UTF-8');

                    // Set everything to values that would be appropriate of NO file
                    $programName="";
                    $amountProgramLines=0;
                    $programRunTime="";
                    $gCodeAttachmentFileType=""; 
                    $gCodeAttachmentFileSize=0;
                    $gCodeContent=null;

                    // Set a flag to determine if the GCode is the same
                    $gCodeIsSame=false;
                    // Determine if there is a filename. Future or past.
                    if (htmlspecialchars($_POST['programName'.$setupNumber], ENT_QUOTES, 'UTF-8')!=""){
                        // determine if the gcode has been uploaded
                        $hasGCodeBeenUploaded = is_uploaded_file($_FILES['gCodeAttachment'.$setupNumber]['tmp_name']);
                        if($hasGCodeBeenUploaded) {
                            // Get the properties of the file to upload
                            $fname    = $db->getDBConnection()->real_escape_string($_FILES['gCodeAttachment'.$setupNumber]['name']); 
                            $tmpName  = $db->getDBConnection()->real_escape_string($_FILES['gCodeAttachment'.$setupNumber]['tmp_name']);

                            // Determine if the file size is such that we can accept it.
                            if ($gCodeAttachmentFileSize < 20000000){
                                // get relavent values from this new file
                                $programName = $fname;
                                $amountProgramLines=htmlspecialchars($_POST['amountProgramLines'.$setupNumber], ENT_QUOTES, 'UTF-8');
                                $programRunTime=htmlspecialchars($_POST['programRunTime'.$setupNumber], ENT_QUOTES, 'UTF-8');
                                $gCodeAttachmentFileType = $db->getDBConnection()->real_escape_string($_FILES['gCodeAttachment'.$setupNumber]['type']);
                                $gCodeAttachmentFileSize = intval($_FILES['gCodeAttachment'.$setupNumber]['size']);
                                $gCodeContent = $db->getDBConnection()->real_escape_string(file_get_contents($tmpName));
                            }
                            else {
                                // Let the user know the file was NOT uploaded
                                echo("The GCode file ('" . $fname . "') will not be uploaded, because it is too large for this site. File must be under 20MB.");
                            }
                        }
                        else {
                            // Determine if we are doing this sync
                            if ($syncOldCode==true){
                                // Determine if this is on a valid machine
                                $machineType='';
                                if ($machineID!=null && $machineID != -1){
                                    // Create a query to determine what type of machine this is
                                    $sql = 'SELECT Type FROM machines WHERE MachineID = ' . $machineID . ';';
                                    
                                    // Get the machine type
                                    $machineTypeQuery = $db->queryDB($sql, $userRow, "setup_presentation occurance 6");

                                    // Determine if the query came back with a row
                                    if (mysqli_num_rows($machineTypeQuery)==1){
                                        // Get the readable row
                                        $machineTypeAssocRow = $machineTypeQuery->fetch_assoc();
                                        
                                        // Get what type of machine this is
                                        $machineType=$machineTypeAssocRow["Type"];
                                    }
                                }
                                
                                // Determine if this is a machine we currently handle. 
                                // TODO: Currently we are only handling Mills for the tools. Update this as we handle more.
                                if ($machineType!='' && $machineType != 'MILL'){
                                    // Send a message back to let them know we are not handling this SPECIFIC type of machine
                                    $alertString = '<script>alert("Informational: We do not handle modifications for type ' . $machineType . ' yet. GCode will not be modified.");</script>';
                                    
                                    // Show the 'info message'
                                    echo $alertString;
                                }
                                else {
                                    // Create a sql to get the GCode and TaskID for this setup.
                                    $sql = 'SELECT GCode, GCodeFileSize, TaskID FROM machiningsetups WHERE MachiningSetupID=' . $setupNumber . ';';

                                    // Get the old GCode
                                    $oldSetupInfo = $db->queryDB($sql, $userRow, "setup_presentation occurance 7");

                                    // Determine if the query came back with a row
                                    if (mysqli_num_rows($oldSetupInfo)==1){
                                        // Get the readable row
                                        $oldSetupInfoAssocRow = $oldSetupInfo->fetch_assoc();

                                        // Sync the GCode in case something happened
                                        $syncMessage = syncSetupGCodeWithTask($db, $userRow, $oldSetupInfoAssocRow, 
                                                       $setupNumber, $order, $toolDetails);      

                                        // Determine if there were messages from the sync
                                        if ($syncMessage!=''){
                                            // Send the user an alert for this setup
                                            echo '<script>alert("' . $syncMessage . 
                                                 '\r\n---------------------------------\r\n' .
                                                 'State and assigned to user has been reset.");</script>';

                                            // Set a variable that will allow us to know to reset the state and Assigned To User.
                                            $returnStatusBack = true;
                                        }
                                    }
                                }
                            }

                            // Set the variable to state that the GCodes has not changed
                            $gCodeIsSame=true;
                        }
                    }
                    else if ($syncOldCode){
                        // return the fact that there is no GCode for this setup and a sync is necessary
                        echo '<script>alert("There is no GCode for setup number ' . $order . ' ' .
                                    'and a sync with GCode is required to leave this state. ' .
                                    '\r\n\r\nCheck the setup and ensure that there is a GCode ' . 
                                    'associated with the setup. GCode Sync Aborted.");</script>';
                                        
                        // Set a variable that will allow us to know to reset the state and Assigned To User.
                        $returnStatusBack = true;
                    }

                    // Set everything to values that would be appropriate of NO file
                    $toolStartFileName="";
                    $toolStartAttachmentFileType=""; 
                    $toolStartAttachmentContent=null;

                    // Get the flag to let me know they want to delete
                    $isRemoveTool=$_POST['isRemoveTool' . $setupNumber];

                    // Set a variable to determine if the file is staying the same
                    $isToolStartSame=false;

                    // Determine if this is NOT scheduled for deletion
                    if ($isRemoveTool==0){
                        // determine if the image has been uploaded
                        if(is_uploaded_file($_FILES['toolStartAttachment'.$setupNumber]['tmp_name'])) {
                            // Get the file size to be uploaded
                            $toolStartAttachmentFileSize = intval($_FILES['newToolStartAttachment'.$setupNumber]['size']);

                            // Determine if the file size is such that we can accept it.
                            if ($toolStartAttachmentFileSize < 20000000){
                                // Get the properties of the file to upload
                                $fname    = $db->getDBConnection()->real_escape_string($_FILES['toolStartAttachment'.$setupNumber]['name']); 
                                $tmpName  = $db->getDBConnection()->real_escape_string($_FILES['toolStartAttachment'.$setupNumber]['tmp_name']);
                                $toolStartAttachmentFileType = $db->getDBConnection()->real_escape_string($_FILES['toolStartAttachment'.$setupNumber]['type']);

                                //process the file
                                $toolStartFileName = $fname;
                                $toolStartAttachmentContent = $db->getDBConnection()->real_escape_string(file_get_contents($tmpName));
                            }
                            else {
                                // Let the user know the file was NOT uploaded
                                echo('<script>alert("The Tool Start file (\'' . $fname . '\') will not be uploaded, because it is too large for this site. File must be under 20MB.");</script>');
                            }
                        } 
                        else {
                            // Set the fact that the file is the same file
                            $isToolStartSame=true;
                        }
                    } 
                    
//    echo '<script>alert("GCode=' . $gCodeContent . ' ");</script>';
                        
                    // Let's create the update query off of what we have
                    $sql='UPDATE machiningsetups SET ';
                    $sql = $sql . 'hasM00=' . $m00;
                    if ($order!=null) {$sql = $sql . ', SetupOrder=' . $order;}
                    if ($setupByID!=null) {$sql = $sql . ', SetupByID=' . $setupByID;}
                    if ($setupCheckedByID!=null) {$sql = $sql . ', SetupCheckedByID=' . $setupCheckedByID;}
                    if ($side!=null) {$sql = $sql . ', Side=' . $side;}
                    if ($coordinateID!=null) {$sql = $sql . ', CoordinateSystem="' . $coordinateID . '"';}
                    $sql = $sql . ', HoldBy="' . $holdBy . '"';
                    $sql = $sql . ', Orientation="' . $orientation . '"';
                    if ($xLocation!=null) {$sql = $sql . ', xZeroLocation="' . $xLocation . '"';}
                    if ($yLocation!=null) {$sql = $sql . ', yZeroLocation="' . $yLocation . '"';}
                    if ($zLocation!=null) {$sql = $sql . ', zZeroLocation="' . $zLocation . '"';}
                    if (!$gCodeIsSame) {$sql = $sql . ', GCodeFileName="' . $programName . '"';}
                    if (!$gCodeIsSame) {$sql = $sql . ', GCodeFileLinesOfCode=' . $amountProgramLines;}
                    if (!$gCodeIsSame) {$sql = $sql . ', GCodeRuntime="' . $programRunTime . '"';}
                    if (!$gCodeIsSame) {$sql = $sql . ', GCodeFileType="' . $gCodeAttachmentFileType . '"';}
                    if (!$gCodeIsSame) {$sql = $sql . ', GCodeFileSize="' . $gCodeAttachmentFileSize . '"';}
                    if (!$gCodeIsSame) {$sql = $sql . ', GCode="' . $gCodeContent . '"';}
                    if (!$gCodeIsSame) {$sql = $sql . ', LastVerifiedByID=' . $userRow["UserID"];}
                    if (!$syncOldCode) {$sql = $sql . ', ToolDetails="' . $toolDetails . '"';}
                    $sql = $sql . ', ModdedToolDetails="' . $moddedToolDetails . '"';
                    if (!$isToolStartSame) {$sql = $sql . ', ToolStartFileName="' . $toolStartFileName . '"';}
                    if (!$isToolStartSame) {$sql = $sql . ', ToolStartFileType="' . $toolStartAttachmentFileType . '"';}
                    if (!$isToolStartSame) {$sql = $sql . ', ToolStart="' . $toolStartAttachmentContent . '"';}
                    $sql=$sql .' WHERE MachiningSetupID=' . $setupNumber . ';';
                }
//echo '<script>alert("' . addslashes($sql) . '");</script>';

                // Attempt to run the query and get the response
                if ($db->queryDB($sql, $userRow, "setup_presentation Form occurance 8.")){
                    // Add any new M00 Instructions
                    addNewChildNotesToDB($db, $userRow, 'SETUP_M00', $setupNumber);

                    // Update any old M00 Instructions
                    updateOldChildNotes($db, $userRow, 'SETUP_M00', $setupNumber);

                    // Add any new Setup Notes
                    addNewChildNotesToDB($db, $userRow, 'SETUP_NOTE', $setupNumber);

                    // Update any old Setup Notes
                    updateOldChildNotes($db, $userRow, 'SETUP_NOTE', $setupNumber);

                    // Add any new Operator Feedback Notes
                    addNewChildNotesToDB($db, $userRow, 'OPERATOR_FEEDBACK_NOTE', $setupNumber);

                    // Update any old Operator Feedback Notes
                    updateOldChildNotes($db, $userRow, 'OPERATOR_FEEDBACK_NOTE', $setupNumber);
                }
            }
        }
    }
    catch (Exception $ex) {
        // I only have this catch in here so I can use the finally
    } 
    finally {
        // Return the result
        return $returnStatusBack;
    }
}

function addNewSetupsToDB($db, $userRow, $taskID){
    // Determine if there are new setups
    if (isset($_POST['newSetupNumbers']) && $_POST['newSetupNumbers']!=0 &&
        $taskID != null && is_numeric($taskID)){
        // Get the amount of new setups as a variable
        $setupNumStrings=$_POST['newSetupNumbers'];
        $setupNumStringsNums=explode('|', $setupNumStrings);

        // Loop through and get all new note elements
        foreach ($setupNumStringsNums as $loopNumber){
            // Get the posted items that I am worried about
            $newOrder=htmlspecialchars($_POST['newOrder'.$loopNumber], ENT_QUOTES, 'UTF-8');
            $newSetupByID=htmlspecialchars($_POST['newSetupBy'.$loopNumber], ENT_QUOTES, 'UTF-8');
            $newSetupCheckedByID=htmlspecialchars($_POST['newSetupCheckedBy'.$loopNumber], ENT_QUOTES, 'UTF-8');
            $newSide=htmlspecialchars($_POST['newSide'.$loopNumber], ENT_QUOTES, 'UTF-8');
            $newCoordinateID=htmlspecialchars($_POST['newCoordinateID'.$loopNumber], ENT_QUOTES, 'UTF-8');
            $newM00 = (isset($_POST['newM00'.$loopNumber])?1:0);
            $newHoldBy=htmlspecialchars($_POST['newHoldBy'.$loopNumber], ENT_QUOTES, 'UTF-8');
            $newOrientation=htmlspecialchars($_POST['newOrientation'.$loopNumber], ENT_QUOTES, 'UTF-8');
            $newXLocation=htmlspecialchars($_POST['newXLocation'.$loopNumber], ENT_QUOTES, 'UTF-8');
            $newYLocation=htmlspecialchars($_POST['newYLocation'.$loopNumber], ENT_QUOTES, 'UTF-8');
            $newZLocation=htmlspecialchars($_POST['newZLocation'.$loopNumber], ENT_QUOTES, 'UTF-8');
            $newToolDetails=htmlspecialchars($_POST['newToolDetails'.$loopNumber], ENT_QUOTES, 'UTF-8');
            
            $newProgramName=htmlspecialchars($_POST['newProgramName'.$loopNumber], ENT_QUOTES, 'UTF-8');
            $newAmountProgramLines=htmlspecialchars($_POST['newAmountProgramLines'.$loopNumber], ENT_QUOTES, 'UTF-8');
            $newProgramRunTime=htmlspecialchars($_POST['newProgramRunTime'.$loopNumber], ENT_QUOTES, 'UTF-8');
            $newGCodeAttachmentFileType=null;
            $newGCodeAttachmentFileSize=null;
            $newGCodeContent=null;
            
            $newToolStartFileName = null; 
            $newToolStartAttachmentFileType = null; 
            $newToolStartAttachmentContent  = null;
            
            // determine if the image has been uploaded
            $hasGCodeBeenUploaded = is_uploaded_file($_FILES['newGCodeAttachment'.$loopNumber]['tmp_name']);
            if($hasGCodeBeenUploaded) {
                // Get the properties of the file to upload
                $fname    = $db->getDBConnection()->real_escape_string($_FILES['newGCodeAttachment'.$loopNumber]['name']); 
                $tmpName  = $db->getDBConnection()->real_escape_string($_FILES['newGCodeAttachment'.$loopNumber]['tmp_name']);

                // Determine if the file size is such that we can accept it.
                if ($newGCodeAttachmentFileSize < 20000000){
                    // get relavent values from this new file
                    $newProgramName = $fname;
                    $newGCodeAttachmentFileSize = intval($_FILES['newGCodeAttachment'.$loopNumber]['size']);
                    $newGCodeAttachmentFileType = $db->getDBConnection()->real_escape_string($_FILES['newGCodeAttachment'.$loopNumber]['type']);
                    $newGCodeContent = $db->getDBConnection()->real_escape_string(file_get_contents($tmpName));
                }
                else {
                    // reset all values to nothing
                    $newProgramName=null;
                    $newAmountProgramLines=0;
                    $newProgramRunTime='None';
                    
                    // Let the user know the file was NOT uploaded
                    echo("The GCode file ('" . $fname . "') will not be uploaded, because it is too large for this site. File must be under 20MB.");
                }
            }   
                                
            // determine if the image has been uploaded
            if(is_uploaded_file($_FILES['newToolStartAttachment'.$loopNumber]['tmp_name'])) {
                // Get the properties of the file to upload
                $fname    = $db->getDBConnection()->real_escape_string($_FILES['newToolStartAttachment'.$loopNumber]['name']); 
                $tmpName  = $db->getDBConnection()->real_escape_string($_FILES['newToolStartAttachment'.$loopNumber]['tmp_name']);

                // Determine if the file size is such that we can accept it.
                if ($newToolStartAttachmentFileSize < 20000000){
                    //process the file
                    $newToolStartFileName=$fname;
                    $newToolStartAttachmentContent = $db->getDBConnection()->real_escape_string(file_get_contents($tmpName));
                    $newToolStartAttachmentFileSize = intval($_FILES['newToolStartAttachment'.$loopNumber]['size']);
                    $newToolStartAttachmentFileType = $db->getDBConnection()->real_escape_string($_FILES['newToolStartAttachment'.$loopNumber]['type']);
                }
                else {
                    // Let the user know the file was NOT uploaded
                    echo("The Tool Start file ('" . $fname . "') will not be uploaded, because it is too large for this site. File must be under 20MB.");
                }
            }   
                                
            // Let's create the insert query off of what we have
            $sql='INSERT INTO machiningsetups (';
            if ($taskID!=null) {$sql = $sql . 'TaskID';}
            if ($newOrder!=null) {$sql = $sql . ', SetupOrder';}
            if ($newSetupByID!=null) {$sql = $sql . ', SetupByID';}
            if ($newSetupCheckedByID!=null) {$sql = $sql . ',SetupCheckedByID';}
            if ($newSide!=null) {$sql = $sql . ',Side';}
            if ($newCoordinateID!=null) {$sql = $sql . ',CoordinateSystem';}
            if ($newM00!=null) {$sql = $sql . ',hasM00';}
            if ($newHoldBy!=null) {$sql = $sql . ',HoldBy';}
            if ($newOrientation!=null) {$sql = $sql . ',Orientation';}
            if ($newXLocation!=null) {$sql = $sql . ',XZeroLocation';}
            if ($newYLocation!=null) {$sql = $sql . ',YZeroLocation';}
            if ($newZLocation!=null) {$sql = $sql . ',ZZeroLocation';}
            if ($newProgramName!=null) {$sql = $sql . ',GCodeFileName';}
            if ($newAmountProgramLines!=null) {$sql = $sql . ',GCodeFileLinesOfCode';}
            if ($newProgramRunTime!=null) {$sql = $sql . ',GCodeRuntime';}
            if ($newGCodeAttachmentFileType!=null) {$sql = $sql . ',GCodeFileType';}
            if ($newGCodeAttachmentFileSize!=null) {$sql = $sql . ',GCodeFileSize';}
            if ($hasGCodeBeenUploaded) {$sql = $sql . ',GCode';}
            if ($newToolStartFileName!=null) {$sql = $sql . ',ToolStartFileName';}
            if ($newToolDetails!=null) {$sql = $sql . ',ToolDetails';}
            if ($newToolDetails!=null) {$sql = $sql . ',ModdedToolDetails';}
            if ($newToolStartAttachmentFileType!=null) {$sql = $sql . ',ToolStartFileType';}
            if ($newToolStartAttachmentContent!=null) {$sql = $sql . ',ToolStart';}
            $sql=$sql .') VALUES (';
            if ($taskID!=null) {$sql = $sql . $taskID;}
            if ($newOrder!=null) {$sql = $sql . ', "' . $newOrder . '"';}
            if ($newSetupByID!=null) {$sql = $sql . ', "' . $newSetupByID . '"';}
            if ($newSetupCheckedByID!=null) {$sql = $sql . ', "' . $newSetupCheckedByID . '"';}
            if ($newSide!=null) {$sql = $sql . ', "' . $newSide . '"';}
            if ($newCoordinateID!=null) {$sql = $sql . ', "' . $newCoordinateID . '"';}
            if ($newM00!=null) {$sql = $sql . ', "' . $newM00 . '"';}
            if ($newHoldBy!=null) {$sql = $sql . ', "' . $newHoldBy . '"';}
            if ($newOrientation!=null) {$sql = $sql . ', "' . $newOrientation . '"';}
            if ($newXLocation!=null) {$sql = $sql . ', "' . $newXLocation . '"';}
            if ($newYLocation!=null) {$sql = $sql . ', "' . $newYLocation . '"';}
            if ($newZLocation!=null) {$sql = $sql . ', "' . $newZLocation . '"';}
            if ($newProgramName!=null) {$sql = $sql . ', "' . $newProgramName . '"';}
            if ($newAmountProgramLines!=null) {$sql = $sql . ', "' . $newAmountProgramLines . '"';}
            if ($newProgramRunTime!=null) {$sql = $sql . ', "' . $newProgramRunTime . '"';}
            if ($newGCodeAttachmentFileType!=null) {$sql = $sql . ', "' . $newGCodeAttachmentFileType . '"';}
            if ($newGCodeAttachmentFileSize!=null) {$sql = $sql . ', "' . $newGCodeAttachmentFileSize . '"';}
            if ($newGCodeContent!=null) {$sql = $sql . ', "' . $newGCodeContent . '"';}
            if ($newToolStartFileName!=null) {$sql = $sql . ', "' . $newToolStartFileName . '"';}
            if ($newToolDetails!=null) {$sql = $sql . ', "' . $newToolDetails . '"';}
            if ($newToolDetails!=null) {$sql = $sql . ', "' . $newToolDetails . '"';}
            if ($newToolStartAttachmentFileType!=null) {$sql = $sql . ', "' . $newToolStartAttachmentFileType . '"';}
            if ($newToolStartAttachmentContent!=null) {$sql = $sql . ', "' . $newToolStartAttachmentContent . '"';}
            $sql=$sql .');';
            
            // Attempt to run the query and get the response
            if ($db->queryDB($sql, $userRow, "setup_presentation Form occurance 9.")){
                // Get the most recent ID (setup)
                $newSetupID = mysqli_insert_id($db->getDBConnection());

                // Add any new M00 Instructions
                addNewChildNotesToDB($db, $userRow, 'SETUP_M00', $loopNumber, "NEW", $newSetupID);
                
                // Add any new Setup Notes
                addNewChildNotesToDB($db, $userRow, 'SETUP_NOTE', $loopNumber, "NEW", $newSetupID);
                
                // Add any new Setup Notes
                addNewChildNotesToDB($db, $userRow, 'OPERATOR_FEEDBACK_NOTE', $loopNumber, "NEW", $newSetupID);
            }
        }
    }
}

function retrieveSetupsDiv($db, $userRow, $inAssociatedCategoryID, &$validationHTML=""){
    // Get any current setups
    $results=retrieveCurrentSetups($db, $userRow, $inAssociatedCategoryID, $validationHTML="");
    
    // Determine if we added some setups
    $setupColorHtml = '';
    if ($results != '') {
        // Change the color of the Notes Title font
        $setupColorHtml = 'style="color:LimeGreen;"';
    }

    // Init all of the settings to the appropriate values
    $setupsDiv = '
                    <br><br>
                    <table width="100%">
                        <tr width="100%">
                            <td align="left" width="50%">
                                <label style="font-size: 20px;"><strong>New Setups: </strong></label>
                            </td>
                            <td align="right" width="50%">
                                <input type="hidden" id="newSetupNumbers" name="newSetupNumbers" value="0"></input>
                                <button type="button" onClick="javascript:addNewSetup();if (typeof _isDirty !== \'undefined\' && _isDirty !== null) {_isDirty=true;};" align="right">Add New Setup</button>
                            </td>
                        </tr>
                    </table>
                    <div id="newSetups" style="border-top-style:dashed; border-width: 1px; ">
                    </div>
                    ' .
                    $results .
                    '
                ';
    
    // Return the result
    return $setupsDiv;
}

function hasDuplicateToolsInDetails($toolDetails){
    try {
        // Split the string on end line characters
        $toolDetailsLines = explode("\n", $toolDetails);
        
        // Loop through the file looking for end line characters
        $currentTools = "";
        foreach($toolDetailsLines as $toolDetailsLine) {
            // Split the tooline into toolnumber and tool name
            $myArray = explode("-", $toolDetailsLine);

            // Determine if we have more than one variable
            if (count($myArray) > 1){
                // Take the first value and determine if that tool number is already in the tools
                $toolNumber=trim($myArray[0]) . "-";
                if (strpos($currentTools, $toolNumber) !== FALSE) {
                    // Send knowledge back that this has duplicate tools
                    return $myArray[0];
                }
                else {
                    // Add this tool number to the current array
                    $currentTools .= $toolNumber;
                }
            }
        }
    }
    catch (Exception $ex) {
        // If we got here, then there are no duplicates
        return "";
    }
    
    // If we got here, then there are no duplicates
    return "";
}

function hasDuplicateToolsInTaskSetups($db, $userRow, &$currentSuccess, &$duplicateToolsString, $taskIDToCheck=null){
    try {
        // Determine if they are currently successful as well as the proper variables are passed in
        if ($currentSuccess && 
            $taskIDToCheck!= null && $taskIDToCheck>0){
            // Create a query to get all of the setup IDs associated with the task to copy
            $sql = 'SELECT MachiningSetupID, ModdedToolDetails, SetupOrder FROM machiningsetups WHERE TaskID=' . $taskIDToCheck . ';';

            // Query the database for the setup IDs 
            $rows = $db->queryDB($sql, $userRow, "setup_presentation Form occurance 10");

            // Loop through the returned results
            while ($row=mysqli_fetch_array($rows)){
                // Get information about duplicates
                $duplicateTool=hasDuplicateToolsInDetails($row["ModdedToolDetails"]);

                // Determine if there are duplicate tools used in this setup
                if ($duplicateTool !== ""){
                    // add to the string that ther are duplicate tools for this setup
                    $duplicateToolsString .= " ++ TID: " . $taskIDToCheck . " -- Setup Order Number: " . $row["SetupOrder"] . " -- Tool Number: " . $duplicateTool . "\n";
                }
            }
        }
    } 
    catch (Exception $ex) {
        // Assign the output string as to what happened
        return $currentSuccess;
    } 
    finally {
        // Return the result
        return $currentSuccess;
    }
}
                
function copySetups($db, $userRow, &$currentSuccess, &$duplicateToolsString, $newTaskID, $taskIDToCopy=null){
    try {
        // Determine if they are currently successful as well as the proper variables are passed in
        if ($currentSuccess && 
            $taskIDToCopy!= null && $taskIDToCopy>0 && 
            $newTaskID!= null && $newTaskID>0){
            // Create a query to get all of the setup IDs associated with the task to copy
            $sql = 'SELECT MachiningSetupID, ToolDetails, SetupOrder FROM machiningsetups WHERE TaskID=' . $taskIDToCopy . ';';

            // Query the database for the setup IDs 
            $rows = $db->queryDB($sql, $userRow, "setup_presentation Form occurance 11");

            // Loop through the returned results
            while ($row=mysqli_fetch_array($rows)){
                // Get information about duplicates
                $duplicateTool=hasDuplicateToolsInDetails($row["ToolDetails"]);
                
                // Determine if there are duplicate tools used in this setup
                if ($duplicateTool !== ""){
                    // add to the string that ther are duplicate tools for this setup
                    $duplicateToolsString .= " ++ TID: " . $newTaskID . " -- Setup Order Number: " . $row["SetupOrder"] . " -- Tool Number: " . $duplicateTool . "\n";
                }
                
                // Create the query as if there is a parent
                $sql='INSERT INTO machiningsetups(TaskID, SetupOrder, SetupByID, ' . 
                        'SetupCheckedByID, SecondaryMachineID, SecondaryFixtureToUseID, ' . 
                        'Side, CoordinateSystem, hasM00, HoldBy, Orientation, ' . 
                        'xZeroLocation, yZeroLocation, zZeroLocation, M00Instructions, ' . 
                        'Notes, GCodeFileName, GCodeFileLinesOfCode, GCodeRuntime, ' . 
                        'GCodeFileType, GCodeFileSize, GCode, ToolDetails, ToolStart, ' . 
                        'ToolStartFileName, ToolStartFileType, ModdedToolDetails) ' . 
                      'SELECT ' . $newTaskID . ', SetupOrder, SetupByID, ' . 
                        'SetupCheckedByID, SecondaryMachineID, SecondaryFixtureToUseID, ' . 
                        'Side, CoordinateSystem, hasM00, HoldBy, Orientation, ' . 
                        'xZeroLocation, yZeroLocation, zZeroLocation, M00Instructions, ' . 
                        'Notes, GCodeFileName, GCodeFileLinesOfCode, GCodeRuntime, ' . 
                        'GCodeFileType, GCodeFileSize, GCode, ToolDetails, ToolStart, ' . 
                        'ToolStartFileName, ToolStartFileType, ToolDetails ' . 
                        'FROM machiningsetups ' . 
                        'WHERE MachiningSetupID=' . $row["MachiningSetupID"] . ';';

                // Attempt to update the task
                if (!$db->queryDB($sql, $userRow, "setup_presentation Form occurance 12")){
                    // Set all as a fail
                    $currentSuccess=false;
                }
                else {
                    // Get the most recent ID (setup)
                    $newSetupID = mysqli_insert_id($db->getDBConnection());

                    // Create M00 notes from the old setup to this setup
                    copyNotes($db, $userRow, "SETUP_M00", false, $currentSuccess, 
                              $newSetupID, $row["MachiningSetupID"]);

                    // Create setup notes from the old setup to this setup
                    copyNotes($db, $userRow, "SETUP_NOTE", false, $currentSuccess, 
                              $newSetupID, $row["MachiningSetupID"]);
                }
            }
        }
    } 
    catch (Exception $ex) {
        // Assign the output string as to what happened
        return $currentSuccess;
    } 
    finally {
        // Return the result
        return $currentSuccess;
    }
}
?>   
