<?php 
include ('includes/header.php');
include ('config.php');
include ('api/config.php');


// Caminho para o banco de dados específico
$dbPath = __DIR__ . '/api/8733ac603c8e69a3cbee1ff6bc217a45/.db.db';

// Conectando ao banco de dados
$db = new SQLite3($dbPath);

// Nome da tabela
$table_name = "dns";

// Arquivo atual
$base_file = basename($_SERVER["SCRIPT_NAME"]);

// Criar a tabela se não existir
$db->exec("CREATE TABLE IF NOT EXISTS {$table_name}(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, title VARCHAR(100), url TEXT)");

// Chamada para a tabela
$res = $db->query("SELECT * FROM {$table_name}");

// Chamada para o update
@$resU = $db->query("SELECT * FROM {$table_name} WHERE id='{$_GET['update']}'");
@$rowU = $resU->fetchArray();

// Processar o formulário de atualização
if (isset($_POST['submitU'])) {
    $db->exec("UPDATE {$table_name} SET title='{$_POST['title']}', url='{$_POST['url']}' WHERE id='{$_POST['id']}'");
    $db->close();
    header("Location: {$base_file}");
}

// Processar o formulário de inserção de novo DNS
if (isset($_POST['submit'])) {
    $db->exec("INSERT INTO {$table_name}(title, url) VALUES('{$_POST['title']}', '{$_POST['url']}')");
    header("Location: {$base_file}");
}

// Processar o delete de um DNS
if (isset($_GET['delete'])) {
    $db->exec("DELETE FROM {$table_name} WHERE id={$_GET['delete']}");
    header("Location: {$base_file}");
}

// Processar a alteração do ID (Index)
if (isset($_POST['submit_id'])) {
    $current_id = $_POST['current_id'];
    $new_id = $_POST['new_id'];

    // Verificar se o novo ID já existe
    $checkQuery = $db->query("SELECT id FROM {$table_name} WHERE id = '{$new_id}'");
    if ($checkQuery->fetchArray()) {
        echo "O ID {$new_id} já existe!";
    } else {
        // Atualizar o ID
        $db->exec("UPDATE {$table_name} SET id = '{$new_id}' WHERE id = '{$current_id}'");
        header("Location: {$base_file}");
    }
}
?>

<div class="modal fade" id="confirm-delete" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content" style="background-color: black;">
            <div class="modal-header">
                <h2 style="color: white;">Confirmar</h2>
            </div>
            <div class="modal-body" style="color: white;">
                Quer realmente apagar?
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary" data-dismiss="modal">Cancelar</button>
                <a style="color: white;" class="btn btn-danger btn-ok">Apagar</a>
            </div>
        </div>
    </div>
</div>

<?php
if (isset($_GET['create'])) {
    // Formulário para criar um novo DNS
?>
<div class="container text-center text-dark mt-5">
  <div class="row">
    <div class="col-lg-4 d-block mx-auto mt-5">
      <div class="row">
        <div class="col-xl-12 col-md-12 col-md-12">
          <div class="card">
            <div class="card-body wow-bg" id="formBg">
              <h3 class="colorboard">Add DNS</h3>
              <form method="post">
                <div class="input-group mb-3"> <input type="text" class="form-control textbox-dg" name="title" placeholder="Title"> </div>
                <div class="input-group mb-4"> <input type="text" class="form-control textbox-dg" name="url" placeholder="DNS"> </div>
                <div class="row">
                  <div class="col-12"> <button type="submit" name="submit" class="btn btn-primary btn-block logn-btn">Salvar</button> </div>
                </div>
              </form>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>
<?php 
} else if (isset($_GET['update'])) {
    // Formulário para editar um DNS
?>
<div class="container text-center text-dark mt-5">
  <div class="row">
    <div class="col-lg-4 d-block mx-auto mt-5">
      <div class="row">
        <div class="col-xl-12 col-md-12 col-md-12">
          <div class="card">
            <div class="card-body wow-bg" id="formBg">
              <h3 class="colorboard">Edit DNS</h3>
              <form method="post">
                <input type="hidden" name="id" value="<?= $_GET['update'] ?>">
                <div class="input-group mb-3"> <input type="text" class="form-control textbox-dg" name="title" value="<?= $rowU['title'] ?>"> </div>
                <div class="input-group mb-4"> <input type="text" class="form-control textbox-dg" name="url" value="<?= $rowU['url'] ?>"> </div>
                <div class="row">
                  <div class="col-12"> <button type="submit" name="submitU" class="btn btn-primary btn-block logn-btn">Salvar</button> </div>
                </div>
              </form>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>
<?php
} else {
    // Tabela principal
?>
<div class="col-md-12 mx-auto">
    <center>
        <h2 class="colorboard">Manage DNS</h2>
        <a id="button" href="./<?php echo $base_file ?>?create" class="btn btn-primary">New DNS</a>
    </center>
    <br>
    <div class="table-responsive">
        <table class="table table-striped table-sm">
        <thead style="color:white!important">
            <tr>
            <th>Index</th>
            <th>Title</th>
            <th>DNS</th>
            <th>Actions</th>
            </tr>
        </thead>
        <?php while ($row = $res->fetchArray()) { ?>
        <tbody>
            <tr>
            <td>
                <!-- Formulário para alterar o ID -->
                <form method="post" action="<?php echo $base_file ?>">
                    <input type="hidden" name="current_id" value="<?= $row['id'] ?>">
                    <input type="text" name="new_id" value="<?= $row['id'] ?>" style="width: 60px;">
                    <button type="submit" name="submit_id" class="btn btn-warning btn-sm">Alterar</button>
                </form>
            </td>
            <td><?= $row['title'] ?></td>
            <td><?= $row['url'] ?></td>
            <td>
                <a class="btn btn-info btn-ok" href="<?php echo $base_file ?>?update=<?= $row['id'] ?>"><i class="fa fa-pencil-square-o"></i></a>
                &nbsp;&nbsp;&nbsp;
                <a class="btn btn-danger btn-ok" href="#" data-href="<?php echo $base_file ?>?delete=<?= $row['id'] ?>" data-toggle="modal" data-target="#confirm-delete"><i class="fa fa-trash-o"></i></a>
            </td>
            </tr>
        </tbody>
        <?php } ?>
        </table>
    </div>
</div>
<?php } ?>

<?php include ('includes/footer.php'); ?>
<? include ('config.php'); ?>
<? include ('api/config.php'); ?>
</body>
</html>
