<?php

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$db = new SQLite3('a/.eggziedb.db');
$db1 = $db;
$db->exec('CREATE TABLE IF NOT EXISTS ibo(id INTEGER PRIMARY KEY NOT NULL,mac_address VARCHAR(100),username VARCHAR(100),password VARCHAR(100),expire_date VARCHAR(100),url VARCHAR(100),title VARCHAR(100),created_at VARCHAR(100))');
$res = $db->query('SELECT * FROM ibo');

if(isset($_GET['index'])) {
    $index = $_GET['index'];

} else {

    $index = ""; // Default value

}

if(isset($_GET['update'])) {
    $user_id = $_GET['update'];
    $res1 = $db->query("SELECT * FROM ibo WHERE id = '$user_id'");
    while ($row1 = $res1->fetchArray()) {
                                  
        $user_id = $row1['id'];
        $username = $row1['username'];
        $password = $row1['password'];
        $expire_date = $row1['expire_date'];
        $mac_address_old = $row1['mac_address'];
        $dns = $row1['url'];
        $extra = $row1['extra'];
        $title = $row1['title'];
        
    }
} else {
    echo "<script>alert('Selecione o usuario a ser editado!');</script>";
    header('Location: users.php');
}

include 'includes/header.php';

if (isset($_POST['submit'])) {
    
            $usuario =  $_POST['username'];
            $mac_adress = strtoupper($_POST['mac_address']);
            $result = $db1->query("SELECT COUNT(*) as count FROM ibo WHERE mac_address = '$mac_adress' AND mac_address <> '$mac_address_old'");
            $row = $result->fetchArray(SQLITE3_ASSOC);
            $count = $row['count'];
        
            if($count || $usuario == "ADM") {
              echo "<script>alert('Já existe um usuario registrado com esse usuario que você esta tentando, por favor escolha outro!');window.location.href='users.php';</script>";
            } else {
    
    	$we = strtotime($_POST['expire_date']);
    	$ne = date('Y-m-d', $we);
    	$start = date('Y-m-d');
    	$end = date('h:m:s');
    	$full = $start . 'T' . $end . '.000000Z';
    	$mac_adress = strtoupper($_POST['mac_address']);
    	$username = $_POST['username'];
    	$password = $_POST['password'];
    	$dns = $_POST['url'];
    	$title = $_POST['title'];
    	$id = $_POST['id'];
    	$descricao = $_POST['Descricao'];
    	$db1->exec("UPDATE ibo SET mac_address = '$mac_adress', username = '$username', password = '$password', expire_date = '$ne', url = '$dns', title = '$title', extra = '$descricao' WHERE id = '$id'");
    
    	$db1->close();
        echo "<script>window.location.href='users.php';</script>";
        
            }
        
}


?>
<script>
document.addEventListener("DOMContentLoaded", function() {
    var macAddressInput = document.getElementById("mac_address");

    macAddressInput.addEventListener("input", function(e) {
        var value = e.target.value;
        value = value.replace(/[^a-fA-F0-9]/g, "").toUpperCase();

        var formattedValue = "";
        for (var i = 0; i < value.length; i++) {
            formattedValue += value[i];
            if ((i + 1) % 2 === 0 && i < value.length - 1) {
                formattedValue += ":";
            }
        }

        e.target.value = formattedValue;
    });
});
</script>
<script>
function extract(event) {
  event.preventDefault(); // Prevent page refresh

  var m3uLink = document.getElementById("m3u_address").value;

  // Extract server URL
  var serverUrl = m3uLink.split("/get.php")[0];
  document.getElementById("server_url").value = serverUrl;

  // Extract username
  var username = getParameterByName("username", m3uLink);
  document.getElementById("username").value = username;

  // Extract password
  var password = getParameterByName("password", m3uLink);
  document.getElementById("password").value = password;
}

function getParameterByName(name, url) {
  name = name.replace(/[\[\]]/g, "\\$&");
  var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
      results = regex.exec(url);
  if (!results) return "";
  if (!results[2]) return "";
  return decodeURIComponent(results[2].replace(/\+/g, " "));
}


</script>
        <div class="container-fluid">
          <h1 class="h3 mb-1 text-gray-800"> Atualizar Usuário</h1>
                <div class="card border-left-primary shadow h-100 card shadow mb-4">
                <div class="card-header py-3">
                <h6 class="m-0 font-weight-bold text-primary3"><i class="fas fa-user"></i> Editar Usuário</h6>
                </div>
                <div class="card-body">
                        <form method="post">          
                        <div class="form-group ">
                                    <label class="control-label " for="mac_address">
                                        <strong>Mac Address</strong> 
                                    </label>
                                    <div class="input-group">
                                        <input type="form-control text-primary" name="id" value="<?php echo $user_id; ?>" type="hidden" readonly>
                                        <input class="form-control text-primary" id="description" name="mac_address" value="<?php echo $mac_address_old;?>" type="text"required/>
                                    </div>
                                </div>
                                <div class="form-group ">
                                    <label class="control-label " for="username">
                                        <strong>Username</strong>
                                    </label>
                                    <div class="input-group">
                                        <input type="text" class="form-control text-primary" name="username" value="<?php echo $username;?>" id="discription" required/>
                                    </div>
                                </div>
                                <div class="form-group ">
                                    <label class="control-label " for="password">
                                        <strong>Password</strong>
                                    </label>
                                    <div class="input-group">
                                        <input type="text" class="form-control text-primary" name="password" value="<?php echo $password;?>"" id="discription" required/>
                                    </div>
                                </div>
                                <div class="form-group ">
                                    <label class="control-label " for="expire_date">
                                        <strong>Expiration</strong>
                                    </label>
                                    <div class="input-group">
                                        <input type="text" class="form-control text-primary" name="expire_date" value="<?php echo $expire_date;?>" id="datepicker" /> 
                                    </div>

                                </div>
                                <div class="form-group ">
                                    <label class="control-label " for="dns">
                                        <strong>DNS</strong>
                                    </label>
                                    <div class="input-group">
                                        <input type="text" class="form-control text-primary" name="url" value="<?php echo $dns;?>" id="discription" required/>
                                    </div>
                                </div>
                                  <div class="form-group ">
                                    <label class="control-label " for="dns">
                                        <strong>Descricao</strong>
                                    </label>
                                    <div class="input-group">
                                        <input type="text" class="form-control text-primary" name="Descricao" value="<?php echo $extra;?>" id="Descricao" required/>
                                    </div>
                                </div>
                                <div class="form-group ">
                                    <label class="control-label " for="title">
                                        <strong>Server Name</strong>
                                    </label>
                                    <div class="input-group">
                                        <input type="text" class="form-control text-primary" name="title" value="<?php echo $title;?>" id="discription" required/>
                                    </div>

                                </div>
                                <div class="form-group">
                                    <div>
                                        <button class="btn btn-success btn-icon-split" name="submit" type="submit">
                        <span class="icon text-white-50"><i class="fas fa-check"></i></span><span class="text">Submit</span>
                        </button>
                                    </div>

                                </div>
                            </form>
                        </div>
                    </div>

<br><br><br>
</div>
<script>
$('#confirm-delete').on('show.bs.modal', function(e) {
    $(this).find('.btn-ok').attr('href', $(e.relatedTarget).data('href'));
});
</script>



<?php 
include 'includes/footer.php';
?>

</html>