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

include('../api/conexao_rev.php'); 

$id_rev = $_SESSION['rev_logado'];

// Busca os dados atuais da revenda
$sql = $conn_rev->query("SELECT login_rev, senha_rev FROM dados_rev WHERE id_rev = '$id_rev'");
$dados = $sql->fetch_assoc();

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

$status = "";
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_pass'])) {
    if (!isset($_POST['token']) || !hash_equals($_SESSION['rev_token'], $_POST['token'])) {
        exit('Token de segurança inválido.');
    }

    $nova_senha = $_POST['nova_senha'];
    $confirma_senha = $_POST['confirma_senha'];

    if ($nova_senha === $confirma_senha) {
        // Atualiza apenas a senha no banco de dados
        $update = $conn_rev->query("UPDATE dados_rev SET senha_rev = '$nova_senha' WHERE id_rev = '$id_rev'");
        if ($update) {
            $status = "success";
        } else {
            $status = "error";
        }
    } else {
        $status = "mismatch";
    }
}
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Segurança - Alterar Senha</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <style>
        /* DESIGN PREMIUM DARK - PADRÃO DO APP */
        * { box-sizing: border-box; }
        html, body { 
            background-color: #020617 !important; 
            color: #e2e8f0 !important;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            margin: 0; padding: 0;
        }
        .container-fluid { padding: 15px !important; }
        .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; max-width: 500px; margin-left: auto; margin-right: auto; display: flex;
        }
        .premium-card {
            background: #070e1b !important; border: 1px solid #1e293b !important;
            border-radius: 20px; padding: 25px; box-shadow: 0 10px 25px rgba(0,0,0,0.3);
            max-width: 500px; margin: 0 auto; width: 100%;
        }
        .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: #f43f5e; font-size: 0.8rem; margin-top: 4px; font-weight: 600; }
        
        label { display: block; color: #64748b; font-size: 0.7rem; font-weight: 800; margin-bottom: 8px; text-transform: uppercase; letter-spacing: 1px; }
        
        /* Estilo para campo bloqueado */
        .input-blocked {
            width: 100%; background: #0f172a !important; border: 1px solid #1e293b !important;
            color: #475569 !important; padding: 15px; border-radius: 12px; font-size: 0.95rem; margin-bottom: 20px;
            cursor: not-allowed; opacity: 0.7; font-weight: 600;
        }

        .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;
        }
        .form-input:focus { border-color: #f43f5e !important; outline: none; box-shadow: 0 0 0 2px rgba(244, 63, 94, 0.1); }

        .btn-premium-save {
            width: 100%; background: #f43f5e !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(244, 63, 94, 0.2); transition: 0.3s;
        }
        .btn-premium-save:hover { background: #e11d48 !important; }
        .btn-premium-save:active { transform: scale(0.98); }

        .info-box {
            background: rgba(244, 63, 94, 0.05); border: 1px solid rgba(244, 63, 94, 0.1);
            padding: 15px; border-radius: 12px; margin-bottom: 20px; display: flex; align-items: center; gap: 12px;
        }
        .info-box i { color: #f43f5e; font-size: 1.2rem; }
        .info-box span { font-size: 0.75rem; color: #94a3b8; line-height: 1.4; }
    </style>
</head>
<body>

<div class="container-fluid">
    <a href="dashboard_rev.php" class="btn-back-nav"><i class="fas fa-chevron-left"></i> Voltar ao Painel</a>

    <div class="premium-card">
        <div class="card-header-premium">
            <h1>Segurança</h1>
            <p><i class="fas fa-lock mr-1"></i> Alteração de Credenciais</p>
        </div>

        <div class="info-box">
            <i class="fas fa-user-shield"></i>
            <span>Por motivos de segurança, o seu nome de usuário não pode ser alterado através deste painel.</span>
        </div>

        <form method="post">
            <input type="hidden" name="token" value="<?php echo $_SESSION['rev_token']; ?>">
            
            <label>Usuário (Bloqueado)</label>
            <input class="input-blocked" type="text" value="<?php echo $dados['login_rev']; ?>" readonly>

            <label>Nova Senha</label>
            <input class="form-input" type="password" name="nova_senha" placeholder="Digite a nova senha" required>

            <label>Confirmar Nova Senha</label>
            <input class="form-input" type="password" name="confirma_senha" placeholder="Repita a nova senha" required>

            <button type="submit" name="update_pass" class="btn-premium-save">
                <i class="fas fa-save"></i> Atualizar Senha
            </button>
        </form>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
    $(document).ready(function() {
        const status = "<?php echo $status; ?>";
        
        if (status === "success") {
            Swal.fire({
                icon: 'success',
                title: 'Senha Atualizada!',
                text: 'Sua nova senha já está em vigor.',
                background: '#070e1b',
                color: '#fff',
                confirmButtonColor: '#f43f5e'
            });
        } else if (status === "mismatch") {
            Swal.fire({
                icon: 'error',
                title: 'Erro!',
                text: 'As senhas digitadas não coincidem.',
                background: '#070e1b',
                color: '#fff',
                confirmButtonColor: '#f43f5e'
            });
        } else if (status === "error") {
            Swal.fire({
                icon: 'error',
                title: 'Ops!',
                text: 'Ocorreu um erro ao atualizar no banco de dados.',
                background: '#070e1b',
                color: '#fff'
            });
        }
    });
</script>
</body>
</html>
