<?php
session_start();

// Verificar se o usuário está autenticado e é um administrador
if (!isset($_SESSION['id']) || !$_SESSION['admin']) {
    header("Location: login.php");
    exit();
}

// Configurações de erro
ini_set("display_errors", 0);
ini_set("display_startup_errors", 0);
error_reporting(32767);

// Conexão com o banco de dados SQLite
$db = new SQLite3("./api/.ansdb.db");

// Criar a tabela 'ibo' se não existir
$db->exec("CREATE TABLE IF NOT EXISTS ibo(
    id INTEGER PRIMARY KEY NOT NULL,
    mac_address VARCHAR(100),
    key VARCHAR(100),
    username VARCHAR(100),
    password VARCHAR(100),
    expire_date VARCHAR(100),
    dns VARCHAR(100),
    epg_url VARCHAR(100),
    title VARCHAR(100),
    url VARCHAR(100),
    type VARCHAR(100),
    id_user INT,
    ip_endereco VARCHAR(100),
    phone_number VARCHAR(15)
)");

// Criar a tabela 'deleted_macs' para armazenar os MACs excluídos
$db->exec("CREATE TABLE IF NOT EXISTS deleted_macs(
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    mac_address VARCHAR(100) NOT NULL UNIQUE,
    delete_date DATETIME DEFAULT CURRENT_TIMESTAMP
)");

// Exclui um usuário da tabela se 'delete' estiver no URL
if (isset($_GET["delete"])) {
    // Obter o MAC do usuário antes de excluir
    $stmt = $db->prepare("SELECT mac_address FROM ibo WHERE id = :id");
    $stmt->bindValue(':id', $_GET["delete"], SQLITE3_INTEGER);
    $result = $stmt->execute();
    $row = $result->fetchArray();

    if ($row) {
        $mac_address = $row["mac_address"];

        // Inserir o MAC excluído na tabela 'deleted_macs'
        $insertStmt = $db->prepare("INSERT OR IGNORE INTO deleted_macs (mac_address) VALUES (:mac_address)");
        $insertStmt->bindValue(':mac_address', $mac_address, SQLITE3_TEXT);
        $insertStmt->execute();
    }

    // Excluir o usuário da tabela 'ibo'
    $db->exec("DELETE FROM ibo WHERE id = " . $_GET["delete"]);
    $db->close();

    header("Location: all_users.php");
}

// Incluir o cabeçalho da página
include "includes/header.php";

// Modal de confirmação de exclusão
echo "<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\">
            <div class=\"modal-header\">
                <h2>Confirmar Exclusão</h2>
            </div>
            <div class=\"modal-body\">
                Você realmente deseja excluir este usuário?
            </div>
            <div class=\"modal-footer\">
                <button type=\"button\" class=\"btn btn-default\" data-dismiss=\"modal\">Cancelar</button>
                <a class=\"btn btn-danger btn-ok\">Excluir</a>
            </div>
        </div>
    </div>
</div>";

// Exibir a lista de usuários
echo "<main role=\"main\" class=\"col-15 pt-4 px-5\">
      <h2>Todos os Usuários</h2>
      <div class=\"input-group\">
          <a class=\"btn btn-success btn-icon-split\" href=\"./users_create.php\">
              <span class=\"icon text-white-50\"><i class=\"fas fa-check\"></i></span>
              <span class=\"text\">Criar Novo</span>
          </a>
          <div class='form-check'>
              <input class='form-check-input' type='checkbox' id='expired'>
              <label class='form-check-label' for='expired'>Expirados</label>
          </div>
          <div class=\"input-group-prepend\">
              <span class=\"input-group-text\" style=\"font-size:24px;color:#1cc88a\"><i class=\"fas fa-search\"></i></span>
          </div>
          <input class=\"form-control\" type=\"text\" id=\"search\" placeholder=\"Buscar ...\" name=\"search_value\"/>
      </div>
      <div class=\"table-responsive\">
        <table id=\"myTable\" class=\"table table-striped table-sm\">
          <thead class=\"text-primary\">
            <tr>
              <th>ID</th>
              <th>Mac</th>
              <th>Vencimento</th>
              <th>Dns</th>
              <th>Nome</th>
              <th>Expirado?</th>
              <th>Editar</th>
              <th>Apagar</th>
            </tr>
          </thead>
          <tbody class=\"text-primary\">";

$res = $db->query("SELECT * FROM ibo");
while ($row = $res->fetchArray()) {
    $iid = $row["id"];
    $imac = $row["mac_address"];
    $iexpire_date = $row["expire_date"];
    $idns = $row["dns"] ? $row["dns"] : $row["url"];
    $ititle = $row["title"];
    $ip_endereco = $row["ip_endereco"];
    $phone_number = isset($row["phone_number"]) ? $row["phone_number"] : '';
    $today = date('Y-m-d');
    $active = $row['active'] && $iexpire_date >= $today;
    $expired = $active ? "Não" : "Sim";

    echo "<tr>
            <td>$iid</td>
            <td>$imac</td>
            <td>$iexpire_date</td>
            <td>$idns</td>
            <td>$ititle</td>
         
            <td class='expired_td'>$expired</td>
            <td><a class=\"btn btn-icon\" href=\"./users_update.php?update=$iid\">
              <i class=\"fa fa-pencil\" style=\"font-size:24px;color:blue\"></i></a>
            </td>
            <td><a class=\"btn btn-icon\" href=\"#\" data-href=\"./all_users.php?delete=$iid\" data-toggle=\"modal\" data-target=\"#confirm-delete\">
              <i class=\"fa fa-trash\" style=\"font-size:24px;color:red\"></i></a>
            </td>
          </tr>";
}

echo "</tbody></table></div></main>";

include "includes/footer.php";
?>

<script>
$("#search").keyup(function () {
    var value = this.value.toLowerCase().trim();
    $("#expired").prop('checked', false);
    $("table tr").each(function (index) {
        if (!index) return;
        $(this).find("td").each(function () {
            var id = $(this).text().toLowerCase().trim();
            var not_found = (id.indexOf(value) == -1);
            $(this).closest('tr').toggle(!not_found);
            return not_found;
        });
    });
});

$("#expired").change(function(){
    var value = this.checked ? "Sim" : "Não";
    $("table tr").each(function (index) {
        if (!index) return;
        $(this).find("td.expired_td").each(function () {
            var expired = $(this).text().toLowerCase().trim();
            var found = expired == value.toLowerCase();
            $(this).closest('tr').toggle(found);
            return found;
        });
    });
});

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