<?php 
    // continue the session
    session_start();
    
    // init variables
    $updateMachineId=-1;
    
    // now determine if it was posted
    if (isset($_GET['updateMachineID'])){
        // Default for the machine ID is as a posted variable
        $updateMachineId=$_GET['updateMachineID'];
    }
    
    // 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/machine_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 || 
            $updateMachineId == -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;

        // 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 machine page
                echo ('<script>window.location = "machines.php";</script>');
            }
            else {
                // Change the form back to NOT being submitted
                $_SESSION['formSubmitted']='FALSE';

                // Set the local variables from what was posted
                $machineID = htmlspecialchars($_POST['machineID'], ENT_QUOTES, 'UTF-8');
                $name = htmlspecialchars($_POST['name'], ENT_QUOTES, 'UTF-8');
                $type = htmlspecialchars($_POST['type'], ENT_QUOTES, 'UTF-8');
                $description = htmlspecialchars($_POST['description'], ENT_QUOTES, 'UTF-8');
                $xTravel = htmlspecialchars($_POST['xTravel'], ENT_QUOTES, 'UTF-8');
                $yTravel = htmlspecialchars($_POST['yTravel'], ENT_QUOTES, 'UTF-8');
                $zTravel = htmlspecialchars($_POST['zTravel'], ENT_QUOTES, 'UTF-8');
                $dateAcquired = htmlspecialchars($_POST['dateAcquired'], ENT_QUOTES, 'UTF-8');
                $maxRPM = htmlspecialchars($_POST['maxRPM'], ENT_QUOTES, 'UTF-8');
                $airBlast=(isset($_POST['airBlast'])?1:0);
                $showOnWhiteboard=(isset($_POST['showOnWhiteboard'])?1:0);
                $maxTools = htmlspecialchars($_POST['maxTools'], ENT_QUOTES, 'UTF-8');
                $isDown=(isset($_POST['isDown'])?1:0);
                
                $lastMaxTools = -1;

                // Determine if we have tools added
                if ($maxTools!=null) {
                    // Create the query string to query for the current maximum tools
                    $sql = 'SELECT MaxTools FROM machines WHERE MachineID='. $machineID . ';';

                    // Attempt to get the max tools from previous
                    $maxToolsRow = $db->queryDB($sql, $userRow, "updateMachine Form occurance 1");
                    
                    // Attempt to get the max tools row
                    $maxToolsAssocTask = $maxToolsRow->fetch_assoc();

                    // Set the max tools
                    $lastMaxTools = $maxToolsAssocTask["MaxTools"];

                    // Determine if the new max tools is a value greater than the old
                    if ($maxTools>$lastMaxTools){
                        // Loop through from the last row added to the current max
                        for ($toolNumber = ($lastMaxTools+1); $toolNumber < ($maxTools+1); $toolNumber++) {
                            // Insert a row with only the new tool number and Machine id into assigned tools
                            $sql='INSERT INTO assignedtools (MachineID, Position) ' .
                                 'VALUES (' . $machineID . ', ' . $toolNumber . ');';

                            // Attempt to run the query and evaluate the response
                            $db->queryDB($sql, $userRow, "updateMachine Form occurance 2");
                        }
                    }
                    else {
                        // Create a query to remove all rows that are greater than the new max
                        $sql='DELETE FROM assignedtools ' . 
                             'WHERE MachineID = ' . $machineID . ' ' . 
                             'AND Position > ' . $maxTools . ';';

                        // Attempt to delete them
                        $db->queryDB($sql, $userRow, "updateMachine Form occurance 3");
                    }
                }

                // Let's create the update query off of what we have
                $sql='UPDATE machines SET ';
                if ($name!=null) {$sql = $sql . 'Name="' . $name . '"';}
                if ($type!=null) {$sql = $sql . ', Type="' . $type . '"';}
                if ($description!=null) {$sql = $sql . ', Description="' . $description . '"';}
                if ($xTravel!=null) {$sql = $sql . ', XTravel="' . $xTravel . '"';}
                if ($yTravel!=null) {$sql = $sql . ', YTravel="' . $yTravel . '"';}
                if ($zTravel!=null) {$sql = $sql . ', ZTravel="' . $zTravel . '"';}
                if ($dateAcquired!=null) {$sql = $sql . ', DateAcquired="' . $dateAcquired . '"';}
                if ($maxRPM!=null) {$sql = $sql . ', MaxRPM="' . $maxRPM . '"';}
                $sql = $sql . ', AirBlast=' . $airBlast;
                $sql = $sql . ', ShowOnWhiteboard=' . $showOnWhiteboard;
                if ($maxTools!=null) {$sql = $sql . ', MaxTools="' . $maxTools . '"';}
                $sql = $sql . ', IsDown=' . $isDown;
                $sql=$sql .' WHERE MachineID=' . $updateMachineId . ';';

                // Attempt to run the query and evaluate the response
                if (!$db->queryDB($sql, $userRow, "updateMachine Form occurance 4")){
                    echo '<script>alert("Machine 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 machines page
                    echo ('<script>window.location = "machines.php";</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 Machine</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/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" >

    <script type="text/javascript">
      $(function()
        {
          $.fn.jPicker.defaults.images.clientPath='scripts/jpicker-1.1.6/images/';
        });
    </script>
        
    <style type="text/css">
        .Table
        {
            display: table;
            width: 100%;
        }
        .Title
        {
            display: table-caption;
            text-align: center;
            font-weight: bold;
            font-size: larger;
            width: 100%;
        }
        .Heading
        {
            display: table-row;
            font-weight: bold;
            text-align: center;
            width: 100%;
        }
        .Row
        {
            display: table-row;
            width: 100%;
        }
        .cell
        {
            display: table-cell;
            border: solid;
            border-width: thin;
            padding-left: 2px;
            padding-right: 2px;
            font-weight: bold;
            font-size: 10;
        }
        .fileInputCell
        {
            width: 50%;
            text-align: center;
        }
        .buttonCell
        {
            width: 35%;
            text-align: center;
        }
    </style>
</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 Machine</div>
    <div class="breadcrumb"> <a href="../index.html"> Home </a> > <a href="tasks.php"> Task Management System </a> > <a href="updateMachine.php"> Update Machine </a></div>

    <br>
    <?php
        // Determine if they are GTG
        if ($gtg){
            echo getMachine($db, $userRow, $updateMachineId);
        }
        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>

</body>

</html>