<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$results_per_page = 10;

if (isset($_GET['view'])) {
    $page = $_GET['view'];
} else {
    $page = 1;
}

$start_from = ($page - 1) * $results_per_page;
$db1 = new SQLite3('a/.eggziedb.db');

// Contadores para o Dashboard
$total_clients_query = $db1->query("SELECT COUNT(id) AS total FROM ibo");
$total_clients = $total_clients_query->fetchArray()['total'];

// Obter tema atual
$setting_json = file_get_contents('./a/rtx/Setting.json');
$settings = json_decode($setting_json, true);
$current_theme = "Padrão";
foreach($settings as $set) {
    if($set['RTXSetting'] == 'mLayout') {
        $current_theme = $set['PanalData'];
        break;
    }
}

// Contar temas disponíveis
$themes_count = count(glob('./rtx/layout/*.json'));

// Search functionality
$searchTerm = isset($_GET['search']) ? $_GET['search'] : '';
$searchQuery = '';
if (!empty($searchTerm)) {
    $searchQuery = "WHERE mac_address LIKE '%$searchTerm%' OR title LIKE '%$searchTerm%'";
}

$result = $db1->query("SELECT COUNT(id) AS total FROM ibo $searchQuery");
$rownew = $result->fetchArray();
$totaleview = $rownew['total'];
$total_pages = ceil($rownew['total'] / $results_per_page);
$res1 = $db1->query("SELECT * FROM ibo $searchQuery ORDER BY id DESC LIMIT $start_from, $results_per_page");

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

include 'includes/header.php';
?>

<div class="container-fluid">
    <!-- Dashboard Header -->
    <div class="d-sm-flex align-items-center justify-content-between mb-4">
        <h1 class="h3 mb-0 text-gray-800">Dashboard</h1>
        <div>
            <a href="./dns_migration.php" class="d-none d-sm-inline-block btn btn-sm btn-warning shadow-sm mr-2">
                <i class="fas fa-exchange-alt fa-sm text-white-50"></i> Migrar DNS em Massa
            </a>
            <a href="./users_create.php" class="d-none d-sm-inline-block btn btn-sm btn-primary shadow-sm">
                <i class="fas fa-plus fa-sm text-white-50"></i> Novo Cliente
            </a>
        </div>
    </div>

    <!-- Contadores -->
    <div class="row">
        <!-- Total Clientes -->
        <div class="col-xl-4 col-md-6 mb-4">
            <div class="card border-left-primary shadow h-100 py-2 dash-card">
                <div class="card-body">
                    <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">Total de Clientes</div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo $total_clients; ?></div>
                        </div>
                        <div class="col-auto">
                            <div class="icon-box bg-celeste-light">
                                <i class="fas fa-users"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Tema Atual -->
        <div class="col-xl-4 col-md-6 mb-4">
            <div class="card border-left-info shadow h-100 py-2 dash-card" style="border-left: .25rem solid var(--azul-escuro) !important;">
                <div class="card-body">
                    <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-info text-uppercase mb-1" style="color: var(--azul-escuro) !important;">Tema Ativo</div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo strtoupper(str_replace('_', ' ', $current_theme)); ?></div>
                        </div>
                        <div class="col-auto">
                            <div class="icon-box bg-escuro-light">
                                <i class="fas fa-palette"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Total Temas -->
        <div class="col-xl-4 col-md-6 mb-4">
            <div class="card border-left-warning shadow h-100 py-2 dash-card">
                <div class="card-body">
                    <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-warning text-uppercase mb-1">Temas Disponíveis</div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo $themes_count; ?></div>
                        </div>
                        <div class="col-auto">
                            <div class="icon-box" style="background-color: rgba(246, 194, 62, 0.1); color: #f6c23e;">
                                <i class="fas fa-layer-group"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Tabela de Clientes -->
    <div class="card shadow mb-4">
        <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
            <h6 class="m-0 font-weight-bold text-primary"><i class="fas fa-list"></i> Lista de Clientes</h6>
            <form method="get" class="form-inline">
                <div class="input-group input-group-sm">
                    <input type="text" name="search" class="form-control bg-light border-0 small" placeholder="Buscar MAC ou Título..." value="<?php echo $searchTerm; ?>">
                    <div class="input-group-append">
                        <button class="btn btn-primary" type="submit">
                            <i class="fas fa-search fa-sm"></i>
                        </button>
                    </div>
                </div>
            </form>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-hover" id="dataTable" width="100%" cellspacing="0">
                    <thead>
                        <tr>
                            <th>Título</th>
                            <th>Endereço MAC</th>
                            <th>Usuário</th>
                            <th>Expiração</th>
                            <th>DNS</th>
                            <th class="text-center">Ações</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php while ($row1 = $res1->fetchArray()) { 
                            $users_id = $row1['id'];
                        ?>
                            <tr>
                                <td class="font-weight-bold"><?php echo $row1['title']; ?></td>
                                <td><code class="text-primary"><?php echo $row1['mac_address']; ?></code></td>
                                <td><?php echo $row1['username']; ?></td>
                                <td><span class="badge badge-light"><?php echo $row1['expire_date']; ?></span></td>
                                <td class="small"><?php echo $row1['url']; ?></td>
                                <td class="text-center">
                                    <a href="./users_update.php?update=<?php echo $users_id; ?>" class="btn btn-sm btn-info btn-circle shadow-sm" title="Editar">
                                        <i class="fas fa-edit"></i>
                                    </a>
                                    <a href="#" data-href="./users.php?delete=<?php echo $users_id; ?>" data-toggle="modal" data-target="#confirm-delete" class="btn btn-sm btn-danger btn-circle shadow-sm" title="Excluir">
                                        <i class="fas fa-trash"></i>
                                    </a>
                                </td>
                            </tr>
                        <?php } ?>
                    </tbody>
                </table>
            </div>
            
            <!-- Paginação -->
            <?php if ($total_pages > 1) { ?>
                <nav aria-label="Navegação de página">
                    <ul class="pagination pagination-sm justify-content-center mt-4">
                        <li class="page-item <?php echo ($page <= 1) ? 'disabled' : ''; ?>">
                            <a class="page-link" href="users.php?view=<?php echo ($page - 1); ?>&search=<?php echo $searchTerm; ?>">Anterior</a>
                        </li>
                        <?php for ($i = 1; $i <= $total_pages; $i++) { ?>
                            <li class="page-item <?php echo ($i == $page) ? 'active' : ''; ?>">
                                <a class="page-link" href="users.php?view=<?php echo $i; ?>&search=<?php echo $searchTerm; ?>"><?php echo $i; ?></a>
                            </li>
                        <?php } ?>
                        <li class="page-item <?php echo ($page >= $total_pages) ? 'disabled' : ''; ?>">
                            <a class="page-link" href="users.php?view=<?php echo ($page + 1); ?>&search=<?php echo $searchTerm; ?>">Próximo</a>
                        </li>
                    </ul>
                </nav>
            <?php } ?>
        </div>
    </div>
</div>

<!-- Modal de Confirmação -->
<div class="modal fade" id="confirm-delete" tabindex="-1" role="dialog" aria-labelledby="deleteModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content border-0 shadow">
            <div class="modal-header bg-danger text-white">
                <h5 class="modal-title" id="deleteModalLabel">Confirmar Exclusão</h5>
                <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body text-center py-4">
                <i class="fas fa-exclamation-triangle text-danger fa-3x mb-3"></i>
                <p>Tem certeza que deseja excluir este cliente? Esta ação não pode ser desfeita.</p>
            </div>
            <div class="modal-footer bg-light">
                <button type="button" class="btn btn-secondary btn-sm" data-dismiss="modal">Cancelar</button>
                <a class="btn btn-danger btn-sm btn-ok">Sim, Excluir</a>
            </div>
        </div>
    </div>
</div>

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