<?php
session_start();

// Verifica se a variável de sessão "U" está definida
if (!isset($_SESSION["U"])) {
    // Redireciona para a página de login se o usuário não estiver autenticado
    header("Location: index.php");
    exit;
}

// Obtém o ID do usuário da sessão
$id = $_SESSION['id'];

// Conexão com o banco de dados de usuários
$db = new SQLite3("./api/db/studiolivecode_users.db");

// Faça uma consulta para obter as informações de admin e nível do usuário
$query = $db->query("SELECT admin FROM users WHERE id = $id");
$userData = $query->fetchArray(SQLITE3_ASSOC);

// Verifique se o usuário é administrador (admin = 1) ou tem o nível necessário (por exemplo, nível = 1)
if (!$userData || $userData['admin'] != 1) {
    header("Location: index.php"); // Redirecionar usuários que não têm acesso
    exit;
}

if (isset($_GET["create"])) {
    // Formulário de criação de revenda
    if ($_SERVER["REQUEST_METHOD"] === "POST") {
        $name = $_POST['name'];
        $username = $_POST['username'];
        $password = $_POST['password'];
        $mac_amount = $_POST['mac_amount'];

        // Consulta para contar o número total de usuários
        $countQuery = "SELECT COUNT(*) as count FROM users WHERE store_type = 1";
        $result = $db->querySingle($countQuery);

        if ($result < 10) {
            // Inserir o novo usuário
            $stmt = $db->prepare("INSERT INTO users (name, username, password, logo, mac_amount, store_type, nivel) VALUES (:name, :username, :password, 'img/logo.png', :mac_amount, 1, 2)");
            $stmt->bindValue(':name', $name, SQLITE3_TEXT);
            $stmt->bindValue(':username', $username, SQLITE3_TEXT);
            $stmt->bindValue(':password', $password, SQLITE3_TEXT);
            $stmt->bindValue(':mac_amount', $mac_amount, SQLITE3_INTEGER);

            if ($stmt->execute()) {
                header("Location: revendas.php?r=adicionado");
            } else {
                $mensagem = "Erro ao criar revendedor.";
            }
        } else {
            // Exibir mensagem de erro
            $mensagem = "Limite de 10 Revendas foi atingido. Não é possível criar mais Revendas.";
        }
    }
    include './includes/header.php';
?>
<?php if (!empty($mensagem)): ?>
    <div class='alert alert-danger'><b><?php echo $mensagem; ?></b></div>
<?php endif; ?>
<div class="card radius-10">
    <div class="card-body">
        <form method="post">
            <div class="form-group mb-4">
                <label class="control-label" for="name">
                    <strong>Nome</strong>
                </label>
                <input type="text" class="form-control" name="name" placeholder="Nome Revendedor" required />
            </div>
            <div class="form-group mb-4">
                <label class="control-label" for="mac_amount">
                    <strong>Limite de MACs</strong>
                </label>
                <input type="number" class="form-control" name="mac_amount" placeholder="Limite de MACs" min="1" value="1" required />
            </div>
            <div class="form-group mb-4">
                <label class="control-label" for="username">
                    <strong>Usuário</strong>
                </label>
                <input type="text" class="form-control" name="username" placeholder="Usuário" required />
            </div>
            <div class="form-group mb-4">
                <label class="control-label" for="password">
                    <strong>Senha</strong>
                </label>
                <input type="text" class="form-control" name="password" placeholder="Senha" required />
            </div>
            <button type="submit" name="submit" class="btn btn-primary mr-2">
                <i class="bx bx-check mr-1"></i> Enviar
            </button>
        </form>
    </div>
</div>
<?php
    include './includes/footer.php';
} elseif (isset($_GET['update'])) {
    // Formulário de atualização de revenda
    $user_id = $_GET['update'];
    $query = $db->query("SELECT * FROM users WHERE id = $user_id");
    $userData = $query->fetchArray();

    if ($_SERVER["REQUEST_METHOD"] === "POST") {
        $name = $_POST['name'];
        $username = $_POST['username'];
        $password = $_POST['password'];
        $mac_amount = $_POST['mac_amount'];

        $db->exec("UPDATE users SET name='$name', username='$username', password='$password', mac_amount=$mac_amount WHERE id=$user_id");

        header("Location: revendas.php?r=atualizado");
    }
    include './includes/header.php';
?>
    <div class="card radius-10">
        <div class="card-body">
            <form method="post">
                <input type="hidden" name="id" value="<?= $user_id ?>">
                <div class="form-group mb-4">
                    <label class="control-label" for="name">
                        <strong>Nome</strong>
                    </label>
                    <input type="text" class="form-control" name="name" value="<?= $userData['name'] ?>" required />
                </div>
                <div class="form-group mb-4">
                    <label class="control-label" for="mac_amount">
                        <strong>MACs</strong>
                    </label>
                    <input type="number" class="form-control" name="mac_amount" value="<?= $userData['mac_amount'] ?>" min="1" required />
                </div>
                <div class="form-group mb-4">
                    <label class="control-label" for="username">
                        <strong>Usuário</strong>
                    </label>
                    <input type="text" class="form-control" name="username" value="<?= $userData['username'] ?>" required />
                </div>
                <div class="form-group mb-4">
                    <label class="control-label" for="password">
                        <strong>Senha</strong>
                    </label>
                    <input type="text" class="form-control" name="password" value="<?= $userData['password'] ?>" required />
                </div>
                <button type="submit" name="submit" class="btn btn-primary mr-2">
                    <i class="bx bx-check mr-1"></i> Enviar
                </button>
            </form>
        </div>
    </div>
<?php
    include './includes/footer.php';
} elseif (isset($_GET['delete'])) {
    // Excluir revendedor
    $user_id = $_GET['delete'];

    // Certifique-se de tratar a entrada do usuário para evitar SQL injection
    $user_id = intval($user_id);

    // Execute a exclusão no banco de dados
    $db->exec("DELETE FROM users WHERE id = $user_id");

    header("Location: revendas.php?r=excluido");
    exit;
} else {
    // Tabela principal
    include './includes/header.php';
?>
    <div class="card radius-10">
        <div class="card-header border-bottom-0 bg-transparent">
            <div class="d-flex align-items-center">
                <div>
                    <h5 class="font-weight-bold mb-0">Revendas Cadastradas</h5>
                </div>
                <div class="ms-auto">
                    <a href="revendas.php?create">
                        <button type="button" class="btn btn-white radius-10">Adicionar Revenda</button>
                    </a>
                </div>
            </div>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table mb-0 align-middle">
                    <thead>
                        <tr>
                            <th>Nome</th>
                            <th>Usuário</th>
                            <th>MACs</th>
                            <th>MACs Disponíveis</th>
                            <th>Editar</th>
                            <th>Deletar</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        $db2 = new SQLite3("./api/db/studiolivecode_clientes.db");
                        $res = $db->query("SELECT * FROM users WHERE (admin != 1 OR admin IS NULL) AND store_type = 1");

                        while ($row = $res->fetchArray()) {
                            $id = $row["id"];
                            $name = $row["name"];
                            $username = $row["username"];
                            $macs = $row["mac_amount"];

                            // Obter a contagem de MACs usados
                            $macsUsed = $db2->query("SELECT COUNT(*) as count FROM ibo WHERE id_user = '$id' AND active = 1 AND expire_date > date('now')");
                            $macsUsed = $macsUsed->fetchArray()['count'];
                            $macsAvailable = $macs - $macsUsed;
                        ?>
                            <tr>
                                <td><?php echo $name; ?></td>
                                <td><?php echo $username; ?></td>
                                <td><?php echo $macs; ?></td>
                                <td><?php echo $macsAvailable; ?></td>
                                <td>
                                    <div class="d-flex order-actions">
                                        <a href="revendas.php?update=<?= $row['id'] ?>" class="text-light bg-primary border-0"><i class='bx bxs-edit'></i></a>
                                    </div>
                                </td>
                                <td>
                                    <div class="d-flex order-actions">
                                        <a class="text-light bg-danger border-0 btn-ok" data-bs-toggle="modal" data-bs-target="#confirm-delete-<?=$row['id']?>"><i class="bx bxs-trash"></i></a>
                                    </div>
                                    <!-- Modal -->
                                    <div class="modal fade" id="confirm-delete-<?=$row['id']?>" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
                                        <div class="modal-dialog">
                                            <div class="modal-content">
                                                <div class="modal-header">
                                                    <h5 class="modal-title" id="exampleModalLabel">Confirmar</h5>
                                                </div>
                                                <div class="modal-body">Você realmente deseja excluir?</div>
                                                <div class="modal-footer">
                                                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Não</button>
                                                    <a href="revendas.php?delete=<?=$row['id'] ?>" class="btn btn-danger btn-ok">Sim</a>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </td>
                            </tr>
                        <?php
                        }
                        ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
<?php
    include './includes/footer.php';
}
if (isset($_GET["r"])) {
    $result = $_GET["r"];
    switch ($result) {
        case "adicionado":
            echo "<script>
            const Toast = Swal.mixin({
              toast: true,
              position: 'bottom',
              showConfirmButton: false,
              timer: 2000,
            })
            Toast.fire({
              icon: 'success',
              title: 'Revendedor Adicionado com Sucesso!'
            })</script>";
            break;
        case "excluido":
            echo "<script>
            const Toast = Swal.mixin({
              toast: true,
              position: 'bottom',
              showConfirmButton: false,
              timer: 2000,
            })
            Toast.fire({
              icon: 'success',
              title: 'Revendedor Excluído com Sucesso!'
            })</script>";
            break;
        case "atualizado":
            echo "<script>
            const Toast = Swal.mixin({
              toast: true,
              position: 'bottom',
              showConfirmButton: false,
              timer: 2000,
            })
            Toast.fire({
              icon: 'success',
              title: 'Revendedor Atualizado com Sucesso!'
            })</script>";
            break;
    }
}
?>
