<?php

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$db = new SQLite3('../a/.eggziedb.db');

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

if(isset($_GET['update'])) {
    $sub_revenda_id = $_GET['update'];
    $res1 = $db->query("SELECT * FROM sub_revenda WHERE id = '$sub_revenda_id' AND registrado_por = '$seller_name'");
    while ($row1 = $res1->fetchArray()) {
        $sub_revenda_id = $row1['id'];
        $sub_revenda_nome = $row1['nome'];
        $sub_revenda_usuario = $row1['usuario'];
        $user = $sub_revenda_usuario;
        $sub_revenda_senha = $row1['senha'];
        $sub_revenda_registro = $row1['registro'];
        $sub_revenda_macs = $row1['macs'];
        $sub_revenda_extra = $row1['extra'];
    }
} else {
    echo "<script>alert('Selecione o sub revenda a ser editado!');</script>";
    echo "<script>window.location.href='sub_revenda.php';</script>";
}

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

if (isset($_POST['submit'])) {
    $usuario = $_POST['username'];
    $result = $db->query("SELECT COUNT(*) as count FROM revenda WHERE usuario = '$usuario' AND usuario <> '$sub_revenda_usuario'");
    $row = $result->fetchArray(SQLITE3_ASSOC);
    $count = $row['count'];
    
    $result = $db->query("SELECT COUNT(*) as count FROM sub_revenda WHERE usuario = '$usuario' AND usuario <> '$sub_revenda_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 {
        $result = $db->query("SELECT macs FROM revenda WHERE usuario = '$seller_name'");
        while ($row = $result->fetchArray()) {
            $macs_rev = $row['macs'];
            break;
        }
         
        $result = $db->query("SELECT macs FROM sub_revenda WHERE id = '$sub_revenda_id'");
        while ($row = $result->fetchArray()) {
            $macs_sub = $row['macs'];
            break;
        }
    
        $nome = $_POST['nome'];
        $Descricao = $_POST['Descricao'];
        $usuario = $_POST['username'];
        $senha = $_POST['password'];
        $new_macs = $_POST['macs'];
        
        if($new_macs < $macs_sub) {
             echo "<script>alert('O numero de MACs deve ser maior ou igual ao numero de MAcs atuais!');window.location.href='sub_revenda.php';</script>";
        } else {
            $dif_macs = $new_macs - $macs_sub;
            $newmac = $macs_rev - $dif_macs;
            if($dif_macs > $macs_rev) {
                echo "<script>alert('MACs insuficientes para cobrir o novo valor!');window.location.href='sub_revenda.php';</script>";
            } else {
                $db->exec("UPDATE sub_revenda SET nome = '$nome', usuario = '$usuario', senha = '$senha', macs = '$new_macs', extra = '$Descricao' WHERE id = '$sub_revenda_id' AND registrado_por = '$seller_name'");
                $db->exec("UPDATE revenda SET macs = '$newmac' WHERE usuario = '$seller_name'");
                
                // renomear arquivos conforme lógica original
                @rename("../a/rtx/Setting_$user.json", "../a/rtx/Setting_$usuario.json");
                @rename("../a/rtx/logo_filenames_$user.json", "../a/rtx/logo_filenames_$usuario.json");
                @rename("../a/rtx/image_filenames_$user.json", "../a/rtx/image_filenames_$usuario.json");
                @rename("../a/note_$user.json", "../a/note_$usuario.json");
                @rename("../api/theme_$user.json", "../api/theme_$usuario.json");
                
                $db2 = new SQLite3("../api/.adb.db");
                $db2->exec("UPDATE ads SET owner = '$usuario' WHERE owner = '$user'");
                $db3 = new SQLite3("../api/intro.db");
                $db3->exec("UPDATE intro SET owner = '$usuario' WHERE owner = '$user'");
                $db->close();
                echo "<script>window.location.href='sub_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-emerald: #00ff88;
        --neon-gold: #ffcc00;
        --dark-bg: #050a0e;
        --glass-bg: rgba(255, 255, 255, 0.02);
        --glass-border: rgba(0, 255, 136, 0.15);
    }

    /* Blindagem total contra fundo branco */
    html, body, #wrapper, #content-wrapper, #content, .container-fluid, .bg-white {
        background-color: var(--dark-bg) !important;
        color: #e0e0e0 !important;
        font-family: 'Poppins', sans-serif;
    }

    .h3 {
        font-family: 'Orbitron', sans-serif;
        color: #fff !important;
        text-transform: uppercase;
        letter-spacing: 2px;
        text-shadow: 0 0 10px rgba(0, 255, 136, 0.3);
    }

    .card-futuristic {
        background: var(--glass-bg) !important;
        backdrop-filter: blur(15px);
        border: 1px solid var(--glass-border) !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, 255, 136, 0.03) !important;
        border-bottom: 1px solid var(--glass-border) !important;
        padding: 1.2rem !important;
    }

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

    .form-control {
        background: rgba(0, 0, 0, 0.5) !important;
        border: 1px solid var(--glass-border) !important;
        color: #fff !important;
        border-radius: 8px !important;
        padding: 12px 15px !important;
        height: auto !important;
    }

    .form-control:focus {
        border-color: var(--neon-emerald) !important;
        box-shadow: 0 0 15px rgba(0, 255, 136, 0.2) !important;
    }

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

    .btn-emerald {
        background: transparent;
        border: 1px solid var(--neon-emerald);
        color: var(--neon-emerald) !important;
        font-family: 'Orbitron', sans-serif;
        padding: 12px 30px;
        border-radius: 8px;
        transition: 0.4s;
        text-transform: uppercase;
        font-size: 0.8rem;
        cursor: pointer;
    }

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

    .warning-box {
        background: rgba(255, 204, 0, 0.05);
        border-left: 4px solid var(--neon-gold);
        padding: 15px;
        border-radius: 4px;
        margin: 20px 0;
        color: #fff;
        font-size: 0.85rem;
    }
</style>

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

    <div class="row">
        <div class="col-lg-10 mx-auto">
            <div class="card card-futuristic shadow">
                <div class="card-header-futuristic">
                    <h6><i class="fas fa-user-edit mr-2"></i> Detalhes do revenda:</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><strong>Nome</strong></label>
                                    <input class="form-control" name="nome" placeholder="Digite o Nome" type="text" value="<?php echo $sub_revenda_nome;?>" required/>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group mb-4">
                                    <label><strong>MACs</strong></label>
                                    <input type="number" min="1" max="999" class="form-control" name="macs" placeholder="Número de MACs" value="<?php echo $sub_revenda_macs;?>" required/>
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group mb-4">
                                    <label><strong>Usuario</strong></label>
                                    <input type="text" class="form-control" name="username" placeholder="Digite o Usuário" value="<?php echo $sub_revenda_usuario;?>" required/>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group mb-4">
                                    <label><strong>Senha</strong></label>
                                    <input type="text" class="form-control" name="password" placeholder="Digite a Senha" value="<?php echo $sub_revenda_senha;?>" required/>
                                </div>
                            </div>
                        </div>

                        <div class="form-group mb-4">
                            <label><strong>Descricao</strong></label>
                            <input class="form-control" name="Descricao" placeholder="Digite a Descricao" type="text" value="<?php echo $sub_revenda_extra;?>" required/>
                        </div>

                        <div class="warning-box">
                            <i class="fas fa-exclamation-triangle mr-2" style="color: var(--neon-gold);"></i>
                            <strong>Aviso:</strong> A diferença de MACs será descontada automaticamente do seu saldo atual.
                        </div>

                        <div class="text-right mt-4">
                            <a href="sub_revenda.php" class="btn btn-outline-secondary mr-2" style="font-family:'Orbitron'; border-radius:8px;">Cancelar</a>
                            <button class="btn btn-emerald" name="submit" type="submit">
                                <i class="fas fa-save mr-2"></i> Salvar Alterações
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

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