<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$results_per_page = 5;
include '../includes/header2.php';

error_reporting(0);
if (isset($_GET['view'])) {
    $page = $_GET['view'];
} else {
    if($_SESSION['aviso_seller'] == 0) {    
        $page = 1;
        $file_path = '../a/revenda_mensagem.json';
        $file_content = file_get_contents($file_path);
        $data_array = json_decode($file_content, true);
        $titulo = $data_array['title'];
        $mensagem = $data_array['content'];
        $_SESSION['aviso_seller'] = 1;
    } 
}

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

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

$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 ASC LIMIT $start_from, $results_per_page");

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

<style>
/* === DESIGN FUTURISTA PARA INDEX.PHP === */
:root {
    --primary: #FF6B9D;
    --primary-dark: #D94A7E;
    --secondary: #00D4FF;
    --accent: #FFD166;
    --surface: #0A0F1C;
    --surface-light: #1A1F2C;
    --surface-lighter: #2A2F3C;
    --text-primary: #FFFFFF;
    --text-secondary: #B0B7C3;
    --text-muted: #6B7280;
    --border: rgba(255,255,255,0.1);
    --glow: 0 0 20px rgba(255, 107, 157, 0.3);
    --glow-blue: 0 0 20px rgba(0, 212, 255, 0.3);
}

.main-content {
    background: transparent !important;
    padding: 20px;
    min-height: calc(100vh - 80px);
}

.futuristic-card {
    background: var(--surface-light) !important;
    border: 1px solid var(--border);
    border-radius: 20px;
    backdrop-filter: blur(20px);
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
    overflow: hidden;
    position: relative;
}

.futuristic-card::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 2px;
    background: linear-gradient(90deg, var(--primary), var(--accent));
}

.card-header-futuristic {
    background: linear-gradient(135deg, var(--surface-light), var(--surface-lighter)) !important;
    border-bottom: 1px solid var(--border);
    padding: 20px 25px;
    position: relative;
}

.card-header-futuristic h6 {
    color: var(--text-primary);
    font-weight: 600;
    font-size: 1.1rem;
    display: flex;
    align-items: center;
    gap: 12px;
    margin: 0;
}

.card-header-futuristic h6 i {
    background: linear-gradient(135deg, var(--primary), var(--accent));
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    background-clip: text;
}

.card-body-futuristic {
    padding: 25px;
    background: transparent !important;
}

/* === FORMULÁRIOS FUTURISTAS === */
.futuristic-input {
    background: var(--surface-lighter) !important;
    border: 1px solid var(--border) !important;
    border-radius: 12px !important;
    color: var(--text-primary) !important;
    padding: 12px 16px !important;
    transition: all 0.3s ease;
}

.futuristic-input:focus {
    border-color: var(--primary) !important;
    box-shadow: var(--glow) !important;
    background: var(--surface-light) !important;
}

.futuristic-input::placeholder {
    color: var(--text-muted) !important;
}

.futuristic-btn {
    background: linear-gradient(135deg, var(--primary), var(--primary-dark)) !important;
    border: none !important;
    border-radius: 12px !important;
    padding: 12px 24px !important;
    color: white !important;
    font-weight: 600;
    transition: all 0.3s ease;
    box-shadow: var(--glow);
}

.futuristic-btn:hover {
    transform: translateY(-2px);
    box-shadow: 0 0 30px rgba(255, 107, 157, 0.5);
    color: white !important;
}

.futuristic-btn-secondary {
    background: linear-gradient(135deg, var(--secondary), #0099CC) !important;
    box-shadow: var(--glow-blue);
}

.futuristic-btn-secondary:hover {
    box-shadow: 0 0 30px rgba(0, 212, 255, 0.5);
}

/* === TABELA FUTURISTA === */
.futuristic-table {
    background: var(--surface-lighter) !important;
    border-radius: 16px;
    overflow: hidden;
    border: 1px solid var(--border);
    margin-top: 20px;
}

.futuristic-table thead {
    background: linear-gradient(135deg, var(--surface-light), var(--surface-lighter)) !important;
    border-bottom: 2px solid var(--border);
}

.futuristic-table th {
    color: var(--text-primary) !important;
    font-weight: 600;
    padding: 16px 12px !important;
    border: none !important;
    font-size: 0.9rem;
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

.futuristic-table td {
    color: var(--text-secondary) !important;
    padding: 14px 12px !important;
    border-bottom: 1px solid var(--border) !important;
    vertical-align: middle;
    background: transparent !important;
}

.futuristic-table tbody tr {
    transition: all 0.3s ease;
    background: transparent !important;
}

.futuristic-table tbody tr:hover {
    background: rgba(255, 107, 157, 0.05) !important;
    transform: translateX(4px);
}

.futuristic-table tbody tr:hover td {
    color: var(--text-primary) !important;
}

/* === BOTÕES DE AÇÃO === */
.btn-action {
    border: none;
    border-radius: 10px;
    padding: 8px 12px;
    transition: all 0.3s ease;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    text-decoration: none;
}

.btn-edit {
    background: rgba(0, 212, 255, 0.1);
    border: 1px solid var(--secondary);
    color: var(--secondary);
}

.btn-edit:hover {
    background: var(--secondary);
    color: white;
    transform: scale(1.05);
    box-shadow: 0 0 15px rgba(0, 212, 255, 0.4);
}

.btn-delete {
    background: rgba(255, 107, 157, 0.1);
    border: 1px solid var(--primary);
    color: var(--primary);
}

.btn-delete:hover {
    background: var(--primary);
    color: white;
    transform: scale(1.05);
    box-shadow: 0 0 15px rgba(255, 107, 157, 0.4);
}

/* === PAGINAÇÃO FUTURISTA === */
.futuristic-pagination {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    margin-top: 30px;
    flex-wrap: wrap;
}

.pagination-btn {
    background: var(--surface-lighter);
    border: 1px solid var(--border);
    border-radius: 12px;
    padding: 10px 16px;
    color: var(--text-secondary);
    text-decoration: none;
    font-weight: 600;
    transition: all 0.3s ease;
    min-width: 44px;
    text-align: center;
}

.pagination-btn:hover {
    background: linear-gradient(135deg, var(--primary), var(--primary-dark));
    color: white;
    transform: translateY(-2px);
    box-shadow: var(--glow);
    border-color: transparent;
}

.pagination-btn.active {
    background: linear-gradient(135deg, var(--secondary), #0099CC);
    color: white;
    border-color: transparent;
    box-shadow: var(--glow-blue);
}

/* === BADGES E STATUS === */
.status-badge {
    padding: 6px 12px;
    border-radius: 8px;
    font-size: 0.8rem;
    font-weight: 600;
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

.badge-active {
    background: linear-gradient(135deg, #00D4FF, #0099CC);
    color: white;
}

.badge-expired {
    background: linear-gradient(135deg, #FF6B9D, #D94A7E);
    color: white;
}

/* === MODAIS FUTURISTAS === */
.futuristic-modal .modal-content {
    background: var(--surface-light);
    border: 1px solid var(--border);
    border-radius: 20px;
    backdrop-filter: blur(20px);
    box-shadow: 0 20px 60px rgba(0, 0, 0, 0.5);
}

.futuristic-modal .modal-header {
    background: linear-gradient(135deg, var(--surface-light), var(--surface-lighter));
    border-bottom: 1px solid var(--border);
    border-radius: 20px 20px 0 0;
    padding: 20px 25px;
}

.futuristic-modal .modal-header h2 {
    color: var(--text-primary);
    margin: 0;
    font-size: 1.3rem;
    background: linear-gradient(135deg, var(--primary), var(--accent));
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    background-clip: text;
}

.futuristic-modal .modal-body {
    color: var(--text-secondary);
    padding: 25px;
    background: transparent;
}

.futuristic-modal .modal-footer {
    border-top: 1px solid var(--border);
    padding: 20px 25px;
    background: transparent;
}

/* === RESPONSIVIDADE === */
@media (max-width: 768px) {
    .main-content {
        padding: 15px;
    }
    
    .card-body-futuristic {
        padding: 20px;
    }
    
    .futuristic-table {
        font-size: 0.9rem;
    }
    
    .futuristic-table th,
    .futuristic-table td {
        padding: 10px 8px !important;
    }
    
    .futuristic-pagination {
        gap: 4px;
    }
    
    .pagination-btn {
        padding: 8px 12px;
        min-width: 40px;
        font-size: 0.9rem;
    }
}

/* === ANIMAÇÕES === */
@keyframes fadeInUp {
    from {
        opacity: 0;
        transform: translateY(20px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

.fade-in-up {
    animation: fadeInUp 0.5s ease-out;
}

/* === SCROLLBAR PERSONALIZADA === */
.futuristic-table-container::-webkit-scrollbar {
    width: 8px;
    height: 8px;
}

.futuristic-table-container::-webkit-scrollbar-track {
    background: var(--surface-light);
    border-radius: 4px;
}

.futuristic-table-container::-webkit-scrollbar-thumb {
    background: linear-gradient(135deg, var(--primary), var(--accent));
    border-radius: 4px;
}

.futuristic-table-container::-webkit-scrollbar-thumb:hover {
    background: linear-gradient(135deg, var(--primary-dark), var(--accent));
}
</style>

<!-- Modal de Confirmação de Exclusão -->
<div class="modal fade futuristic-modal" id="confirm-delete" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h2><i class="fas fa-exclamation-triangle me-2"></i>Confirmar Exclusão</h2>
            </div>
            <div class="modal-body">
                <div class="text-center mb-3">
                    <i class="fas fa-trash-alt fa-3x text-primary mb-3"></i>
                    <p class="mb-0">Você realmente deseja excluir este usuário?</p>
                    <small class="text-muted">Esta ação não pode ser desfeita.</small>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn futuristic-btn futuristic-btn-secondary" data-dismiss="modal">
                    <i class="fas fa-times me-2"></i>Cancelar
                </button>
                <a class="btn futuristic-btn btn-ok">
                    <i class="fas fa-trash me-2"></i>Deletar
                </a>
            </div>
        </div>
    </div>
</div>

<!-- Modal de Mensagem da Revenda -->
<?php if(isset($titulo)): ?>
<div class="modal fade vertical futuristic-modal" id="mensagem_revenda" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h2><i class="fas fa-bullhorn me-2"></i><?php echo $titulo; ?></h2>
            </div>
            <div class="modal-body">
                <div class="alert alert-info border-0 bg-transparent">
                    <i class="fas fa-info-circle me-2"></i>
                    <?php echo $mensagem; ?>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn futuristic-btn futuristic-btn-secondary" data-dismiss="modal">
                    <i class="fas fa-check me-2"></i>Entendi
                </button>
            </div>
        </div>
    </div>
</div>
<?php endif; ?>

<main class="main-content fade-in-up">
    <!-- Content Row -->
    <div class="row">
        <div class="col-lg-12">
            <!-- Card Principal -->
            <div class="futuristic-card shadow mb-4">
                <div class="card-header-futuristic">
                    <h6><i class="fas fa-fw fa-users"></i> Gerenciamento de Usuários</h6>
                </div>
                <div class="card-body-futuristic">
                    <!-- Barra de Pesquisa -->
                    <form method="get" class="mb-4">
                        <div class="row g-3 align-items-end">
                            <div class="col-md-8">
                                <label class="form-label text-primary small fw-bold">PESQUISAR USUÁRIOS</label>
                                <input type="text" name="search" class="form-control futuristic-input" 
                                       placeholder="Digite MAC, Título, Username..." 
                                       value="<?php echo htmlspecialchars($searchTerm); ?>">
                            </div>
                            <div class="col-md-4">
                                <button type="submit" class="btn futuristic-btn w-100">
                                    <i class="fas fa-search me-2"></i>Pesquisar
                                </button>
                            </div>
                        </div>
                    </form>

                    <!-- Botão Criar -->
                    <div class="d-flex justify-content-between align-items-center mb-4">
                        <div class="d-flex align-items-center">
                            <span class="text-muted small">
                                <i class="fas fa-chart-bar me-2"></i>
                                Total: <?php echo $totaleview; ?> usuários
                            </span>
                        </div>
                        <a href="./users_create.php" class="btn futuristic-btn futuristic-btn-secondary">
                            <i class="fas fa-plus-circle me-2"></i>Criar Novo Usuário
                        </a>
                    </div>

                    <!-- Tabela de Usuários -->
                    <div class="futuristic-table-container">
                        <table class="table futuristic-table">
                            <thead>
                                <tr>
                                    <th><i class="fas fa-heading me-2"></i>Título</th>
                                    <th><i class="fas fa-network-wired me-2"></i>Mac Address</th>
                                    <th><i class="fas fa-user me-2"></i>Username</th>
                                    <th><i class="fas fa-store me-2"></i>Vendedor</th>
                                    <th><i class="fas fa-calendar-alt me-2"></i>Validade</th>
                                    <th><i class="fas fa-server me-2"></i>DNS</th>
                                    <th><i class="fas fa-cog me-2"></i>Extra</th>
                                    <th><i class="fas fa-edit me-2"></i>Editar</th>
                                    <th><i class="fas fa-trash me-2"></i>Deletar</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php while ($row1 = $res1->fetchArray()): ?>
                                    <?php
                                    $users_id = $row1['id'];
                                    $user_mac = $row1['mac_address'];
                                    $user_username = $row1['username'];
                                    $user_seller = $row1['seller'];
                                    $user_expire_date = $row1['expire_date'];
                                    $user_url = $row1['url'];
                                    $user_title = $row1['title'];
                                    $user_extra = $row1['extra'];
                                    
                                    // Verificar se está expirado
                                    $is_expired = strtotime($user_expire_date) < time();
                                    ?>
                                    <tr>
                                        <td>
                                            <div class="d-flex align-items-center">
                                                <span class="fw-medium"><?php echo htmlspecialchars($user_title); ?></span>
                                                <?php if($is_expired): ?>
                                                    <span class="status-badge badge-expired ms-2">Expirado</span>
                                                <?php else: ?>
                                                    <span class="status-badge badge-active ms-2">Ativo</span>
                                                <?php endif; ?>
                                            </div>
                                        </td>
                                        <td><code class="text-primary"><?php echo htmlspecialchars($user_mac); ?></code></td>
                                        <td><?php echo htmlspecialchars($user_username); ?></td>
                                        <td>
                                            <span class="text-accent"><?php echo htmlspecialchars($user_seller); ?></span>
                                        </td>
                                        <td>
                                            <span class="<?php echo $is_expired ? 'text-danger' : 'text-success'; ?>">
                                                <?php echo date('d/m/Y', strtotime($user_expire_date)); ?>
                                            </span>
                                        </td>
                                        <td>
                                            <small class="text-muted"><?php echo htmlspecialchars($user_url); ?></small>
                                        </td>
                                        <td>
                                            <?php if(!empty($user_extra)): ?>
                                                <span class="badge bg-secondary"><?php echo htmlspecialchars($user_extra); ?></span>
                                            <?php else: ?>
                                                <span class="text-muted">-</span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <a class="btn btn-action btn-edit" href="./users_update.php?update=<?php echo $users_id; ?>" 
                                               title="Editar Usuário">
                                                <i class="fas fa-edit"></i>
                                            </a>
                                        </td>
                                        <td>
                                            <a class="btn btn-action btn-delete delete-btn" href="#" 
                                               data-href="./index.php?delete=<?php echo $users_id; ?>" 
                                               data-toggle="modal" data-target="#confirm-delete"
                                               title="Excluir Usuário">
                                                <i class="fas fa-trash"></i>
                                            </a>
                                        </td>
                                    </tr>
                                <?php endwhile; ?>
                            </tbody>
                        </table>
                    </div>

                    <!-- Paginação -->
                    <?php if ($results_per_page < $totaleview): ?>
                    <div class="futuristic-pagination">
                        <?php if ($page > 1): ?>
                            <a class="pagination-btn" href='index.php?view=<?php echo ($page - 1); ?>&search=<?php echo urlencode($searchTerm); ?>'>
                                <i class="fas fa-chevron-left me-1"></i>Anterior
                            </a>
                        <?php endif; ?>
                        
                        <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                            <?php if ($i == $page): ?>
                                <a class="pagination-btn active" href='index.php?view=<?php echo $i; ?>&search=<?php echo urlencode($searchTerm); ?>'>
                                    <?php echo $i; ?>
                                </a>
                            <?php else: ?>
                                <a class="pagination-btn" href='index.php?view=<?php echo $i; ?>&search=<?php echo urlencode($searchTerm); ?>'>
                                    <?php echo $i; ?>
                                </a>
                            <?php endif; ?>
                        <?php endfor; ?>
                        
                        <?php if ($page < $total_pages): ?>
                            <a class="pagination-btn" href='index.php?view=<?php echo ($page + 1); ?>&search=<?php echo urlencode($searchTerm); ?>'>
                                Próximo<i class="fas fa-chevron-right ms-1"></i>
                            </a>
                        <?php endif; ?>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</main>

<script>
// Script para o modal de confirmação de exclusão
document.addEventListener('DOMContentLoaded', function() {
    $('#confirm-delete').on('show.bs.modal', function(e) {
        $(this).find('.btn-ok').attr('href', $(e.relatedTarget).data('href'));
    });
    
    // Efeitos de hover nas linhas da tabela
    const tableRows = document.querySelectorAll('.futuristic-table tbody tr');
    tableRows.forEach((row, index) => {
        row.style.animationDelay = `${index * 0.05}s`;
    });
    
    // Mostrar modal de mensagem se existir
    <?php if(isset($titulo)): ?>
        setTimeout(() => {
            $('#mensagem_revenda').modal('show');
        }, 1000);
    <?php endif; ?>
});
</script>

<?php
include '../includes/footer2.php';
require '../includes/egz2.php';
?>