<?php
// Include config file
require_once "../assets/php/config.php";
error_log("Loading Page", 0);
// Define variables and initialize with empty values
$sysID = $sysType = $location = $EthMac = $Winkey = "";
$sysID_err = $sysType_err = $location_err = $EthMac_err = $Winkey_err = "";
// Processing form data when form is submitted
if(isset($_POST["id"]) && !empty($_POST["id"])){
    // Get hidden input value
    $id = $_POST["id"];

   // Validate SysID
   $input_sysID = trim($_POST["xsysID"]);
   if(empty($input_sysID)){
       $sysID_err = "Please enter the system ID";     
   }
     else{
       $sysID = $input_sysID;
   }

       // validate location
    $input_location = trim($_POST["location"]);
    if(empty($input_location)){
        $location_err = "please enter a location";     
    } else{
        $location = $input_location;
    } 
          // validate location
          $input_sysType = trim($_POST["System_type"]);
          if(empty($input_sysType)){
              $sysType_err = "please enter the type of system";     
          } else{
              $sysType = $input_sysType;
          } 

          $input_EthMac = trim($_POST["MAC_Adress"]);
          if(empty($input_EthMac)){
              $EthMac_err = "Please enter a MAC_Adress";
          }  else{
              $EthMac = $input_EthMac;
          }
          $input_Winkey = trim($_POST["Win_Key"]);
          if(empty($input_Winkey)){
              $Winkey_err = "Please enter a Windows Key";
          }  else{
              $Winkey = $input_Winkey;
          }
    // Check input errors before inserting in database
    if(empty($sysID_err) && empty($location_err) && empty($requestype_err) && empty($request_by_err) && empty($reason_err)){
        // Prepare an update statement
        $sql = "UPDATE systems SET sysID=?,sysType=?,location=?,EthMac=?, WinKey=?  WHERE id=?";
         
        if($stmt = mysqli_prepare($link, $sql)){
            // Bind variables to the prepared statement as parameters
            mysqli_stmt_bind_param($stmt, "sssssi", $param_sysID, $param_systype, $param_location, $param_EthMac, $param_Winkey, $param_id);
            
            // Set parameters
            $param_sysID = $sysID;
            $param_systype = $sysType;
            $param_location = $location;
            $param_EthMac = $EthMac;
            $param_Winkey = $Winkey;
            $param_id = $id;
            
            // Attempt to execute the prepared statement
            if(mysqli_stmt_execute($stmt)){
                // Records updated successfully. Redirect to landing page
                header("location: systems.php");
                exit();
            } else{
                echo "Something went wrong. Please try again later.";
            }
        }
         
        // Close statement
        mysqli_stmt_close($stmt);
    }
    
} else{
    // Check existence of id parameter before processing further
    if(isset($_GET["id"]) && !empty(trim($_GET["id"]))){
        // Get URL parameter
        $id =  trim($_GET["id"]);
        
        // Prepare a select statement
        $sql = "SELECT * FROM systems WHERE id = ?";
        if($stmt = mysqli_prepare($link, $sql)){
            // Bind variables to the prepared statement as parameters
            mysqli_stmt_bind_param($stmt, "i", $param_id);
            
            // Set parameters
            $param_id = $id;
            
            // Attempt to execute the prepared statement
            if(mysqli_stmt_execute($stmt)){
                $result = mysqli_stmt_get_result($stmt);
    
                if(mysqli_num_rows($result) == 1){
                    /* Fetch result row as an associative array. Since the result set contains only one row, we don't need to use while loop */
                    $row = mysqli_fetch_array($result, MYSQLI_ASSOC);
                    
                    // Retrieve individual field value
                    $sysID = $row["sysID"];
                    $sysType = $row["sysType"];
                    $location = $row["location"];
                    $Winkey = $row["WinKey"];
                    $EthMac = $row["EthMac"];
                    $id = $row['id'];
                    $string = $row["sysMeta"];
                } else{
                    // URL doesn't contain valid id. Redirect to error page
                    header("location: error.php");
                    exit();
                }
                
            } else{
                echo "Oops! Something went wrong. Please try again later.";
            }
        }
        // Close statement
        mysqli_stmt_close($stmt);

    }  else{
        // URL doesn't contain id parameter. Redirect to error page
        header("location: error.php");
        exit();
    }   

}

// System meta Functions
function updateDB() {
    global $link, $string, $id, $row;
        $sql1 = "UPDATE systems SET sysMeta=? WHERE id=?"; 
        if($stmt1 = mysqli_prepare($link, $sql1)){
            // Bind variables to the prepared statement as parameters
            mysqli_stmt_bind_param($stmt1, "si", $param_string, $param_id);
            
            // Set parameters
            $param_string = $string;
            $param_id = $id;
            
            // Attempt to execute the prepared statement
            if(mysqli_stmt_execute($stmt1)){
                // Records updated successfully. Redirect to landing page
            } else{
                echo "Something went wrong. Please try again later.";
            }
        }
         
        // Close statement
        mysqli_stmt_close($stmt1);
   header("location: ?id=$id"); 
}

//Adding entry to sting
if(isset($_POST['typedata']))
{
$string = $string."\n".$_POST['typedata']."*".$_POST['metadata'];
updateDB();
}

if(isset($_GET['deldata']))
{
$string = str_replace("\n".$_GET['deldata'], '', $string);
//Removing string witout "\n" incase there is one entry
$string = str_replace($_GET['deldata'], '', $string);
updateDB();
}

// Close connection
mysqli_close($link);

$trimmedString = trim($string);
$lines = explode("\n", $trimmedString);
?>
 
 <!DOCTYPE html>
<html lang="en-us">

<head>
    <title>SYSDesk - Edit system #<?php echo $sysID; ?></title>
    <meta charset="UTF-8">
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="shortcut icon" type="image/x-icon" href="../assets/favicon.ico" />
    <link href="https://fonts.googleapis.com/css?family=Roboto:400,100,100italic,300,300italic,400italic,500,500italic,700italic,700,900,900italic" rel="stylesheet">
    <!-- STYLESHEETS -->
    <style type="text/css">
            [fuse-cloak],
            .fuse-cloak {
                display: none !important;
            }
        </style>
    <!-- Icons.css -->
    <link type="text/css" rel="stylesheet" href="../assets/icons/fuse-icon-font/style.css">
    <!-- Animate.css -->
    <link type="text/css" rel="stylesheet" href="../assets/node_modules/animate.css/animate.min.css">




    <!-- Perfect Scrollbar -->
    <link type="text/css" rel="stylesheet" href="../assets/node_modules/perfect-scrollbar/css/perfect-scrollbar.css" />
    <!-- Fuse Html -->
    <link type="text/css" rel="stylesheet" href="../assets/fuse-html/fuse-html.min.css" />
    <!-- Main CSS -->
    <link type="text/css" rel="stylesheet" href="../assets/css/main.css">
	<!-- Custom CSS -->
	<link type="text/css" rel="stylesheet" href="../assets/css/custom.css">
    <!-- / STYLESHEETS -->
    
    <!-- JAVASCRIPT -->
    <!-- jQuery -->
    <script type="text/javascript" src="../assets/node_modules/jquery/dist/jquery.min.js"></script>
    <!-- Mobile Detect -->
    <script type="text/javascript" src="../assets/node_modules/mobile-detect/mobile-detect.min.js"></script>
    <!-- Perfect Scrollbar -->
    <script type="text/javascript" src="../assets/node_modules/perfect-scrollbar/dist/perfect-scrollbar.min.js"></script>
    <!-- Popper.js -->
    <script type="text/javascript" src="../assets/node_modules/popper.js/dist/umd/popper.min.js"></script>
    <!-- Bootstrap -->
    <script type="text/javascript" src="../assets/node_modules/bootstrap/dist/js/bootstrap.min.js"></script>
    <!-- Data tables -->
    <script type="text/javascript" src="../assets/node_modules/datatables.net/js/jquery.dataTables.js"></script>
    <script type="text/javascript" src="../assets/node_modules/datatables-responsive/js/dataTables.responsive.js"></script>
    <!-- Bootstrap Select -->
    <script src="../assets/js/bootstrap-select.js" type="text/javascript"></script>
    <!-- Fuse Html -->
    <script type="text/javascript" src="../assets/fuse-html/fuse-html.min.js"></script>
    <!-- Main JS -->
    <script type="text/javascript" src="../assets/js/main.js"></script>
    <!-- Custom JS -->
    <script>
    function yesnoCheck(that) {
    if (that.value == "other") {
        document.getElementById("ifYes").style.display = "block";
    } else {
        document.getElementById("ifYes").style.display = "none";
    }
}
</script>
<!-- /Custom JS -->
    <!-- / JAVASCRIPT -->
</head>
<body class="layout layout-vertical layout-left-navigation layout-below-toolbar layout-below-footer">
    <main>
        <div id="wrapper">
            <aside id="aside" class="aside aside-left" data-fuse-bar="aside" data-fuse-bar-media-step="md" data-fuse-bar-position="left">
                <div class="aside-content bg-primary-700 text-auto">
                    <div class="aside-toolbar">
                        <div class="logo">
                            <span class="logo-icon icon-desktop-mac"></span>
                            <p class="logo-text texttoolbar">SYSDesk</p>
                        </div>
                        <button id="toggle-fold-aside-button" type="button" class="btn btn-icon d-none d-lg-block" data-fuse-aside-toggle-fold>
                            <i class="icon icon-backburger"></i>
                        </button>
                    </div>
                    <ul class="nav flex-column custom-scrollbar" id="sIDnav" data-children=".nav-item">
                        <li class="nav-item">
                            <a class="nav-link ripple " href="systems.php" data-url="index.html">
                                <i class="icon s-4 icon-desktop-tower"></i>
                                <span>Systems</span>
                            </a>
                        </li>
						<li class="nav-item">
                            <a class="nav-link ripple" href="tickets.php">
                                <i class="icon s-4 icon-message-bulleted"></i>
                                <span>Tickets</span>
                            </a>
                        </li>

                        <li class="nav-item" role="tab" id="heading-ecommerce">

                            <a class="nav-link ripple with-arrow collapsed" data-toggle="collapse" data-target="#collapse-ecommerce" href="#" aria-expanded="false" aria-controls="collapse-ecommerce">

                                <i class="icon s-4 icon-settings"></i>

                                <span>Settings</span>
                            </a>
                            <ul id="collapse-ecommerce" class='collapse ' role="tabpanel" aria-labelledby="heading-ecommerce" data-children=".nav-item">

                                <li class="nav-item">
                                    <a class="nav-link ripple " href="users.php" data-url="index.html">

                                        <span>Users</span>
                                    </a>
                                </li>
                                 <li class="nav-item">
                                    <a class="nav-link ripple " href="reset-password.php">

                                        <span>Reset Password</span>
                                    </a>
                                </li>
                                <li class="nav-item">
                                    <a class="nav-link ripple " href="other-settings.php" data-url="index.html">

                                        <span>Other settings</span>
                                    </a>
                                </li>
                            </ul>
                        </li>
                    </ul>
                </div>
            </aside>
            <div class="content-wrapper">
                <nav id="toolbar" class="bg-white">
                    <div class="row no-gutters align-items-center flex-nowrap">
                        <div class="col">
                            <div class="row no-gutters align-items-center flex-nowrap">
                                <button type="button" class="toggle-aside-button btn btn-icon d-block d-lg-none fuse-ripple-ready" data-fuse-bar-toggle="aside">
                                    <i class="icon icon-menu"></i>
                                </button>
                                <div class="toolbar-separator d-block d-lg-none"></div>
                            </div>
                        </div>
                        <div class="col-auto">
                            <div class="row no-gutters align-items-center justify-content-end">
							<a href="logout.php" class="logintoolbar ripple icon row align-items-center no-gutters px-2 px-sm-4" role="button" id="logintoolbar" aria-haspopup="true" aria-expanded="false">Logout</a>
                            </div>
                        </div>
                    </div>
                </nav>
					   <div class="content custom-scrollbar">
						<div class="page-layout simple full-width">
						 <div class="page-content-wrapper">
						 
						 
						  <!-- CONTENT -->
      <div class="clearfix" style="background:white; padding:20px;">
       <a href="systems.php" class="btn btn-secondary btn-fab pull-left"><i class="icon-arrow-left"></i></a>
       <h2 class="pull-right">system ID: <?php echo $sysID; ?></h2>
      </div>
     <div class="form-wrapper md-elevation-8 p-4">
     <h3>System Information</h3>
                <form action="<?php echo htmlspecialchars(basename($_SERVER['REQUEST_URI'])); ?>" method="post">
                        <div class="form-group col-md-4 col-md-4  <?php echo (!empty($sysID_err)) ? 'has-error' : ''; ?>">
                            <label>sysID</label>
                            <input type="text" name="xsysID" class="form-control" value="<?php echo $sysID; ?>">
                            <span class="help-block"><?php echo $sysID_err;?></span>
                        </div>
                        <div class="form-group col-md-4 col-md-4  <?php echo (!empty($sysType_err)) ? 'has-error' : ''; ?>">
                            <label>System Type</label>
                            <input type="text" name="System_type" class="form-control" value="<?php echo $sysType; ?>">
                            <span class="help-block"><?php echo $sysType_err;?></span>
                        </div>
                        <div class="form-group col-md-4 col-md-4  <?php echo (!empty($location_err)) ? 'has-error' : ''; ?>">
                            <label>location</label>
                            <input type="text" name="location" class="form-control"  value="<?php echo $location; ?>">
                            <span class="help-block"><?php echo $location_err;?></span>
                        </div>
                        <div class="form-group col-md-4 col-md-4  <?php echo (!empty($EthMac_err)) ? 'has-error' : ''; ?>">
                            <label>MAC Adress</label>
                            <input type="text" name="MAC_Adress" class="form-control" value="<?php echo $EthMac; ?>">
                            <span class="help-block"><?php echo $EthMac_err;?></span>
                        </div>
                        <div class="form-group col-md-4 <?php echo (!empty($Winkey_err)) ? 'has-error' : ''; ?>">
                            <label>Windows Key</label>
                            <input type="text" name="Win_Key" class="form-control" value="<?php echo $Win_Key; ?>">
                            <span class="help-block"><?php echo $Winkey_err;?></span>
                        </div>
                         <input type="hidden" name="id" value="<?php echo $id; ?>"/> 
                        <input type="submit" class="btn btn-secondary" value="Submit">
                    </form>
                    <div class="split"><div class="line split"></div></div>
                <div class="col-md12"> 
                <h3>System Meta</h3>
                    <br>
                    <form class="form-inline" method="post">
                         <label for="meta">Meta Tag:</label>
                         <input id="meta" type="text" name="typedata">
                         <label for="value">Value:</label>
                          <input id="value" type="text" name="metadata"><br>
                          <input type="submit" class="btn btn-secondary" name="submit" value="ADD">
                      </form>
                      <br>
                     </div> 
                    <div class="col-md-4">  
                    <table class="table">
                    <thead>
                      <tr>
                        <th>Meta Tag</th>
                        <th>Value</th>
                      </tr>
                      </thead>
                      <?php
                      foreach($lines as $line) {
                        echo "<tr>";
                        $elements = explode("*", $line);
                        foreach($elements as $element) {
                          echo "<td>" . $element . "</td>";
                        }
                        echo "<td><a class='crud' href='?id=". $row["id"] ."&deldata=". $line ."' title='Delete' data-toggle='tooltip'><span class='icons icon-trash'></span></a></td>";
                        echo "</tr>";
                      }
                      
                      ?>
                      </table>
                      
                    </div>
</div>
						  <!-- / CONTENT -->
						  
						  
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </main>
</body>
</html>
