<?php
// Configura o tempo de vida da sessão no servidor (60 segundos)
ini_set('session.gc_maxlifetime', 600);
session_set_cookie_params(600);

session_start();

// Define o tempo de expiração (1 minuto = 60 segundos)
$tempo_expiracao = 600; 

if (isset($_SESSION['ultimo_clique'])) {
    $inatividade = time() - $_SESSION['ultimo_clique'];
    
    if ($inatividade > $tempo_expiracao) {
        // Se passou de 1 minuto, destrói a sessão e manda para o login
        session_unset();
        session_destroy();
        header("Location: login.php?erro=sessao_expirada");
        exit;
    }
}

// Atualiza o tempo do último clique para agora
$_SESSION['ultimo_clique'] = time();
?>

<?php
header('Content-Type: text/html; charset=utf-8');

// 1. VERIFICAÇÃO DE LOGIN
if (!isset($_SESSION['usuario_id'])) { header("Location: login.php"); exit; }

$usuario_id = $_SESSION['usuario_id'];
$file_usuarios = 'usuarios.json';
$file_pedidos = 'db_pedidos.json';
$file_creditos = 'creditos.json'; // O NOVO BANCO DE SALDOS

$usuarios = json_decode(file_get_contents($file_usuarios), true) ?: [];
$pedidos = json_decode(file_get_contents($file_pedidos), true) ?: [];

// --- CORREÇÃO: BUSCA O SALDO REAL NO NOVO BANCO creditos.json ---
$creditos_db = file_exists($file_creditos) ? json_decode(file_get_contents($file_creditos), true) : [];
$meu_saldo_real = floatval($creditos_db[trim((string)$usuario_id)] ?? 0.00);

// Localiza o usuário logado para pegar informações de perfil (nome, etc)
$user_logado = null;
foreach ($usuarios as $u) {
    if (trim((string)$u['id']) == trim((string)$usuario_id)) { $user_logado = $u; break; }
}

// Filtra apenas os pedidos deste cliente para o histórico de gastos
$meus_pedidos = array_filter($pedidos, function($p) use ($usuario_id) {
    $id_do_pedido = $p['cliente_id'] ?? $p['usuario_id'] ?? null;
    return ($id_do_pedido !== null && trim((string)$id_do_pedido) == trim((string)$usuario_id));
});

// Ordena para que os gastos mais recentes apareçam primeiro
$meus_pedidos = array_reverse($meus_pedidos);
?>

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <title>Minha Carteira</title>
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;700;900&display=swap');
        body { font-family: 'Inter', sans-serif; background-color: #0f172a; color: white; }
        .card-glass { background: rgba(30, 41, 59, 0.6); backdrop-filter: blur(10px); border: 1px solid rgba(255,255,255,0.05); }
        .animate-float { animation: float 3s ease-in-out infinite; }
        @keyframes float { 0%, 100% { transform: translateY(0); } 50% { transform: translateY(-5px); } }
    </style>
</head>
<body class="pb-32">

    <nav class="p-6 flex justify-between items-center bg-slate-900/50 border-b border-white/5">
        <div>
            <p class="text-[9px] font-black uppercase text-slate-500 tracking-widest">Sua Conta BRT ENTREGAS </p>
            <h1 class="text-lg font-black italic uppercase text-blue-500">Financeiro</h1>
        </div>
        <div class="w-10 h-10 bg-[#003964] rounded-xl flex items-center justify-center border border-white/10 text-yellow-500 shadow-lg">
            <i class="fas fa-wallet"></i>
        </div>
    </nav>

    <div class="p-6 max-w-md mx-auto">

        <div class="bg-gradient-to-br from-[#003964] to-blue-900 p-8 rounded-[2.5rem] shadow-2xl relative overflow-hidden border-b-4 border-blue-400/20">
            <div class="relative z-10">
                <p class="text-[9px] font-black uppercase tracking-widest text-blue-200/50">Saldo Disponível</p>
                
                <div class="flex items-center justify-between mt-2">
                    <h2 class="text-4xl font-black italic tracking-tighter">
                        R$ <?php echo number_format($meu_saldo_real, 2, ',', '.'); ?>
                    </h2>
                    
                    <button onclick="abrirModalPix()" class="bg-yellow-500 text-[#003964] px-4 py-3 rounded-2xl flex items-center gap-2 hover:bg-white transition-all active:scale-90 shadow-xl shadow-yellow-500/20 animate-float">
                        <i class="fab fa-pix text-lg"></i>
                        <span class="text-[10px] font-bold uppercase italic tracking-tighter leading-none">Recarregar<br>via PIX</span>
                    </button>
                </div>

                <div class="mt-6 flex gap-2">
                    <span class="bg-white/10 px-3 py-1 rounded-lg text-[8px] font-black uppercase text-blue-200 tracking-widest border border-white/5 italic">
                        ID: #<?php echo $usuario_id; ?>
                    </span>
                    <span class="px-3 py-1 rounded-lg text-[8px] font-black uppercase tracking-widest border italic <?php echo ($meu_saldo_real > 0) ? 'bg-emerald-500/20 text-emerald-400 border-emerald-500/10' : 'bg-red-500/20 text-red-400 border-red-500/10'; ?>">
                        <?php echo ($meu_saldo_real > 0) ? 'Crédito Ativo' : 'Saldo Zerado - Recarregue'; ?>
                    </span>
                </div>
            </div>
            <div class="absolute -bottom-10 -right-10 w-40 h-40 bg-white/5 rounded-full blur-3xl"></div>
        </div>

        <div class="mt-10">
            <div class="flex justify-between items-end mb-4 px-2">
                <h3 class="text-[10px] font-black uppercase italic tracking-widest text-slate-500">Histórico de Gastos</h3>
                <span class="text-[9px] text-slate-600 font-bold uppercase italic">Últimas Atividades</span>
            </div>

            <div class="space-y-3">
                <?php if(empty($meus_pedidos)): ?>
                    <div class="p-10 text-center card-glass rounded-[2rem] border-dashed border-white/10">
                        <i class="fas fa-receipt text-slate-700 text-3xl mb-3"></i>
                        <p class="text-[10px] font-bold text-slate-500 uppercase italic">Nenhuma corrida registrada em seu nome.</p>
                    </div>
                <?php else: ?>
                    <?php foreach($meus_pedidos as $p): ?>
                    <div class="card-glass p-5 rounded-[2.5rem] flex items-center justify-between border-l-4 border-l-red-500/50 shadow-lg">
                        <div class="flex items-center gap-4">
                            <div class="w-10 h-10 bg-red-500/10 rounded-2xl flex items-center justify-center border border-red-500/10">
                                <i class="fas fa-motorcycle text-red-500 text-xs"></i>
                            </div>
                            <div>
                                <h4 class="text-[11px] font-black uppercase text-white tracking-tight italic leading-none">Corrida BRT</h4>
                                <p class="text-[9px] text-slate-500 font-bold uppercase mt-1 italic"><?php echo $p['data'] ?? '---'; ?> • <?php echo $p['hora'] ?? ''; ?></p>
                                <p class="text-[8px] text-blue-400/60 font-bold uppercase italic mt-1 truncate max-w-[120px]">Para: <?php echo $p['ponto_entrega'] ?? $p['destino'] ?? 'Destino'; ?></p>
                            </div>
                        </div>
                        <div class="text-right">
                            <p class="text-sm font-black text-white italic">- R$ <?php echo number_format($p['valor'] ?? 5.00, 2, ',', '.'); ?></p>
                            <span class="bg-blue-500/10 text-blue-400 text-[7px] font-black px-2 py-0.5 rounded-full uppercase italic border border-blue-500/10">Confirmado</span>
                        </div>
                    </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <div id="modalPix" class="fixed inset-0 bg-slate-950/90 backdrop-blur-md z-[100] hidden flex items-center justify-center p-6">
        <div class="bg-white rounded-[3rem] w-full max-w-sm p-10 text-center relative shadow-2xl border-b-[12px] border-[#003964]">
            <button onclick="fecharModalPix()" class="absolute top-6 right-6 text-slate-300 hover:text-slate-900 transition-all"><i class="fas fa-times text-xl"></i></button>
            <div class="w-16 h-16 bg-emerald-100 rounded-3xl flex items-center justify-center mx-auto mb-6">
                <i class="fab fa-pix text-emerald-600 text-3xl"></i>
            </div>
            <h3 class="text-[#003964] text-xl font-black uppercase italic tracking-tighter">Recarga via PIX</h3>
            <p class="text-slate-400 text-[10px] font-bold uppercase tracking-widest mt-1 mb-6">BRT SOLUÇÕES ENTREGAS</p>
            <div class="bg-slate-100 p-4 rounded-3xl mb-6 border-2 border-dashed border-slate-200">
                <img src="https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=65384278000155" alt="QR Code" class="mx-auto rounded-xl">
            </div>
            <button onclick="copiarChave()" class="w-full bg-[#003964] text-white font-black py-4 rounded-2xl uppercase italic text-[11px] tracking-widest active:scale-95 transition-all shadow-xl">
                <i class="fas fa-copy mr-2"></i> Copiar Chave PIX CNPJ
            </button>
        </div>
    </div>

    <nav class="fixed bottom-0 left-0 right-0 bg-slate-900/90 backdrop-blur-xl border-t border-white/10 px-8 py-4 flex justify-between items-center z-50 rounded-t-[2.5rem] shadow-2xl">
        <a href="index.php" class="flex flex-col items-center group">
            <i class="fas fa-home text-slate-500 group-hover:text-blue-500 transition-colors"></i>
            <span class="text-[8px] font-black uppercase mt-1 text-slate-500">Início</span>
        </a>
        <a href="acompanhamento.php" class="flex flex-col items-center group">
            <i class="fas fa-map-marker-alt text-slate-500 group-hover:text-blue-500"></i>
            <span class="text-[8px] font-black uppercase mt-1 text-slate-500">Monitorar</span>
        </a>
        <a href="contacredito.php" class="flex flex-col items-center scale-125">
            <i class="fas fa-wallet text-blue-500"></i>
            <span class="text-[8px] font-black uppercase mt-1 text-blue-500">Carteira</span>
        </a>
        <a href="perfil.php" class="flex flex-col items-center group">
            <i class="fas fa-user text-slate-500 group-hover:text-blue-500"></i>
            <span class="text-[8px] font-black uppercase mt-1 text-slate-500">Perfil</span>
        </a>
    </nav>

    <script>
        function abrirModalPix() { document.getElementById('modalPix').classList.remove('hidden'); }
        function fecharModalPix() { document.getElementById('modalPix').classList.add('hidden'); }
        function copiarChave() {
            const chave = "65384278000155"; 
            navigator.clipboard.writeText(chave);
            alert("Chave PIX copiada!");
        }

        // Monitoramento de Inatividade (Redireciona após 1 minuto)
        (function() {
            let tempoInatividade;
            const resetarTimer = () => {
                clearTimeout(tempoInatividade);
                tempoInatividade = setTimeout(() => {
                    window.location.href = 'login.php?erro=inatividade';
                }, 60000);
            };
            ['mousedown', 'mousemove', 'keypress', 'scroll', 'touchstart'].forEach(evento => {
                document.addEventListener(evento, resetarTimer, true);
            });
            resetarTimer();
        })();
    </script>

</body>
</html>