<?php 
    // continue the session
    session_start();
    
    // init variables
    $updateAssignedToolMachineID=-1;
    $updateAssignedToolPosition=-1;
    
    // Look for the posts
    // Add includes to PHP files that I will need to access
    include 'php_only_scripts/database.php';
    include 'php_only_scripts/presentation.php';
    include 'php_only_scripts/toolLists_presentation.php';

    // Init some variables
    $userRow=null;

    // Assume NOT gtg
    $gtg = false;

    // Create and Setup the database
    $db = new Database();
    $db->setupTmsDB();

    // Attempt to log in with this user
    $currentUser = $db->getLoggedInSessionUser(session_id());
    
    // If there is only one result for a username/password combo, then they are good to go.
    if ($currentUser == null){
        exit;
    }
    elseif (mysqli_num_rows($currentUser)==1){
        // Attempt to get the user row
        $userRow = $currentUser->fetch_assoc();
        
        // Determine if this user has access to this page
        if ($userRow["UserLevel"]=='TIMECARD ONLY' || 
            $userRow["SUEmployee"]!=1 ||
            $userRow["AccountStatus"]!='ACTIVE'){
            // redirect to the invalid access page
            echo ('<script>window.location = "invalid_access.php";</script>');

            exit;
        }
        
        // Set the good to go until they log out
        $gtg = true;
        
        // Attempt to get passed in machine ID
        if (isset($_GET['updateAssignedToolMachineID'])){
            // Default for the machine ID is as a posted variable
            $updateAssignedToolMachineID=$_GET['updateAssignedToolMachineID'];
        }

        // Attempt to get passed in machine Name
        if (isset($_GET['updateAssignedToolPosition'])){
            // Default for the machine ID is as a posted variable
            $updateAssignedToolPosition=$_GET['updateAssignedToolPosition'];
        }

        // Determine if BOTH the user name AND password has been set
        if (isset($_POST['formSubmitted']) && 
            htmlspecialchars($_POST['formSubmitted'])=='TRUE'){
            // Determine if this user can even modify
            if (!$userRow["CanModify"]){
                // redirect to the tool list page
                echo ('<script>window.location = "machineToolList.php?toolsMachineID=' . $updateAssignedToolMachineID . '";</script>');
            }
            else {
                // Change the form back to NOT being submitted
                $_SESSION['formSubmitted']='FALSE';

                // Set the local variables from what was posted
                $machineID = htmlspecialchars($updateAssignedToolMachineID, ENT_QUOTES, 'UTF-8');
                $position = htmlspecialchars($updateAssignedToolPosition, ENT_QUOTES, 'UTF-8');
                $exposedLength = htmlspecialchars($_POST['ExposedLength'], ENT_QUOTES, 'UTF-8');
                $currentToolID = htmlspecialchars($_POST['CurrentToolID'], ENT_QUOTES, 'UTF-8');
                $currentToolIDOriginal = htmlspecialchars($_POST['CurrentToolIDOriginal'], ENT_QUOTES, 'UTF-8');
                $loadedOn = htmlspecialchars($_POST['LoadedOn'], ENT_QUOTES, 'UTF-8');
                $notes = htmlspecialchars(($_POST['Notes']==null?"":$_POST['Notes']), ENT_QUOTES, 'UTF-8');
                $requiredExposedLength = htmlspecialchars($_POST['RequiredExposedLength'], ENT_QUOTES, 'UTF-8');
                $removeAfter=(isset($_POST['RemoveAfter'])?1:0);
                $isCommonTool=(isset($_POST['CommonTool'])?1:0);
                $suggestedChangeNewToolID = htmlspecialchars($_POST['SuggestedChangeNewToolID'], ENT_QUOTES, 'UTF-8');
                $suggestedRemoveAfter=(isset($_POST['RemoveSuggestedToolAfter'])?1:0);
                $suggestedUseNewTool=(isset($_POST['SuggestedUseNewTool'])?1:0);
                $suggestedNote = htmlspecialchars($_POST['SuggestedToolNote'], ENT_QUOTES, 'UTF-8');
                
                // Determine if the tool is being changed at this moment but not cleared
                if ($currentToolID == -1){
                    // Change the loaded on to be today
                    $loadedOn = "";
                }
                elseif ($currentToolID != $currentToolIDOriginal){
                    // Get a current date value
                    $currentDate = new DateTime();
                    $currentDate->modify('-1 hour');
                    $currentDateString = $currentDate->format('Y-m-d H:i:s');

                    // Change the loaded on to be today
                    $loadedOn = $currentDateString;
                }
                
                // Let's create the update query off of what we have
                $sql='UPDATE assignedtools SET RemoveAfterUse=' . $removeAfter;
                if ($exposedLength!=null) {$sql = $sql . ', ExposedLength="' . $exposedLength . '"';}
                if ($currentToolID!=null) {$sql = $sql . ', CurrentToolID="' . $currentToolID . '"';}
                $sql = $sql . ', Notes="' . $notes . '"';
                if ($suggestedChangeNewToolID!=null) {$sql = $sql . ', SuggestedChangeNewToolID="' . $suggestedChangeNewToolID . '"';}
                if ($requiredExposedLength!=null) {$sql = $sql . ', SuggestedExposedLength="' . $requiredExposedLength . '"';}
                if ($suggestedNote!=null) {$sql = $sql . ', SuggestedNote="' . $suggestedNote . '"';}
                $sql = $sql . ', CommonTool=' . $isCommonTool;
                $sql = $sql . ', SuggestedUseNewTool=' . $suggestedUseNewTool;
                if ($loadedOn!=null) {$sql = $sql . ', LoadedOn="' . $loadedOn . '"';}
                $sql = $sql . ', SuggestedRemoveToolAfterUse=' . $suggestedRemoveAfter;
                $sql=$sql .' WHERE MachineID=' . $machineID;
                $sql=$sql .' AND Position=' . $position . ';';

//echo '<script>alert("' . addslashes($sql) . '");</script>';
                // Attempt to run the query and evaluate the response
                if (!$db->queryDB($sql, $userRow, "updateAssignedTool Form occurance 1")){
                    echo '<script>alert("Assigned tool was NOT updated in the database. Please check the data and try again.");</script>';
                    // TODO: How do I want to display a failure to the user?
                }
                else {
                    // redirect to the machine tool list page
                    echo ('<script>window.location = "machineToolList.php?toolsMachineID=' . $updateAssignedToolMachineID . '";</script>');
                }
            }
        }
        else {
            // Set the form submitted session variable to FALSE
            $_POST['formSubmitted']='FALSE';
        }
    }
?>
        
﻿<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>Task Management System - Update Assigned tool</title>

    <meta name="keywords" content="GIS,data,testing,IT" />
    <meta name="description" content="EES Divisions." />

    <script src="./SpryAssets/SpryMenuBar.js" type="text/javascript"></script>
    
    <script src="./javascript/general.js" type="text/javascript"></script>
    <script src="./javascript/addresses.js" type="text/javascript"></script>
    
    <script src="scripts/jpicker-1.1.6/jquery-1.4.4.min.js" type="text/javascript"></script>
    <script src="scripts/jpicker-1.1.6/jpicker-1.1.6.min.js" type="text/javascript"></script>
    <script language="JavaScript" src="scripts/gen_validatorv4.js" type="text/javascript"></script>
    
    <link rel="icon" href="images/ees_ico.ico"/> 
    
    <link href="scripts/jpicker-1.1.6/css/jPicker-1.1.6.css" rel="stylesheet" type="text/css"/>
    <link href="./SpryAssets/SpryMenuBarHorizontal.css" rel="stylesheet" type="text/css" />
    <link href="./SpryAssets/SpryMenuBarVertical.css" rel="stylesheet" type="text/css" />
    <link rel = "stylesheet" type="text/css" href="./css/contentpage.css" >

    <style type="text/css">
        .Table
        {
            display: table;
            width: 95%;
            margin: 0 auto;
        }
        .Title
        {
            display: table-caption;
            text-align: center;
            font-weight: bold;
            font-size: larger;
        }
        .Heading
        {
            display: table-row;
            font-weight: bold;
            text-align: center;
            width: 100%;
        }
        .Row
        {
            display: table-row;
            width: 100%;
            height: 12px;
        }
        .cell
        {
            display: table-cell;
            border: solid;
            border-width: thin;
            padding-left: 1px;
            padding-right: 1px;
            font-weight: bold;
            font-size: 10px;
        }
        .machineNameCell
        {
            text-align: left;
            width: 7%;
        }
        .nameCell
        {
            text-align: center;
        }
        .assignedToolsPositionCell
        {
            text-align: center;
            width: 3%;
        }
        .toolsDiameterCell
        {
            width: 7%;
            text-align: center;
        }
        .toolsCuttingLengthCell
        {
            width: 7%;
            text-align: center;
        }
        .toolsCornerRadiusCell
        {
            width: 7%;
            text-align: center;
        }
        .toolsAngleCell
        {
            width: 7%;
            text-align: center;
        }
        .toolsFluteNumberCell
        {
            width: 4%;
            text-align: center;
        }
        .toolsTypeCell, .brandCell, .pnCell
        {
            width: 10%;
            text-align: center;
        }
        .assignedToolsExposedLengthCell
        {
            width: 9%;
            text-align: center;
        }
        .updateCell
        {
            width: 5%;
            text-align: center;
        }
        .suggestedBackground {
            background:repeating-linear-gradient(
                45deg,
                rgba(77, 77, 77, .5),
                rgba(77, 77, 77, .5) 10px,
                rgba(230, 230, 0, .5) 10px,
                rgba(230, 230, 0, .5) 20px
            );
        }
        .commonToolBackground {
            background:repeating-linear-gradient(
                45deg,
                rgba(204, 0, 0, .5),
                rgba(204, 0, 0, .5) 10px,
                rgba(77, 77, 77, .5) 10px,
                rgba(77, 77, 77, .5) 20px
            );
        }
        span {
          display: inline-block;
          vertical-align: middle;
          line-height: normal;      
        }

        /*----------------------------------------------
        CSS settings for HTML div Exact Center
        ------------------------------------------------*/
        #showAllTools {
            align-items: center;
            width:100%;
            height:100%;
            top:0;
            left:0;
            display:none;
            position:fixed;
            background-color: rgba(49, 49, 49, .95);
            overflow:hidden;
        }
        
        #showAllToolsBackground {
            background-color: rgba(255, 255, 255, 1); 
            overflow-y: scroll; 
            top: 4%;
            left: 7%;
            right: 7%;
            width: 85%; 
            height: 90%; 
            padding: 10px; 
            margin: 0 auto;
            position:absolute;
        }
        
        #closeNewBtn:hover {
            float:right;
            display:inline-block;
            padding:2px 5px;
            background-color: rgba(60, 108, 155, 1);
        }    
        
        #closeDiv {
            position: fixed;
            left: 95%;
            top: 48%;
            float:right;
            display:inline-block;
            padding:2px 5px;
            background-color: rgba(49, 49, 49, 0);
        }   
    </style>
    <script type="text/javascript">
        var selectionResultDesc="";
        var selectionResultID='';
        var suggestedNewTool=true;
        
        function ifCheckedPopulateDatePlusDays(/*Args[controlToCheck,controlToPopulate,format,days]*/){
            // Create a variable for the checked value
            var isChecked= document.getElementById(arguments[0]).checked;
            
            // Get the control off of the first passed in argument, which should be the control to populate
            var controlToPopulate = document.getElementById(arguments[1]);
            
            // Determine if we are creating tomorrow or not
            if (isChecked == true) {
                // Create the date
                var theDate = new Date(); 
                theDate.setDate(theDate.getDate()+arguments[3]); 

                // Create the date string
                var theDateString = date2str(theDate, arguments[2]);

                // populate the control with the formatted date
                controlToPopulate.value = theDateString;
            }
            else {
                // populate the control with the formatted date
                controlToPopulate.value = "";
            }
        }
        
        function disableControlsBasedOnCurrentTool() {
            // Determine if ther is no current tool
            if (document.getElementById("CurrentToolID").value==="-1"){
                // Clear all that need to be 
                document.getElementById("RemoveAfter").checked=false;
                document.getElementById("ExposedLength").value = '';
                document.getElementById('Notes').value = '';
                
                // Disable all that need to be 
                document.getElementById("RemoveAfter").disabled = true;
                document.getElementById("ExposedLength").disabled = true;
                document.getElementById('Notes').disabled = true;
            }
            else {
                // disable all that need to be 
                document.getElementById("RemoveAfter").disabled = false;
                document.getElementById("ExposedLength").disabled = false;
                document.getElementById('Notes').disabled = false;
            }
            
            // Now do the suggested tool area
            disableControlsBasedOnSuggestedTool();
        }
        
        function disableControlsBasedOnSuggestedTool() {
            // Get the description element
            var descElem = document.getElementById("SuggestedChangeDescription");
            
            // Determine if there is no suggested tool
            if (descElem.value === ''){
                // Clear all that need to be 
                document.getElementById("RemoveSuggestedToolAfter").checked = 0;
                document.getElementById("RequiredExposedLength").value = '0.000';
                document.getElementById('SuggestedUseNewTool').checked = 0;
                document.getElementById('SuggestedToolNote').value = '';
                
                // Disable all that need to be 
                document.getElementById("RemoveSuggestedToolAfter").disabled = true;
                document.getElementById("RequiredExposedLength").disabled = true;
                document.getElementById('SuggestedUseNewTool').disabled = true;
                document.getElementById('SuggestedToolNote').disabled = true;
              
                // Hide the suggested controls
                setDivVisibility("suggestedChangeAttributes", 0);
            }
            else {
                // enable all that need to be 
                document.getElementById("RemoveSuggestedToolAfter").disabled = false;
                document.getElementById("RequiredExposedLength").disabled = false;
                document.getElementById('SuggestedUseNewTool').disabled = false;
                document.getElementById('SuggestedToolNote').disabled = false;
                
                // Show the suggested controls
                setDivVisibility("suggestedChangeAttributes", 1);
            }
        }
        
        function clearCurrentTool() {
            // Get the description element
            var descElem = document.getElementById("CurrentToolDescription");
            
            // Reset the current tool start
            descElem.value = '';
            
            // Reset the current tool ID to it's original value
            document.getElementById('CurrentToolID').value = '-1';
            
            // Now disable or enable controls depending on the new value
            disableControlsBasedOnCurrentTool();
           
            // Set the border back to black and solid
            descElem.style.border = '1px dotted red';
            
            // Determine if it is already the same
            if (document.getElementById('CurrentToolIDOriginal').value==='-1'){
                // Set the border back to black and solid
                descElem.style.border = '1px solid black';
            }
        }
        
        function clearSuggestedTool(){
            // Get the description element
            var descElem = document.getElementById("SuggestedChangeDescription");

            // Reset the suggested tool description to it's original value
            descElem.value = '';

            // Reset the suggested new tool id to it's original value
            document.getElementById('SuggestedChangeNewToolID').value = '-1';

            // Set the border back to black and solid
            descElem.style.border = '1px dotted red';
            
            // Determine if this was the same as what it was before
            if (document.getElementById('SuggestedChangeNewToolIDOriginal').value === '-1'){
                // Set the border back to black and solid
                descElem.style.border = '1px solid black';
            }
            
            // Now disable or enable controls depending on the new value
            disableControlsBasedOnSuggestedTool();
        }
        
        function resetCurrentTool() {
            // Get the description element
            var descElem = document.getElementById("CurrentToolDescription");
            
            // Reset the current tool description to it's original value
            descElem.value = document.getElementById('CurrentToolDescriptionOriginal').value;
            
            // Reset the current tool ID to it's original value
            document.getElementById('CurrentToolID').value = document.getElementById('CurrentToolIDOriginal').value;
            
            // Reset current tool attributes if they are different
            document.getElementById('LoadedOn').value = document.getElementById('LoadedOnOriginal').value;
            document.getElementById('RemoveAfter').checked = parseInt(document.getElementById('RemoveAfterOriginal').value);
            document.getElementById('ExposedLength').value = document.getElementById('ExposedLengthOriginal').value;
            document.getElementById('Notes').value = document.getElementById('NotesOriginal').value;
            document.getElementById('CommonTool').checked = parseInt(document.getElementById('CommonToolOriginal').value);
            
            // Now disable or enable controls depending on the new value
            disableControlsBasedOnCurrentTool();
           
            // Set the border back to black and solid
            descElem.style.border = '1px solid black';
        }
        
        function resetSuggestedTool(){
            // Get the description element
            var descElem = document.getElementById("SuggestedChangeDescription");
            
            // Reset the suggested tool description to it's original value
            descElem.value = document.getElementById('SuggestedChangeDescriptionOriginal').value;

            // Reset the suggested new tool id to it's original value
            document.getElementById('SuggestedChangeNewToolID').value = document.getElementById('SuggestedChangeNewToolIDOriginal').value;
            
            // Clear all that need to be 
            document.getElementById("RemoveSuggestedToolAfter").checked = parseInt(document.getElementById("RemoveSuggestedToolAfterOriginal").value);
            document.getElementById("RequiredExposedLength").value = document.getElementById("RequiredExposedLengthOriginal").value;
            document.getElementById('SuggestedUseNewTool').checked = parseInt(document.getElementById('SuggestedUseNewToolOriginal').value);
            document.getElementById('SuggestedToolNote').value = document.getElementById('SuggestedToolNoteOriginal').value;

            // Set the border back to black and solid
            descElem.style.border = '1px solid black';
            
            // Now enable/disable controls in the the suggested tool area
            disableControlsBasedOnSuggestedTool();
        }
        
        function newToolSelected(){
            var description = '';
            var descElem = null;
            var idElem = null;

            // Split up the string returned in the description variable
            var descArray = selectionResultDesc.split("||");
            
            // Determine if we have an array larger than 1
            if (descArray.length>1){
                // Loop through the array to build the description
                for(var i = 0; i < descArray.length; i++)
                {
                    // Add this variable to the array plus a line feed
                    description = description + descArray[i] + '\n';
                }

                // Determine if this is coming from the suggested 
                if (suggestedNewTool){
                    // Add That this came from suggested
                    description = description + 'INFO: NEW suggested tool to be setup.';

                    // Get the element as the suggested description element
                    descElem = document.getElementById("SuggestedChangeDescription");

                    // Get the element id as the suggested id element
                    idElem = document.getElementById("SuggestedChangeNewToolID");
                }
                else {
                    // Get the element as the current description element
                    descElem = document.getElementById("CurrentToolDescription");

                    // Get the element id as the current id element
                    idElem = document.getElementById("CurrentToolID");
                }
                
                // Set the ID to what is set in the variable
                idElem.value = selectionResultID;

                // Set the description what was built
                descElem.value = description;

                // Set the border back to red and dotted
                descElem.style.border = '1px dotted red';
            }
            
            // Now disable or enable controls depending on the new value
            disableControlsBasedOnCurrentTool();
           
            // Hide the tools div that should still be shown
            div_hide('showAllTools');
        }
        
        function displayCorrectTypesAll() {
            // get the type combo now by ID
            var cmbTypes = document.getElementById('typeForAll');

            // Loop through the values in the combo box
            for(i = 0; i < cmbTypes.length; i++) {
                // Go onto next index if we are on the ALL TYPES one
                if (cmbTypes[i].value === "ALL TYPES"){
                    // Move to the next element
                    continue;
                }
                
                // assume that the type will become invisible
                var visible = false;
                
                // get value with spaces changed to underscores
                var loopTypeID = cmbTypes[i].value.split(" ").join("_");
                
                // Determine if it is the selected one to be visible or all visible
                if (cmbTypes[i].selected ||
                    cmbTypes[0].selected) {
                    // This is the one to be visible
                    var visible = true;
                }

                // Call the function to set visibility
                setDivVisibility(loopTypeID, visible);
            }
        } 
        
        function setDivVisibility(){
            // Set the div to hide as the ID passed in.  Assume good ID.
            var divToHide = document.getElementById(arguments[0]);
            
            // Determine if the DIV Exists
            if (typeof(divToHide) !== 'undefined' && divToHide !== null){
                // Determine if it is to be visible
                if (arguments[1]) {
                    // show it
                    divToHide.style.display = 'block';
                } else {
                    // Hide it
                    divToHide.style.display = 'none';
                }
            }
        }

        //Function To Display Tools Popup
        function div_showAllTools() {
            // Get the outer div and show it
            div_show('showAllTools');
            
            // Get the show all tools div
            var showAllToolsBackgroundDiv = document.getElementById('showAllToolsBackground');
            
            // Scroll back to the top of the DIV
            showAllToolsBackgroundDiv.scrollTop = 0;
        }

        document.addEventListener('DOMContentLoaded', function() {
            // Now disable or enable controls depending on the value
            disableControlsBasedOnCurrentTool();
        }, false);

    </script>    
</head>

<body class="thrColElsHdr">

<div id="container">
  
<!-- start of banner wrap --->

<div id="topContent">
  
<div>
   <div class="MenuBarHorizontal" id="navBar">  <ul id="TopNav" class="MenuBarHorizontal">

    <script type="text/javascript">
    <!--
    var MenuBar2 = new Spry.Widget.MenuBar("TopNav", {imgDown:"./SpryAssets/SpryMenuBarDownHover.gif", imgRight:"./SpryAssets/SpryMenuBarRightHover.gif"});
    //-->
    </script>

    </div>
  </div>
</div>
<!-- end of banner wrap --->

  <!-- end #header -->
  <br class="clearfloat" />
  <div id="sidebar1">
      <?php 
        // Determine if we are GTG
        if ($gtg){
          // Render the appropriate presentation for the tasks sidebar
          getSidebar($userRow, 'equipment');
        }
      ?>       
      <br class="clearfloat" />
  <!-- end #sidebar1 -->
  </div>
  
  <!-- start #mainContent -->
  <div id="mainContent">
    <div class="maintitle">Task Management System - Update Assigned Tool</div>
    <div class="breadcrumb"> <a href="../index.html"> Home </a> > <a href="tasks.php"> Task Management System </a> > <a href="updateAssignedTool.php"> Update Assigned Tool </a></div>

    <br>
    <?php
        // Determine if they are GTG
        if ($gtg){
            echo getAssignedTool($db, $userRow, $updateAssignedToolMachineID, $updateAssignedToolPosition);
        }
        else {
            // Set the login failed to true
            $_SESSION['failedLogin']='TRUE';

            // Add a session variable that is this page URL
            $_SESSION['pageToGoTo']=$_SERVER['REQUEST_URI'];

            // redirect to the login page
            echo ('<script>window.location = ".";</script>');
        }
    ?>       
    
  <!-- end #mainContent -->
  
  <!-- This clearing element should immediately follow the #mainContent div in order to force the #container div to contain all child floats -->
  <br class="clearfloat" />
  
  <!-- start #footer --></div>
   <div id="footer">
    <p>© 2018 Evolve Engineering and Software. EES, Evolve Engineering and Software, EES Logo are registered marks of Evolve Engineering and Software.</p>
  <!-- end #footer -->
   </div>
<!-- end #container -->
</div>

<div id="showAllTools">
    <div id="showAllToolsBackground">
        <div id="closeDiv">
            <button id="closeNewBtn" onclick="javascript:selectionResultDesc=''; selectionResultID=''; div_hide('showAllTools');">Close</button>
        </div>        
        <?php
            // Determine if they are GTG
            if ($gtg){
                // Time to query for their tools
                echo(retrieveToolsAsListForAssigned($db, $userRow));
            }
            else {
                // Set the login failed to true
                $_SESSION['failedLogin']='TRUE';

                // Add a session variable that is this page URL
                $_SESSION['pageToGoTo']=$_SERVER['REQUEST_URI'];

                // redirect to the login page
                echo ('<script>window.location = ".";</script>');
            }
        ?>       
    </div>
<!-- Popup Div Ends Here -->
</div>
<!-- Popup Div Ends Here -->
</div>
    
</body>

</html>