<?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
$db = new SQLite3("./api/.ansdb.db");
$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
)");

// Função para redirecionar após uma operação
function redirect($location) {
    header("Location: $location");
    exit();
}

// Exclusão de usuários
if (isset($_GET["delete"])) {
    $db->exec("DELETE FROM ibo WHERE id=" . $_GET["delete"]);
    redirect("all_users.php");
}

// Exclusão de todos os usuários
if (isset($_GET["delete_all"])) {
    $db->exec("DELETE FROM ibo");
    redirect("all_users.php");
}

// Inclusão do cabeçalho
include "includes/header.php";

// Link do Font Awesome
echo '<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">';

// Modal para confirmação de exclusão
function renderDeleteModal($id, $message) {
    return "
    <div class=\"modal fade\" id=\"$id\" tabindex=\"-1\" role=\"dialog\" aria-labelledby=\"myModalLabel\" aria-hidden=\"true\">
        <div class=\"modal-dialog\">
            <div class=\"modal-content\">
                <div class=\"modal-header\">
                    <h2>ATENÇÃO</h2>
                </div>
                <div class=\"modal-body\">
                    $message
                </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>";
}

echo renderDeleteModal("confirm-delete", "DESEJA REALMENTE EXCLUIR ESTE USUÁRIO?");
echo renderDeleteModal("confirm-delete-all", "DESEJA REALMENTE EXCLUIR TODOS OS USUÁRIOS?");

// Conteúdo principal
echo "<main role=\"main\" class=\"col-15 pt-4 px-5\">
    <div class=\"row justify-text-center\">
        <h2>Todos os usuários</h2>
        <div class=\"input-group\">
            <a button class=\"btn btn-success btn-icon-split\" id=\"button\" href=\"./users_create.php\">
                <span class=\"icon text-white-50\"><i class=\"fas fa-check\"></i></span>
                <span class=\"text\">NOVO</span>
            </a>
            <a class=\"btn btn-danger btn-icon-split\" href=\"#\" data-toggle=\"modal\" data-target=\"#confirm-delete-all\">
                <span class=\"text\">EXCLUIR TODOS</span>
            </a>
            <div class=\"input-group-prepend\">
            </div>
            <input class=\"form-control\" type=\"text\" id=\"search\" placeholder=\"Pesquisar\" name=\"search_value\"/>
        </div>
    </div>
    <div class=\"table-responsive mt-4\">
        <table id=\"myTable\" class=\"table table-striped table-sm\" style=\"border-radius: 10px; overflow: hidden; border: 2px solid #007bff;\">
            <thead class=\"text-primary bg-light\">
                <tr>
                    <th>Cliente</th>
                    <th>Status</th>
                    <th>MAC</th>
                    <th>Usuário</th>
                    <th>Vencimento</th>
                    <th>DNS</th>
                    <th>ID</th>
                    <th>Editar</th>
                    <th>Excluir</th>
                </tr>
            </thead>
            <tbody class=\"text-primary\">";

$res = $db->query("SELECT * FROM ibo");
$today = date('Y-m-d');

while ($row = $res->fetchArray()) {
    $iid = $row["id"];
    $imac = $row["mac_address"];
    $iexpire_date = $row["expire_date"];
    $iusername = $row["username"];
    $idns = $row["dns"] ?: $row["url"];
    $ititle = $row["title"];
    $statusClass = '';
    $statusText = '';
    $status_icon = '';

    // Determinar o status baseado na data de expiração
    if ($iexpire_date < $today) {
        $statusClass = 'text-danger'; // Inativo
        $status_icon = "<i class='fas fa-times-circle' style='color:red; font-size:24px;'></i>";
    } elseif ($iexpire_date >= $today) {
        $exp_date = date('Y-m-d', strtotime('+3 days'));
        if ($iexpire_date <= $exp_date) {
            $statusClass = 'text-warning'; // Expirando
            $status_icon = "<i class='fas fa-exclamation-circle' style='color:orange; font-size:24px;'></i>";
        } else {
            $statusClass = 'text-success'; // Ativo
            $status_icon = "<i class='fas fa-check-circle' style='color:green; font-size:24px;'></i>";
        }
    }

    // Renderizar a linha da tabela
    echo "
        <tr>
            <td>{$ititle}</td>
            <td class=\"{$statusClass}\">{$status_icon}</td>
            <td>{$imac}</td>
            <td>{$iusername}</td>
            <td>{$iexpire_date}</td>
            <td>{$idns}</td>
            <td>{$iid}</td>
            <td>
                <a class=\"btn btn-icon\" href=\"./users_update.php?update={$iid}\">
                    <span class=\"icon text-white-50\"><i class=\"fa fa-pencil\" style=\"font-size:24px;color:blue\"></i></span>
                </a>
            </td>
            <td>
                <a class=\"btn btn-icon\" href=\"#\" data-href=\"./all_users.php?delete={$iid}\" data-toggle=\"modal\" data-target=\"#confirm-delete\">
                    <span class=\"icon text-white-50\"><i class=\"fa fa-trash\" style=\"font-size:24px;color:red\"></i></span>
                </a>
            </td>
        </tr>";
}

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

include "includes/footer.php";
?>

<script>
    $("#search").keyup(function () {
        var value = this.value.toLowerCase().trim();
        $("#myTable tr").each(function (index) {
            if (!index) return; // Ignorar cabeçalho
            var found = $(this).text().toLowerCase().indexOf(value) > -1;
            $(this).toggle(found);
        });
    });

    $("#confirm-delete-all .btn-ok").click(function () {
        window.location.href = './all_users.php?delete_all=true';
    });

    $("#confirm-delete .btn-ok").click(function () {
        window.location.href = './all_users.php?delete=' + $(this).data('href');
    });
</script>
</body>
</html>