<?php
ini_set('display_errors', 0);
ini_set('display_startup_errors', 0);
error_reporting(E_ALL);

$db = new SQLite3('./a/.eggziedb.db');
$db->exec('CREATE TABLE IF NOT EXISTS `revenda` (
    `id` INTEGER PRIMARY KEY,
    `nome` TEXT NOT NULL,
    `usuario` TEXT NOT NULL,
    `senha` TEXT NOT NULL,
    `registro` TIMESTAMP NOT NULL,
    `macs` INTEGER NOT NULL
);');

include 'includes/header.php';

if(isset($_GET['index'])) {
    $index = $_GET['index'];
} else {
    $index = ""; 
}

if (isset($_POST['submit'])) {
    $usuario = $_POST['username'];
    
    // Verificação de existência em revenda e sub_revenda
    $result = $db->query("SELECT COUNT(*) as count FROM revenda WHERE usuario = '$usuario'");
    $row = $result->fetchArray(SQLITE3_ASSOC);
    $count = $row['count'];
    
    $result2 = $db->query("SELECT COUNT(*) as count FROM sub_revenda WHERE usuario = '$usuario'");
    $row2 = $result2->fetchArray(SQLITE3_ASSOC);
    $count2 = $row2['count'];
    
    $total_count = $count + $count2;
      
    if($total_count > 0 || $usuario == "ADM") {
      echo "<script>alert('Já existe um sub revenda/revenda com esse usuario, por favor escolha outro!');window.location.href='revenda.php';</script>";
    } else {
        $registro = date('Y/m/d');
        $nome = $_POST['nome'];
        $senha = $_POST['password'];
        $macs = $_POST['macs'];
        $descricao = $_POST['Descricao'];
        
        $query = "SELECT MAX(max_value) AS maior_valor FROM (
                SELECT MAX(id_ref) AS max_value FROM revenda
                UNION
                SELECT MAX(id_ref) AS max_value FROM sub_revenda
              ) as combined";
        $result_ref = $db->query($query);
        $row_ref = $result_ref->fetchArray(SQLITE3_ASSOC);
        $ref_id = $row_ref['maior_valor'] ?? 0;
        $ref_id++;
        
        $db->exec("INSERT INTO revenda (nome, usuario, senha, registro, macs, extra, id_ref) VALUES('$nome', '$usuario', '$senha', '$registro', '$macs', '$descricao', '$ref_id')");
        
        // Criar arquivos default para o novo revendedor
        $caminho_arquivo = "a/rtx/";
        @file_put_contents($caminho_arquivo . "Setting_$usuario.json", file_get_contents($caminho_arquivo . "Setting.json"));
        @file_put_contents($caminho_arquivo . "logo_filenames_$usuario.json", file_get_contents($caminho_arquivo . "logo_filenames.json"));
        @file_put_contents($caminho_arquivo . "image_filenames_$usuario.json", file_get_contents($caminho_arquivo . "image_filenames.json"));
        @file_put_contents("a/note_$usuario.json", file_get_contents("a/note.json"));
        @file_put_contents("a/qrcode_$usuario.json", file_get_contents("a/qrcode.json"));
        @file_put_contents("api/theme_$usuario.json", file_get_contents("api/theme.json"));

        $db->close();
        echo "<script>window.location.href='revenda.php'</script>";
    }
}
?>

<style>
    @import url('https://fonts.googleapis.com/css2?family=Orbitron:wght@400;700&family=Poppins:wght@300;400;600&display=swap');

    :root {
        --neon-blue: #00d4ff;
        --dark-bg: #06090c;
        --card-glass: rgba(13, 18, 24, 0.95);
        --border-glass: rgba(0, 212, 255, 0.2);
    }

    /* Reset total para remover fundo branco */
    body, #wrapper, #content-wrapper, #content, .container-fluid {
        background-color: var(--dark-bg) !important;
        color: #f8f9fc;
        font-family: 'Poppins', sans-serif;
    }

    .card-futuristic {
        background: var(--card-glass) !important;
        backdrop-filter: blur(15px);
        border: 1px solid var(--border-glass) !important;
        border-radius: 15px !important;
        box-shadow: 0 10px 30px rgba(0,0,0,0.5);
        margin-bottom: 25px;
    }

    .card-header-futuristic {
        background: rgba(0, 212, 255, 0.03) !important;
        border-bottom: 1px solid var(--border-glass) !important;
        padding: 1.2rem !important;
    }

    .card-header-futuristic h6 {
        font-family: 'Orbitron', sans-serif;
        color: var(--neon-blue) !important;
        text-shadow: 0 0 10px var(--neon-blue);
        letter-spacing: 2px;
        margin: 0;
        text-transform: uppercase;
    }

    /* Formulários e Inputs */
    .form-control {
        background: rgba(0, 0, 0, 0.4) !important;
        border: 1px solid var(--border-glass) !important;
        color: #fff !important;
        border-radius: 8px !important;
        padding: 12px !important;
        transition: 0.3s;
    }

    .form-control:focus {
        border-color: var(--neon-blue) !important;
        box-shadow: 0 0 15px rgba(0, 212, 255, 0.3) !important;
        background: rgba(0, 0, 0, 0.6) !important;
        color: #fff !important;
    }

    label strong {
        color: var(--neon-blue);
        font-family: 'Orbitron', sans-serif;
        font-size: 0.75rem;
        letter-spacing: 1px;
        text-transform: uppercase;
    }

    /* Botão Neon */
    .btn-neon-submit {
        background: transparent;
        border: 1px solid var(--neon-blue);
        color: var(--neon-blue) !important;
        font-family: 'Orbitron', sans-serif;
        padding: 12px 30px;
        border-radius: 8px;
        transition: 0.4s;
        text-transform: uppercase;
        width: 100%;
        letter-spacing: 1px;
    }

    .btn-neon-submit:hover {
        background: var(--neon-blue);
        color: #000 !important;
        box-shadow: 0 0 20px var(--neon-blue);
    }

    .text-gray-800 {
        color: #fff !important;
        font-family: 'Orbitron', sans-serif;
        text-transform: uppercase;
        letter-spacing: 2px;
    }
</style>

<div class="container-fluid pt-4 px-5">
    <h1 class="h3 mb-4">Painel de Revenda</h1>

    <div class="row">
        <div class="col-lg-8 mx-auto">
            <div class="card card-futuristic shadow">
                <div class="card-header-futuristic">
                    <h6><i class="fas fa-user-plus mr-2"></i> Detalhes da Conta</h6>
                </div>
                <div class="card-body p-4">
                    <form method="post">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group mb-4">
                                    <label for="nome"><strong>Nome Completo</strong></label>
                                    <input class="form-control" id="nome" name="nome" placeholder="Ex: João Silva" type="text" required/>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group mb-4">
                                    <label for="macs"><strong>Limite de MACs</strong></label>
                                    <input type="number" min="1" max="99999" class="form-control" name="macs" placeholder="0" id="macs" required/>
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group mb-4">
                                    <label for="username"><strong>ID de Usuário</strong></label>
                                    <input type="text" class="form-control" name="username" placeholder="usuario_revenda" id="username" required/>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group mb-4">
                                    <label for="password"><strong>Senha de Acesso</strong></label>
                                    <input type="text" class="form-control" name="password" placeholder="********" id="password" required/>
                                </div>
                            </div>
                        </div>

                        <div class="form-group mb-4">
                            <label for="Descricao"><strong>Descrição / Observações</strong></label>
                            <input class="form-control" id="Descricao" name="Descricao" placeholder="Notas sobre esta revenda..." type="text" required/>
                        </div>

                        <div class="mt-4">
                            <button class="btn btn-neon-submit" name="submit" type="submit">
                                <i class="fas fa-save mr-2"></i> Criar Revendedor
                            </button>
                        </div>
                    </form>
                </div>
            </div>
            
            <div class="text-center mt-3">
                <a href="revenda.php" style="color: rgba(255,255,255,0.5); text-decoration: none; font-size: 0.8rem; font-family: 'Orbitron';">
                    <i class="fas fa-arrow-left mr-1"></i> Voltar ao Terminal
                </a>
            </div>
        </div>
    </div>
</div>

<?php include 'includes/footer.php'; ?>