<?php

ini_set("display_errors", 0);
ini_set("display_startup_errors", 0);
session_start();

$id_store = $_SESSION['id'];

if ($_SESSION['store_type'] == 2) {
    header("Location: users_mac.php");
}

error_reporting(32767);

// Conexão com o banco de dados principal
$db = new SQLite3("./api/.ansdb.db");
$db->exec("CREATE TABLE IF NOT EXISTS ibo(
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    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 INTEGER,
    store_type INTEGER DEFAULT 1,
    active INTEGER,
    last_submit DATETIME DEFAULT CURRENT_TIMESTAMP,
    isAdmin INTEGER DEFAULT 0,
    FOREIGN KEY (id_user) REFERENCES USERS(id) ON DELETE CASCADE
)");

if (isset($_GET["delete"])) {
    $db->exec("DELETE FROM ibo WHERE id=" . $_GET["delete"]);
    $db->close();
    header("Location: users.php");
}

// Incluir o link do Font Awesome aqui
echo '<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">';
include "includes/header.php";

// Conexão com o banco de dados de usuários
$dbUsers = new SQLite3("./api/.anspanel.db");
$res = $dbUsers->query("SELECT mac_amount FROM USERS WHERE id = '$id_store'");
$macCount = $res->fetchArray()['mac_amount'];
$dbUsers->close();

// Contando usuários ativos
$res = $db->query("SELECT COUNT(*) as count FROM ibo WHERE id_user = '$id_store' AND active = 1 AND expire_date > date('now')");
$count = $res->fetchArray()['count'];

$available = $macCount - $count;

if (!$_SESSION["admin"] = $isAdmin) {
    echo "<div class='alert alert-warning'><b>VOCÊ PODE REGISTRAR MAIS, $available MAC [LIMITE DE $macCount]</b></div>";
}

// Modal de confirmação de exclusão
echo <<<HTML
<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>ATENÇÃO</h2>
            </div>
            <div class="modal-body">
                DESEJA REALMENTE 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>
<main role="main" class="col-15 pt-4 px-5">
    <div class="row justify-text-center">
        <h2>MEUS 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>
            &nbsp;&nbsp;&nbsp;&nbsp;
            <input class="form-control" type="text" id="search" placeholder="Pesquisar" name="search_value"/>
        </div>
    </div>
    
    <div style="margin-top: 20px;"></div>

    <div class="table-responsive">
        <table id="myTable" class="table table-striped" style="border-radius: 10px; overflow: hidden; border: 2px solid #007bff;">
            <thead class="text-primary bg-light">
                <tr>
                    <th>Status</th>
                    <th>Cliente</th>
                    <th>Usuário</th>
                    <th>MAC</th>
                    <th>DNS</th>
                    <th>Senha</th> <!-- Mantendo a coluna de Senha -->
                    <th>Editar</th>
                    <th>Excluir</th>
                </tr>
            </thead>
            <tbody class="text-primary">
HTML;

$res = $db->query("SELECT * FROM ibo WHERE id_user = " . $_SESSION['id']);
while ($row = $res->fetchArray()) {
    $iid = $row["id"];
    $imac = $row["mac_address"];
    $iexpire_date = $row["expire_date"];
    $idns = $row["dns"];
    $password = $row["password"]; // Obtendo a senha

    // Determinando o status
    $statusClass = '';
    $statusText = '';
    $expireDate = new DateTime($iexpire_date);
    $now = new DateTime();
    $interval = $expireDate->diff($now);

    if ($expireDate > $now) {
        if ($interval->days <= 3) {
            $statusClass = 'text-warning'; // Amarelo
            $statusText = 'Expirando';
        } else {
            $statusClass = 'text-success'; // Verde
            $statusText = 'Ativo';
        }
    } else {
        $statusClass = 'text-danger'; // Vermelho
        $statusText = 'Inativo';
    }

    echo "<tr>
        <td class=\"" . $statusClass . "\">" . $statusText . "</td>
        <td>" . $row["title"] . "</td>
        <td>" . $row["username"] . "</td>
        <td>" . $imac . "</td>
        <td>" . $idns . "</td>
        <td>" . $password . "</td> <!-- Exibindo apenas a senha -->
        <td><a class=\"btn btn-icon\" href=\"./users_update.php?update=" . $iid . "\"><span class=\"icon text-white-50\"><i class=\"fas fa-pencil-alt\" style=\"font-size:24px;color:blue !important\"></i></span></a></td>
        <td><a class=\"btn btn-icon\" href=\"#\" data-href=\"./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 <<<HTML
            </tbody>
            </table>
        </div>
    </div>
</main>
<br><br><br>
HTML;

include "includes/footer.php";

echo <<<SCRIPT
<script>
$("#search").keyup(function () {
    var value = this.value.toLowerCase().trim();
    $("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;
        });
    });
});
</script>
<script>
$('#confirm-delete').on('show.bs.modal', function(e) {
    $(this).find('.btn-ok').attr('href', $(e.relatedTarget).data('href'));
});
</script>
</body>
</html>
SCRIPT;
?>