<?php 
session_start();
if (!isset($_SESSION['id'])) {
    header("Location: login.php");
    exit();
}

include 'auth.php';

if (!isset($_SESSION['admin_token'])) {
    $_SESSION['admin_token'] = bin2hex(random_bytes(32));
}

$db = new SQLite3("./api/.anspanel.db");
$res = $db->prepare("SELECT * FROM USERS WHERE id = :id");
$res->bindValue(':id', $_GET["update"], SQLITE3_TEXT);
$result = $res->execute();
$row = $result->fetchArray();

if (!$row) {
    header("Location: stores.php");
    exit();
}

$id = $row["id"];
$name = $row["NAME"];
$mac_amount = $row["mac_amount"];
$username = $row["USERNAME"];
$current_password = $row["PASSWORD"];

if (isset($_POST["submit"])) {
    if (!isset($_POST['token']) || !hash_equals($_SESSION['admin_token'], $_POST['token'])) {
        header("Location: login.php");
        exit(); 
    }

    $name_up = $_POST['name'];
    $user_up = $_POST['username'];
    $mac_up = $_POST['mac_amount'];
    $pass_up = !empty($_POST["password"]) ? $_POST["password"] : $current_password;

    $stmt = $db->prepare("UPDATE USERS SET NAME = :name, USERNAME = :user, PASSWORD = :pass, mac_amount = :mac WHERE id = :id");
    $stmt->bindValue(':name', $name_up, SQLITE3_TEXT);
    $stmt->bindValue(':user', $user_up, SQLITE3_TEXT);
    $stmt->bindValue(':pass', $pass_up, SQLITE3_TEXT);
    $stmt->bindValue(':mac', $mac_up, SQLITE3_INTEGER);
    $stmt->bindValue(':id', $id, SQLITE3_INTEGER);
    
    if ($stmt->execute()) {
        $db->close();
        header("Location: stores.php?status=updated");
        exit();
    }
}

include "includes/header.php";
?>

<style>
    /* RESET E FUNDO TOTAL DARK */
    html, body, .wrapper, .main-panel, .content, .container-fluid { 
        background-color: #020617 !important; 
        color: #e2e8f0 !important;
        overflow-x: hidden;
    }

    /* OCULTAR ELEMENTOS DO HEADER ORIGINAL */
    .lua-icon, .fa-moon, .fa-sun, .navbar, #dark-mode-switch { display: none !important; }

    .container-fluid { padding: 15px !important; }

    /* BOTÃO VOLTAR */
    .btn-back-nav {
        display: inline-flex;
        align-items: center;
        gap: 8px;
        color: #64748b;
        text-decoration: none !important;
        font-size: 0.85rem;
        font-weight: 600;
        margin-bottom: 20px;
    }

    /* CARD PREMIUM */
    .premium-card {
        background: #070e1b !important;
        border: 1px solid #1e293b !important;
        border-radius: 20px;
        padding: 20px;
        box-shadow: 0 10px 25px rgba(0,0,0,0.3);
        box-sizing: border-box;
    }

    .card-header-premium { 
        margin-bottom: 25px; 
        border-bottom: 1px solid rgba(255,255,255,0.05); 
        padding-bottom: 15px; 
    }
    .card-header-premium h1 { font-size: 1.4rem; font-weight: 800; color: #fff; margin: 0; }
    .card-header-premium p { color: #3b82f6; font-size: 0.8rem; margin-top: 4px; font-weight: 600; }

    /* ESTILO FORMULÁRIO */
    label { 
        display: block; color: #3b82f6; font-size: 0.7rem; font-weight: 800; 
        margin-bottom: 8px; text-transform: uppercase; letter-spacing: 1px;
    }

    .form-input { 
        width: 100%; background: #0f172a !important; border: 1px solid #1e293b !important; 
        color: #fff !important; padding: 15px; border-radius: 12px; font-size: 0.95rem; margin-bottom: 20px; 
        transition: 0.3s;
        box-sizing: border-box; /* CORREÇÃO DE LARGURA */
    }
    .form-input:focus { border-color: #3b82f6 !important; outline: none; box-shadow: 0 0 10px rgba(59, 130, 246, 0.1); }

    /* CONTAINER SENHA COM OLHO */
    .password-wrapper { position: relative; width: 100%; box-sizing: border-box; }
    .toggle-pass {
        position: absolute; right: 15px; top: 15px; color: #475569;
        cursor: pointer; z-index: 10; font-size: 1.1rem;
    }

    /* BOTÕES */
    .row-buttons { display: grid; grid-template-columns: 1fr; gap: 12px; margin-top: 10px; box-sizing: border-box; }
    
    .btn-premium-save {
        width: 100%; /* Garante preenchimento da coluna */
        background: #3b82f6 !important; color: #fff !important;
        padding: 18px; border-radius: 14px; font-weight: 800; text-transform: uppercase;
        border: none; cursor: pointer; display: flex; align-items: center; justify-content: center; gap: 10px;
        box-shadow: 0 4px 15px rgba(59, 130, 246, 0.2); transition: 0.3s;
        box-sizing: border-box; /* CORREÇÃO DE LARGURA */
    }
    
    .btn-premium-cancel {
        width: 100%; /* Garante preenchimento da coluna */
        background: #1e293b !important; color: #94a3b8 !important;
        padding: 18px; border-radius: 14px; font-weight: 800; text-transform: uppercase;
        text-align: center; text-decoration: none !important;
        box-sizing: border-box; /* CORREÇÃO DE LARGURA */
    }

    .btn-premium-save:active { transform: scale(0.98); }

    @media (min-width: 768px) {
        .row-buttons { grid-template-columns: 2fr 1fr; }
    }
</style>

<div class="container-fluid">
    <a href="stores.php" class="btn-back-nav">
        <i class="fas fa-chevron-left"></i> Voltar para Revendas
    </a>

    <div class="premium-card">
        <div class="card-header-premium">
            <h1>Editar Revendedor</h1>
            <p><i class="fas fa-user-cog mr-1"></i> Configurações de acesso e limites</p>
        </div>

        <form method="post" id="formUpdate">
            <input type="hidden" name="token" value="<?php echo $_SESSION['admin_token']; ?>">
            
            <label>Nome da Revenda / Loja</label>
            <input type="text" class="form-input" name="name" value="<?=$name?>" placeholder="Ex: Master IPTV" required>

            <label>Quantidade de MACs (Limite)</label>
            <input type="number" class="form-input" name="mac_amount" min="1" value="<?=$mac_amount?>" required>

            <label>Usuário de Acesso</label>
            <input type="text" class="form-input" name="username" value="<?=$username?>" required>

            <label>Nova Senha</label>
            <div class="password-wrapper">
                <input type="password" class="form-input" name="password" id="password" placeholder="Deixe vazio para manter a atual">
                <i class="fas fa-eye toggle-pass" id="eyeIcon"></i>
            </div>

            <div class="row-buttons">
                <button type="submit" name="submit" class="btn-premium-save">
                    <i class="fas fa-check-circle"></i> Atualizar Dados
                </button>
                <a href="stores.php" class="btn-premium-cancel">Cancelar</a>
            </div>
        </form>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
    document.getElementById('eyeIcon').addEventListener('click', function () {
        const passwordInput = document.getElementById('password');
        const type = passwordInput.getAttribute('type') === 'password' ? 'text' : 'password';
        passwordInput.setAttribute('type', type);
        this.classList.toggle('fa-eye');
        this.classList.toggle('fa-eye-slash');
        if(type === 'text') {
            this.style.color = '#3b82f6';
        } else {
            this.style.color = '#475569';
        }
    });
</script>

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