<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$db = new SQLite3('../a/.eggziedb.db');
$db->exec('CREATE TABLE IF NOT EXISTS `sub_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,
    `registrado_por` TEXT NOT NULL
);');

$res = $db->query('SELECT * FROM sub_revenda');

include '../includes/header2.php';

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

if (isset($_POST['submit'])) {
    $macs_cust = $_POST['macs'];
    $usuario = $_POST['username'];
     
    $result = $db->query("SELECT macs FROM revenda WHERE usuario = '$seller_name'");
    while ($row = $result->fetchArray()) {
        $macs = $row['macs'];
        break;
    }
     
    $result = $db->query("SELECT COUNT(*) as count FROM revenda WHERE usuario = '$usuario'");
    $row = $result->fetchArray(SQLITE3_ASSOC);
    $count = $row['count'];
    
    $result = $db->query("SELECT COUNT(*) as count FROM sub_revenda WHERE usuario = '$usuario'");
    $row = $result->fetchArray(SQLITE3_ASSOC);
    $count2 = $row['count'];
    
    $count = $count + $count2;
      
    if($count || $usuario == "ADM") {
        echo "<script>alert('Já existe um sub revenda/revenda com esse usuario, por favor escolha outro!');window.location.href='sub_revenda.php';</script>";
    } else {
        if($macs_cust > $macs || $macs_cust <= 0) {
            echo "<script>alert('Você não possui MACs suficientes ou Numero de MACs deve ser maior que 0!');window.location.href='sub_revenda.php';</script>";
        } else {
            $registro = date('Y/m/d');
            $nome = $_POST['nome'];
            $senha = $_POST['password'];
            $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 = $db->query($query);
            $row = $result->fetchArray(SQLITE3_ASSOC);
            $ref_id = $row['maior_valor'];
            $ref_id++;
        
            $db->exec("INSERT INTO sub_revenda(nome, usuario, senha, registro, macs, registrado_por, extra, id_ref) VALUES('$nome', '$usuario', '$senha', '$registro', '$macs_cust', '$seller_name', '$Descricao', '$ref_id')");
            $newmac = $macs - $macs_cust;
            $db->exec("UPDATE revenda SET macs = '$newmac' WHERE usuario = '$seller_name'");
            $db->close();
            
            // criar arquivos default:
            $caminho_arquivo = "../a/rtx/";
            $resultado = file_put_contents($caminho_arquivo . "Setting_$usuario.json", file_get_contents($caminho_arquivo . "Setting.json"));
            $resultado = file_put_contents($caminho_arquivo . "logo_filenames_$usuario.json", file_get_contents($caminho_arquivo . "logo_filenames.json"));
            $resultado = file_put_contents($caminho_arquivo . "image_filenames_$usuario.json", file_get_contents($caminho_arquivo . "image_filenames.json"));
            $resultado = file_put_contents("../a/note_$usuario.json", file_get_contents("../a/note.json"));
            $resultado = file_put_contents("../a/qrcode_$usuario.json", file_get_contents("../a/qrcode.json"));
            $caminho_arquivo = "../api/theme_$usuario.json";
            $resultado = file_put_contents($caminho_arquivo, file_get_contents("../api/theme.json"));
        
            // inserir ADS default
            $adb->exec("INSERT INTO ads (title, url, owner) VALUES('Exemplo', 'https://meubox.painelmaster.lol/img/banners/67a02a3a6c9ec.jpeg', '$usuario')");
        
            // inserir canal default
            $db = new SQLite3('../api/intro.db');
            $db->exec("INSERT INTO intro (url, owner) VALUES ('Nenhuma URL definida', '$usuario')");
	
            echo "<script>window.location.href='sub_revenda.php';</script>";
        }
    }
}
?>

<style>
/* === DESIGN FUTURISTA PARA CRIAÇÃO DE SUB REVENDAS === */
: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-accent: 0 0 20px rgba(255, 209, 102, 0.3);
}

.container-fluid {
    background: transparent !important;
    padding: 20px;
}

.h3 {
    color: var(--text-primary) !important;
    font-weight: 700;
    margin-bottom: 24px;
    text-align: center;
    background: linear-gradient(135deg, var(--primary), var(--accent));
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    background-clip: text;
}

/* === CARDS FUTURISTAS === */
.card {
    background: var(--surface-light) !important;
    border: 1px solid var(--border) !important;
    border-radius: 16px !important;
    box-shadow: var(--glow) !important;
    backdrop-filter: blur(10px);
    margin-bottom: 24px;
    transition: all 0.3s ease;
}

.card:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 30px rgba(255, 107, 157, 0.4);
}

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

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

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

.card-body {
    padding: 30px !important;
}

/* === FORMULÁRIOS FUTURISTAS === */
.form-group {
    margin-bottom: 24px;
}

.control-label {
    color: var(--text-primary) !important;
    font-weight: 600;
    margin-bottom: 8px;
    display: block;
    font-size: 1rem;
}

.control-label strong {
    background: linear-gradient(135deg, var(--secondary), var(--primary));
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    background-clip: text;
}

.form-control {
    background: var(--surface-lighter) !important;
    border: 1px solid var(--border) !important;
    border-radius: 12px !important;
    color: var(--text-primary) !important;
    padding: 14px 16px;
    font-size: 1rem;
    transition: all 0.3s ease;
    width: 100%;
}

.form-control:focus {
    background: var(--surface-lighter) !important;
    border-color: var(--primary) !important;
    box-shadow: 0 0 0 0.2rem rgba(255, 107, 157, 0.25) !important;
    color: var(--text-primary) !important;
    outline: none;
}

.form-control::placeholder {
    color: var(--text-muted) !important;
}

.input-group {
    position: relative;
    display: flex;
    flex-wrap: wrap;
    align-items: stretch;
    width: 100%;
}

/* === BOTÕES FUTURISTAS === */
.btn-success {
    background: linear-gradient(135deg, var(--accent), #FFB347) !important;
    border: none !important;
    border-radius: 12px !important;
    padding: 14px 28px;
    font-weight: 600;
    font-size: 1rem;
    transition: all 0.3s ease;
    box-shadow: var(--glow-accent);
    color: var(--surface) !important;
}

.btn-success:hover {
    transform: translateY(-2px);
    box-shadow: 0 0 30px rgba(255, 209, 102, 0.5);
    color: var(--surface) !important;
}

.btn-icon-split {
    display: inline-flex;
    align-items: center;
    background: linear-gradient(135deg, var(--secondary), var(--primary-dark)) !important;
    border-radius: 12px;
    overflow: hidden;
    transition: all 0.3s ease;
    box-shadow: var(--glow);
    text-decoration: none;
    border: none;
}

.btn-icon-split:hover {
    transform: translateY(-2px);
    box-shadow: 0 0 30px rgba(0, 212, 255, 0.5);
    text-decoration: none;
}

.icon {
    background: rgba(255, 255, 255, 0.2);
    padding: 12px 16px;
    display: flex;
    align-items: center;
}

.text-white-50 {
    color: rgba(255, 255, 255, 0.9) !important;
}

.btn-icon-split .text {
    padding: 12px 20px;
    font-weight: 600;
}

/* === INDICADOR DE MACS === */
.mac-counter {
    background: var(--surface-lighter);
    border: 1px solid var(--border);
    border-radius: 12px;
    padding: 20px;
    margin: 20px 0;
    text-align: center;
    position: relative;
    overflow: hidden;
}

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

.mac-counter h4 {
    color: var(--text-primary);
    margin-bottom: 8px;
    font-weight: 600;
}

.mac-counter .current-macs {
    font-size: 2rem;
    font-weight: 700;
    background: linear-gradient(135deg, var(--accent), var(--primary));
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    background-clip: text;
    margin: 10px 0;
}

/* === ALERTAS E AVISOS === */
.warning-alert {
    background: linear-gradient(135deg, rgba(255, 107, 157, 0.1), rgba(255, 209, 102, 0.1));
    border: 1px solid var(--primary);
    border-radius: 12px;
    padding: 16px 20px;
    margin: 20px 0;
    color: var(--text-primary);
    position: relative;
}

.warning-alert::before {
    content: '⚠️';
    position: absolute;
    left: 20px;
    top: 50%;
    transform: translateY(-50%);
    font-size: 1.5rem;
}

.warning-alert-content {
    margin-left: 50px;
}

.warning-alert strong {
    color: var(--accent);
}

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

.card {
    animation: fadeInUp 0.6s ease-out;
}

.form-group {
    animation: fadeInUp 0.8s ease-out;
}

/* === RESPONSIVIDADE === */
@media (max-width: 768px) {
    .container-fluid {
        padding: 10px;
    }
    
    .card-body {
        padding: 20px !important;
    }
    
    .form-control {
        padding: 12px 14px;
        font-size: 0.9rem;
    }
    
    .btn-success, .btn-icon-split {
        padding: 12px 20px;
        font-size: 0.9rem;
    }
    
    .h3 {
        font-size: 1.5rem;
    }
    
    .warning-alert::before {
        position: static;
        transform: none;
        margin-bottom: 8px;
        display: block;
    }
    
    .warning-alert-content {
        margin-left: 0;
    }
}

/* === GRID LAYOUT === */
.form-row {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
    gap: 20px;
    margin-bottom: 20px;
}

.form-column {
    display: flex;
    flex-direction: column;
}

/* === BADGE INFORMATIVO === */
.info-badge {
    background: linear-gradient(135deg, var(--secondary), var(--primary-dark));
    color: var(--surface);
    padding: 12px 20px;
    border-radius: 12px;
    font-size: 1rem;
    font-weight: 600;
    display: inline-flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 24px;
    box-shadow: var(--glow);
}
</style>

<div class="container-fluid">
    <h1 class="h3 mb-4 text-gray-800">
        <i class="fas fa-network-wired"></i> Criar Nova Sub Revenda
    </h1>

    <!-- Informações do Revendedor -->
    <?php
    $result = $db->query("SELECT macs FROM revenda WHERE usuario = '$seller_name'");
    $current_macs = 0;
    while ($row = $result->fetchArray()) {
        $current_macs = $row['macs'];
        break;
    }
    ?>
    
    <div class="mac-counter">
        <h4><i class="fas fa-coins"></i> Seus Créditos MACs Disponíveis</h4>
        <div class="current-macs"><?php echo $current_macs; ?> MACs</div>
        <small style="color: var(--text-muted);">Total disponível para distribuição</small>
    </div>

    <!-- Card de Criação da Sub Revenda -->
    <div class="card border-left-primary shadow h-100 card shadow mb-4">
        <div class="card-header py-3">
            <h6 class="m-0 font-weight-bold text-primary">
                <i class="fas fa-user-plus"></i> Configurações da Sub Revenda
            </h6>
        </div>
        <div class="card-body">
            <form method="post">
                <!-- Aviso Importante -->
                <div class="warning-alert">
                    <div class="warning-alert-content">
                        <strong>Atenção:</strong> O número de MACs da sub-revenda serão descontados do seu saldo atual!
                    </div>
                </div>

                <div class="form-row">
                    <!-- Coluna 1: Dados Básicos -->
                    <div class="form-column">
                        <!-- Nome -->
                        <div class="form-group">
                            <label class="control-label" for="nome">
                                <strong>Nome Completo</strong>
                            </label>
                            <div class="input-group">
                                <input class="form-control text-primary" id="nome" name="nome" 
                                       placeholder="Digite o nome completo do sub-revendedor" 
                                       type="text" value="" required/>
                            </div>
                            <small style="color: var(--text-muted); margin-top: 4px; display: block;">
                                <i class="fas fa-user"></i> Nome completo para identificação
                            </small>
                        </div>

                        <!-- Usuário -->
                        <div class="form-group">
                            <label class="control-label" for="username">
                                <strong>Usuário de Acesso</strong>
                            </label>
                            <div class="input-group">
                                <input type="text" class="form-control text-primary" name="username" 
                                       placeholder="Escolha um nome de usuário único" 
                                       id="username" required/>
                            </div>
                            <small style="color: var(--text-muted); margin-top: 4px; display: block;">
                                <i class="fas fa-at"></i> Será usado para login no sistema
                            </small>
                        </div>

                        <!-- Senha -->
                        <div class="form-group">
                            <label class="control-label" for="password">
                                <strong>Senha de Acesso</strong>
                            </label>
                            <div class="input-group">
                                <input type="text" class="form-control text-primary" name="password" 
                                       placeholder="Defina uma senha segura" 
                                       id="password" required/>
                            </div>
                            <small style="color: var(--text-muted); margin-top: 4px; display: block;">
                                <i class="fas fa-lock"></i> Senha para acesso ao painel
                            </small>
                        </div>
                    </div>

                    <!-- Coluna 2: Configurações -->
                    <div class="form-column">
                        <!-- MACs -->
                        <div class="form-group">
                            <label class="control-label" for="macs">
                                <strong>Créditos MACs</strong>
                            </label>
                            <div class="input-group">
                                <input type="number" min="1" max="<?php echo $current_macs; ?>" 
                                       class="form-control text-primary" name="macs" 
                                       placeholder="Número de MACs para distribuir" 
                                       id="macs" value="1" required
                                       style="text-align: center; font-weight: 600;"/>
                            </div>
                            <small style="color: var(--text-muted); margin-top: 4px; display: block;">
                                <i class="fas fa-coins"></i> Máximo disponível: <?php echo $current_macs; ?> MACs
                            </small>
                        </div>

                        <!-- Descrição -->
                        <div class="form-group">
                            <label class="control-label" for="Descricao">
                                <strong>Descrição/Observações</strong>
                            </label>
                            <div class="input-group">
                                <input class="form-control text-primary" id="Descricao" name="Descricao" 
                                       placeholder="Informações adicionais sobre este sub-revendedor" 
                                       type="text" value="" required/>
                            </div>
                            <small style="color: var(--text-muted); margin-top: 4px; display: block;">
                                <i class="fas fa-sticky-note"></i> Campo para observações internas
                            </small>
                        </div>
                    </div>
                </div>

                <!-- Resumo da Criação -->
                <div class="mac-counter" style="background: rgba(0, 212, 255, 0.1);">
                    <h4><i class="fas fa-calculator"></i> Resumo da Criação</h4>
                    <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px; margin-top: 15px;">
                        <div style="text-align: center;">
                            <div style="color: var(--text-secondary); font-size: 0.9rem;">MACs Atuais</div>
                            <div style="color: var(--text-primary); font-size: 1.5rem; font-weight: 700;"><?php echo $current_macs; ?></div>
                        </div>
                        <div style="text-align: center;">
                            <div style="color: var(--text-secondary); font-size: 0.9rem;">MACs a Distribuir</div>
                            <div style="color: var(--accent); font-size: 1.5rem; font-weight: 700;" id="macs-to-distribute">1</div>
                        </div>
                        <div style="text-align: center;">
                            <div style="color: var(--text-secondary); font-size: 0.9rem;">Saldo Restante</div>
                            <div style="color: var(--primary); font-size: 1.5rem; font-weight: 700;" id="remaining-macs"><?php echo $current_macs - 1; ?></div>
                        </div>
                    </div>
                </div>

                <!-- Botão de Submissão -->
                <div class="form-group text-center mt-4">
                    <button class="btn btn-success btn-icon-split" name="submit" type="submit" style="padding: 16px 40px;">
                        <span class="icon text-white-50">
                            <i class="fas fa-rocket"></i>
                        </span>
                        <span class="text" style="font-size: 1.1rem;">Criar Sub Revenda</span>
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
// Atualização dinâmica do contador de MACs
document.addEventListener('DOMContentLoaded', function() {
    const macsInput = document.getElementById('macs');
    const currentMacs = <?php echo $current_macs; ?>;
    const macsToDistribute = document.getElementById('macs-to-distribute');
    const remainingMacs = document.getElementById('remaining-macs');
    
    function updateMacsCounter() {
        let value = parseInt(macsInput.value) || 1;
        
        // Validação
        if (value < 1) value = 1;
        if (value > currentMacs) value = currentMacs;
        
        macsInput.value = value;
        macsToDistribute.textContent = value;
        remainingMacs.textContent = currentMacs - value;
        
        // Efeito visual
        macsToDistribute.style.transform = "scale(1.1)";
        remainingMacs.style.transform = "scale(1.1)";
        setTimeout(() => {
            macsToDistribute.style.transform = "scale(1)";
            remainingMacs.style.transform = "scale(1)";
        }, 200);
    }
    
    macsInput.addEventListener('input', updateMacsCounter);
    macsInput.addEventListener('change', updateMacsCounter);
    
    // Validação do formulário
    document.querySelector('form').addEventListener('submit', function(e) {
        const username = document.getElementById('username').value.trim();
        const macsValue = parseInt(macsInput.value);
        
        // Validação do username
        if (username.toUpperCase() === 'ADM') {
            e.preventDefault();
            showNotification('Username "ADM" não é permitido!', 'error');
            return;
        }
        
        // Validação dos MACs
        if (macsValue > currentMacs) {
            e.preventDefault();
            showNotification('Número de MACs excede seu saldo disponível!', 'error');
            return;
        }
        
        if (macsValue < 1) {
            e.preventDefault();
            showNotification('Número de MACs deve ser maior que zero!', 'error');
            return;
        }
        
        // Confirmação adicional
        if (!confirm('Confirma a criação desta Sub Revenda?\n\nEsta ação irá consumir ' + macsValue + ' créditos MACs do seu saldo.')) {
            e.preventDefault();
        }
    });
});

// Função de notificação
function showNotification(message, type) {
    // Implementação básica de notificação
    alert(message);
}
</script>

<?php 
include '../includes/footer2.php';
?>
</html>