<?php
// Configurações básicas
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);



// Conexão com banco
$db = new SQLite3('./a/.eggziedb.db');

// Processar exclusão
if (isset($_POST['excluir_revenda'])) {
    $id = $_POST['id'];
    $tipo = $_POST['tipo'];
    $tabela = ($tipo === 'revenda') ? 'revenda' : 'sub_revenda';
    $db->exec("DELETE FROM $tabela WHERE id = $id");
    $_SESSION['success_message'] = ($tipo === 'revenda') ? "Revenda excluída com sucesso!" : "Sub-revenda excluída com sucesso!";
    header("Location: " . $_SERVER['PHP_SELF']);
    exit;
}

// Processar edição
if (isset($_POST['editar_revenda'])) {
    $id = $_POST['id'];
    $tipo = $_POST['tipo'];
    $nome = SQLite3::escapeString($_POST['nome']);
    $usuario = SQLite3::escapeString($_POST['usuario']);
    $senha = SQLite3::escapeString($_POST['senha']);
    $macs = (int)$_POST['macs'];
    $descricao = SQLite3::escapeString($_POST['descricao']);
    
    if ($tipo === 'revenda') {
        $db->exec("UPDATE revenda SET nome = '$nome', usuario = '$usuario', senha = '$senha', macs = $macs, extra = '$descricao' WHERE id = $id");
        $_SESSION['success_message'] = "Revenda atualizada com sucesso!";
    } else {
        $db->exec("UPDATE sub_revenda SET nome = '$nome', usuario = '$usuario', senha = '$senha', macs = $macs, extra = '$descricao' WHERE id = $id");
        $_SESSION['success_message'] = "Sub-revenda atualizada com sucesso!";
    }
    
    header("Location: " . $_SERVER['PHP_SELF']);
    exit;
}

// Buscar dados
$revendas = [];
$result = $db->query("SELECT * FROM revenda ORDER BY id DESC");
while ($row = $result->fetchArray(SQLITE3_ASSOC)) $revendas[] = $row;

$sub_revendas = [];
$result = $db->query("SELECT * FROM sub_revenda ORDER BY id DESC");
while ($row = $result->fetchArray(SQLITE3_ASSOC)) $sub_revendas[] = $row;

$db->close();
include 'includes/header.php';

if (isset($_SESSION['success_message'])) {
    $success_message = $_SESSION['success_message'];
    unset($_SESSION['success_message']);
}
?>

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Lista de Revendas - ULTRA IBO</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&display=swap" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        :root {
            --primary: #00D4FF; --secondary: #FF6B9D; --accent: #00FF88;
            --surface: #0A0F1C; --surface-light: #1A1F2C; --text-primary: #FFFFFF;
            --text-secondary: #B0B7C3; --border: rgba(255,255,255,0.1);
            --glow: 0 0 20px rgba(0, 212, 255, 0.3);
        }
        body {
            background: radial-gradient(circle at center, #0a0a0f, #000);
            font-family: "Inter", sans-serif; color: var(--text-primary);
            margin: 0; padding: 20px; min-height: 100vh;
        }
        .container { max-width: 1400px; margin: 0 auto; }
        .header { text-align: center; margin-bottom: 40px; }
        .header h1 {
            background: linear-gradient(135deg, var(--primary), var(--accent));
            -webkit-background-clip: text; -webkit-text-fill-color: transparent;
            font-size: 2.5rem; margin-bottom: 10px;
        }
        .tabs { display: flex; gap: 10px; margin-bottom: 30px; justify-content: center; }
        .tab {
            padding: 15px 30px; background: var(--surface-light); border: 1px solid var(--border);
            border-radius: 12px; cursor: pointer; transition: all 0.3s ease; font-weight: 600;
        }
        .tab.active { background: linear-gradient(135deg, var(--primary), var(--accent)); }
        .tab:hover:not(.active) { background: var(--surface-light); }
        .content-section { display: none; }
        .content-section.active { display: block; }
        .card-grid {
            display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
            gap: 20px; margin-bottom: 40px;
        }
        .card {
            background: rgba(0, 0, 0, 0.9); border: 1px solid var(--border);
            border-radius: 16px; padding: 20px; transition: all 0.3s ease;
            position: relative; overflow: hidden;
        }
        .card::before {
            content: ''; 
            position: absolute; 
            top: 0; 
            left: 0; 
            right: 0; 
            height: 3px;
            background: linear-gradient(90deg, var(--primary), var(--primary));
        }
        .card:hover { transform: translateY(-5px); box-shadow: var(--glow); }
        .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
    background: #000000; /* ↑↑↑ FUNDO PRETO NO HEADER ↑↑↑ */
    padding: 10px;
    margin: -20px -20px 15px -20px; /* Compensa o padding do card */
    border-radius: 16px 16px 0 0; /* Arredonda só o topo */
}
        .card-title { font-size: 1.2rem; font-weight: 700; margin: 0; 
            
        }
        
        .card-badge {
            background: linear-gradient(135deg, var(--secondary), var(--primary));
            padding: 4px 12px; 
            border-radius: 20px; 
            font-size: 0.7rem; 
            font-weight: 600;
            color: black;
        }
        .card-badge.sub { 
            background: linear-gradient(135deg, var(--secondary), var(--primary)); 
            
        }
        .card-date { color: var(--text-secondary); font-size: 0.9rem; margin-bottom: 15px; }
        .action-buttons { display: flex; gap: 10px; }
        .btn { padding: 8px 16px; border: none; border-radius: 8px; font-weight: 600; cursor: pointer; transition: all 0.3s ease; flex: 1; }
        .btn-primary { background: var(--primary); color: white; }
        .btn-info { background: var(--accent); color: white; }
        .btn-danger { background: var(--secondary); color: white; }
        .btn:hover { transform: translateY(-2px); box-shadow: 0 5px 15px rgba(0,0,0,0.3); }
        .stats-container { display: grid; grid-template-columns: repeat(3, 1fr); gap: 20px; margin-bottom: 40px; }
        .stat-card {
            background: rgba(10, 15, 28, 0.85); border: 1px solid var(--border); border-radius: 16px;
            padding: 25px; text-align: center; position: relative; overflow: hidden;
        }
        .stat-card::before {
            content: ''; position: absolute; top: 0; left: 0; right: 0; height: 3px;
            background: linear-gradient(90deg, var(--primary), var(--accent));
        }
        .stat-number {
            font-size: 2.5rem; font-weight: 700;
            background: linear-gradient(135deg, var(--primary), var(--accent));
            -webkit-background-clip: text; -webkit-text-fill-color: transparent; margin: 10px 0;
        }
        .empty-state { text-align: center; padding: 60px 20px; color: var(--text-secondary); }
        
        /* Modals */
        .modal {
            display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%;
            background: rgba(0, 0, 0, 0.8); backdrop-filter: blur(10px); z-index: 1000;
            align-items: center; justify-content: center;
        }
        .modal.active { display: flex; }
        .modal-content {
            background: rgba(10, 15, 28, 0.95); border: 1px solid var(--border);
            border-radius: 20px; padding: 30px; width: 90%; max-width: 500px;
            position: relative; box-shadow: var(--glow);
        }
        .modal-header {
            display: flex; justify-content: space-between; align-items: center;
            margin-bottom: 20px; padding-bottom: 15px; border-bottom: 1px solid var(--border);
        }
        .modal-title {
            font-size: 1.5rem; font-weight: 700;
            background: linear-gradient(135deg, var(--primary), var(--accent));
            -webkit-background-clip: text; -webkit-text-fill-color: transparent; margin: 0;
        }
        .close-modal { background: none; border: none; color: var(--text-secondary); font-size: 1.5rem; cursor: pointer; }
        .form-group { margin-bottom: 20px; }
        .form-label { display: block; color: var(--text-secondary); font-weight: 600; margin-bottom: 8px; }
        .form-input {
            width: 100%; padding: 12px; border-radius: 8px; border: 1px solid var(--border);
            background: var(--surface-light); color: var(--text-primary); font-size: 1rem;
        }
        .form-input:focus { border-color: var(--primary); outline: none; box-shadow: var(--glow); }
        .modal-actions { display: flex; gap: 10px; margin-top: 25px; }
        .modal-actions .btn { flex: 1; }
        .success-message {
            background: rgba(0, 255, 136, 0.1); border: 1px solid #00FF88; border-radius: 12px;
            padding: 15px; margin-bottom: 20px; text-align: center;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1><i class="fas fa-store"></i> Sistema de Revendas</h1>
            <p>Gerencie todas as revendas e sub-revendas do sistema</p>
        </div>
        
        <?php if (isset($success_message)): ?>
            <div class="success-message">
                <h3><i class="fas fa-check-circle"></i> <?php echo $success_message; ?></h3>
            </div>
        <?php endif; ?>
        
        <!-- Estatísticas -->
        <div class="stats-container">
            <div class="stat-card">
                <div class="stat-label">Total de Revendas</div>
                <div class="stat-number"><?php echo count($revendas); ?></div>
            </div>
            <div class="stat-card">
                <div class="stat-label">Total de Sub-revendas</div>
                <div class="stat-number"><?php echo count($sub_revendas); ?></div>
            </div>
            <div class="stat-card">
                <div class="stat-label">Total Geral</div>
                <div class="stat-number"><?php echo count($revendas) + count($sub_revendas); ?></div>
            </div>
        </div>
        
        <!-- Tabs -->
        <div class="tabs">
            <div class="tab active" onclick="showSection('revendas')">Revendas (<?php echo count($revendas); ?>)</div>
            <div class="tab" onclick="showSection('subrevendas')">Sub-revendas (<?php echo count($sub_revendas); ?>)</div>
            <div class="tab" onclick="showSection('todos')">Todos (<?php echo count($revendas) + count($sub_revendas); ?>)</div>
        </div>
        
        <!-- Seção Revendas -->
        <div id="revendas" class="content-section active">
            <?php if (empty($revendas)): ?>
                <div class="empty-state">Nenhuma Revenda Cadastrada</div>
            <?php else: ?>
                <div class="card-grid">
                    <?php foreach ($revendas as $revenda): ?>
                        <div class="card">
                            <div class="card-header">
                                <h3 class="card-title"><?php echo htmlspecialchars($revenda['nome']); ?></h3>
                                <span class="card-badge">REVENDA</span>
                            </div>
                            <div class="card-date">Registro: <?php echo htmlspecialchars($revenda['registro']); ?></div>
                            <div class="action-buttons">
                                <button class="btn btn-info" onclick="visualizarRevenda(<?php echo htmlspecialchars(json_encode($revenda)); ?>, 'revenda')">
                                    <i class="fas fa-eye"></i> Visualizar
                                </button>
                                <button class="btn btn-primary" onclick="abrirEdicao(<?php echo htmlspecialchars(json_encode($revenda)); ?>, 'revenda')">
                                    <i class="fas fa-edit"></i> Editar
                                </button>
                                <button class="btn btn-danger" onclick="abrirExclusao(<?php echo $revenda['id']; ?>, 'revenda', '<?php echo htmlspecialchars($revenda['nome']); ?>')">
                                    <i class="fas fa-trash"></i> Excluir
                                </button>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </div>
        
        <!-- Seção Sub-revendas -->
        <div id="subrevendas" class="content-section">
            <?php if (empty($sub_revendas)): ?>
                <div class="empty-state">Nenhuma Sub-revenda Cadastrada</div>
            <?php else: ?>
                <div class="card-grid">
                    <?php foreach ($sub_revendas as $sub): ?>
                        <div class="card">
                            <div class="card-header">
                                <h3 class="card-title"><?php echo htmlspecialchars($sub['nome']); ?></h3>
                                <span class="card-badge sub">SUB-REVENDA</span>
                            </div>
                            <div class="card-date">Registro: <?php echo htmlspecialchars($sub['registro']); ?></div>
                            <div class="action-buttons">
                                <button class="btn btn-info" onclick="visualizarRevenda(<?php echo htmlspecialchars(json_encode($sub)); ?>, 'subrevenda')">
                                    <i class="fas fa-eye"></i> Visualizar
                                </button>
                                <button class="btn btn-primary" onclick="abrirEdicao(<?php echo htmlspecialchars(json_encode($sub)); ?>, 'subrevenda')">
                                    <i class="fas fa-edit"></i> Editar
                                </button>
                                <button class="btn btn-danger" onclick="abrirExclusao(<?php echo $sub['id']; ?>, 'subrevenda', '<?php echo htmlspecialchars($sub['nome']); ?>')">
                                    <i class="fas fa-trash"></i> Excluir
                                </button>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </div>
        
        <!-- Seção Todos -->
        <div id="todos" class="content-section">
            <?php if (empty($revendas) && empty($sub_revendas)): ?>
                <div class="empty-state">Nenhum Dado Cadastrado</div>
            <?php else: ?>
                <div class="card-grid">
                    <?php foreach ($revendas as $revenda): ?>
                        <div class="card">
                            <div class="card-header">
                                <h3 class="card-title"><?php echo htmlspecialchars($revenda['nome']); ?></h3>
                                <span class="card-badge">REVENDA</span>
                            </div>
                            <div class="card-date">Registro: <?php echo htmlspecialchars($revenda['registro']); ?></div>
                            <div class="action-buttons">
                                <button class="btn btn-info" onclick="visualizarRevenda(<?php echo htmlspecialchars(json_encode($revenda)); ?>, 'revenda')">Visualizar</button>
                                <button class="btn btn-primary" onclick="abrirEdicao(<?php echo htmlspecialchars(json_encode($revenda)); ?>, 'revenda')">Editar</button>
                                <button class="btn btn-danger" onclick="abrirExclusao(<?php echo $revenda['id']; ?>, 'revenda', '<?php echo htmlspecialchars($revenda['nome']); ?>')">Excluir</button>
                            </div>
                        </div>
                    <?php endforeach; ?>
                    <?php foreach ($sub_revendas as $sub): ?>
                        <div class="card">
                            <div class="card-header">
                                <h3 class="card-title"><?php echo htmlspecialchars($sub['nome']); ?></h3>
                                <span class="card-badge sub">SUB-REVENDA</span>
                            </div>
                            <div class="card-date">Registro: <?php echo htmlspecialchars($sub['registro']); ?></div>
                            <div class="action-buttons">
                                <button class="btn btn-info" onclick="visualizarRevenda(<?php echo htmlspecialchars(json_encode($sub)); ?>, 'subrevenda')">Visualizar</button>
                                <button class="btn btn-primary" onclick="abrirEdicao(<?php echo htmlspecialchars(json_encode($sub)); ?>, 'subrevenda')">Editar</button>
                                <button class="btn btn-danger" onclick="abrirExclusao(<?php echo $sub['id']; ?>, 'subrevenda', '<?php echo htmlspecialchars($sub['nome']); ?>')">Excluir</button>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <!-- Modal de Visualização -->
    <div id="modalVisualizar" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3 class="modal-title" id="modalTitulo">Detalhes</h3>
                <button class="close-modal" onclick="fecharModal('modalVisualizar')">&times;</button>
            </div>
            <div class="modal-info" id="modalInfo"></div>
        </div>
    </div>

    <!-- Modal de Edição -->
    <div id="modalEditar" class="modal">
        <div class="modal-content">
            <form method="post">
                <div class="modal-header">
                    <h3 class="modal-title">Editar Revenda</h3>
                    <button type="button" class="close-modal" onclick="fecharModal('modalEditar')">&times;</button>
                </div>
                <input type="hidden" name="id" id="editId">
                <input type="hidden" name="tipo" id="editTipo">
                <input type="hidden" name="editar_revenda" value="1">
                
                <div class="form-group">
                    <label class="form-label">Nome</label>
                    <input type="text" name="nome" id="editNome" class="form-input" required>
                </div>
                <div class="form-group">
                    <label class="form-label">Usuário</label>
                    <input type="text" name="usuario" id="editUsuario" class="form-input" required>
                </div>
                <div class="form-group">
                    <label class="form-label">Senha</label>
                    <input type="text" name="senha" id="editSenha" class="form-input" required>
                </div>
                <div class="form-group">
                    <label class="form-label">MACs</label>
                    <input type="number" name="macs" id="editMacs" class="form-input" required>
                </div>
                <div class="form-group">
                    <label class="form-label">Descrição</label>
                    <input type="text" name="descricao" id="editDescricao" class="form-input">
                </div>
                
                <div class="modal-actions">
                    <button type="button" class="btn btn-danger" onclick="fecharModal('modalEditar')">Cancelar</button>
                    <button type="submit" class="btn btn-primary">Confirmar Edição</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Modal de Exclusão -->
    <div id="modalExcluir" class="modal">
        <div class="modal-content">
            <form method="post">
                <div class="modal-header">
                    <h3 class="modal-title">Confirmar Exclusão</h3>
                    <button type="button" class="close-modal" onclick="fecharModal('modalExcluir')">&times;</button>
                </div>
                <input type="hidden" name="id" id="deleteId">
                <input type="hidden" name="tipo" id="deleteTipo">
                <input type="hidden" name="excluir_revenda" value="1">
                
                <p style="text-align: center; margin: 20px 0;">Tem certeza que deseja excluir <strong id="deleteNome"></strong>?</p>
                
                <div class="modal-actions">
                    <button type="button" class="btn btn-primary" onclick="fecharModal('modalExcluir')">Cancelar</button>
                    <button type="submit" class="btn btn-danger">Confirmar Exclusão</button>
                </div>
            </form>
        </div>
    </div>

    <script>
        function showSection(sectionId) {
            document.querySelectorAll('.content-section').forEach(s => s.classList.remove('active'));
            document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
            document.getElementById(sectionId).classList.add('active');
            event.target.classList.add('active');
        }
        
        function visualizarRevenda(dados, tipo) {
            const modal = document.getElementById('modalVisualizar');
            document.getElementById('modalTitulo').textContent = `Detalhes da ${tipo === 'revenda' ? 'Revenda' : 'Sub-revenda'}`;
            
            let html = `
                <div style="display: grid; gap: 10px;">
                    <div style="display: flex; justify-content: space-between; padding: 10px 0; border-bottom: 1px solid var(--border);">
                        <span style="color: var(--text-secondary);">Nome:</span>
                        <span>${dados.nome}</span>
                    </div>
                    <div style="display: flex; justify-content: space-between; padding: 10px 0; border-bottom: 1px solid var(--border);">
                        <span style="color: var(--text-secondary);">Usuário:</span>
                        <span>${dados.usuario}</span>
                    </div>
                    <div style="display: flex; justify-content: space-between; padding: 10px 0; border-bottom: 1px solid var(--border);">
                        <span style="color: var(--text-secondary);">MACs:</span>
                        <span>${dados.macs}</span>
                    </div>
                    <div style="display: flex; justify-content: space-between; padding: 10px 0; border-bottom: 1px solid var(--border);">
                        <span style="color: var(--text-secondary);">Data:</span>
                        <span>${dados.registro}</span>
                    </div>
            `;
            
            if (tipo === 'subrevenda') {
                html += `
                    <div style="display: flex; justify-content: space-between; padding: 10px 0; border-bottom: 1px solid var(--border);">
                        <span style="color: var(--text-secondary);">Registrado por:</span>
                        <span>${dados.registrado_por}</span>
                    </div>
                `;
            }
            
            if (dados.extra) {
                html += `
                    <div style="display: flex; justify-content: space-between; padding: 10px 0; border-bottom: 1px solid var(--border);">
                        <span style="color: var(--text-secondary);">Descrição:</span>
                        <span>${dados.extra}</span>
                    </div>
                `;
            }
            
            html += `</div>`;
            document.getElementById('modalInfo').innerHTML = html;
            modal.classList.add('active');
        }
        
        function abrirEdicao(dados, tipo) {
            document.getElementById('editId').value = dados.id;
            document.getElementById('editTipo').value = tipo;
            document.getElementById('editNome').value = dados.nome;
            document.getElementById('editUsuario').value = dados.usuario;
            document.getElementById('editSenha').value = dados.senha;
            document.getElementById('editMacs').value = dados.macs;
            document.getElementById('editDescricao').value = dados.extra || '';
            document.getElementById('modalEditar').classList.add('active');
        }
        
        function abrirExclusao(id, tipo, nome) {
            document.getElementById('deleteId').value = id;
            document.getElementById('deleteTipo').value = tipo;
            document.getElementById('deleteNome').textContent = nome;
            document.getElementById('modalExcluir').classList.add('active');
        }
        
        function fecharModal(modalId) {
            document.getElementById(modalId).classList.remove('active');
        }
        
        // Fechar modals ao clicar fora
        document.querySelectorAll('.modal').forEach(modal => {
            modal.addEventListener('click', function(e) {
                if (e.target === this) this.classList.remove('active');
            });
        });
    </script>
</body>
</html>