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

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

$usuario_id = $_SESSION['usuario_id'];
$file_usuarios = 'usuarios.json';
$file_pedidos = 'db_pedidos.json';

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

// BUSCAR DADOS DO USUÁRIO LOGADO (SALDO ATUAL)
$user_logado = null;
foreach ($usuarios as $u) {
    if ($u['id'] == $usuario_id) {
        $user_logado = $u;
        break;
    }
}

// FILTRAR APENAS OS PEDIDOS DESTE CLIENTE
$meus_pedidos = array_filter($pedidos, function($p) use ($usuario_id) {
    return $p['cliente_id'] == $usuario_id;
});

// CALCULAR TOTAL DE GASTOS (DESCONTOS)
$total_gastos = 0;
foreach ($meus_pedidos as $mp) {
    $total_gastos += (float)($mp['valor'] ?? 0);
}
?>

<!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 | BRT Express</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.7); backdrop-filter: blur(10px); border: 1px solid rgba(255,255,255,0.05); }
    </style>
</head>
<body class="pb-24">

    <nav class="p-6 flex justify-between items-center border-b border-white/5 bg-slate-900/50">
        <div>
            <p class="text-[10px] font-black uppercase text-slate-500 tracking-[0.2em]">Bem-vindo de volta,</p>
            <h1 class="text-lg font-black italic uppercase text-blue-500"><?php echo explode(' ', $user_logado['nome'])[0]; ?></h1>
        </div>
        <div class="w-12 h-12 bg-[#003964] rounded-2xl flex items-center justify-center border border-blue-400/20">
            <i class="fas fa-user text-yellow-500"></i>
        </div>
    </nav>

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

        <div class="relative bg-gradient-to-br from-[#003964] to-blue-900 p-8 rounded-[3rem] shadow-2xl overflow-hidden mb-8 border-b-4 border-blue-400/30">
            <div class="absolute -top-10 -right-10 w-32 h-32 bg-white/10 rounded-full blur-3xl"></div>
            
            <div class="relative z-10">
                <div class="flex justify-between items-start">
                    <p class="text-[10px] font-black uppercase tracking-widest text-blue-200/60">Saldo em Carteira</p>
                    <i class="fas fa-bolt text-yellow-400 animate-pulse"></i>
                </div>
                <h2 class="text-4xl font-black italic mt-2 tracking-tighter">
                    R$ <?php echo number_format($user_logado['saldo'] ?? 0, 2, ',', '.'); ?>
                </h2>
                <div class="mt-6 flex gap-3">
                    <div class="bg-black/20 px-4 py-2 rounded-xl border border-white/5">
                        <p class="text-[8px] font-bold text-blue-300 uppercase">Utilizado</p>
                        <p class="text-xs font-black">R$ <?php echo number_format($total_gastos, 2, ',', '.'); ?></p>
                    </div>
                    <div class="bg-black/20 px-4 py-2 rounded-xl border border-white/5">
                        <p class="text-[8px] font-bold text-emerald-400 uppercase">Status</p>
                        <p class="text-xs font-black uppercase italic"><?php echo ($user_logado['saldo'] > 0) ? 'Ativo' : 'Sem Saldo'; ?></p>
                    </div>
                </div>
            </div>
        </div>

        <div class="mb-6 flex justify-between items-center px-2">
            <h3 class="text-xs font-black uppercase italic tracking-widest text-slate-400">Últimos Descontos</h3>
            <span class="text-[10px] font-bold text-blue-500 uppercase">Recentes</span>
        </div>

        <div class="space-y-4">
            <?php if(empty($meus_pedidos)): ?>
                <div class="card-glass p-10 rounded-[2.5rem] text-center border-dashed">
                    <i class="fas fa-history text-slate-700 text-3xl mb-3"></i>
                    <p class="text-slate-500 text-[10px] font-bold uppercase italic">Nenhuma movimentação ainda.</p>
                </div>
            <?php else: ?>
                <?php foreach(array_reverse($meus_pedidos) as $p): ?>
                <div class="card-glass p-5 rounded-[2rem] flex items-center justify-between group hover:bg-slate-800 transition-all">
                    <div class="flex items-center gap-4">
                        <div class="w-10 h-10 bg-red-500/10 rounded-xl flex items-center justify-center border border-red-500/20">
                            <i class="fas fa-arrow-down text-red-500 text-xs"></i>
                        </div>
                        <div>
                            <h4 class="text-[11px] font-black uppercase text-white tracking-tight">Entrega realizada</h4>
                            <p class="text-[9px] text-slate-500 font-bold uppercase"><?php echo date('d/m • H:i', strtotime($p['data'] ?? 'now')); ?></p>
                        </div>
                    </div>
                    <div class="text-right">
                        <p class="text-sm font-black text-white italic">- R$ <?php echo number_format($p['valor'] ?? 5, 2, ',', '.'); ?></p>
                        <p class="text-[8px] font-black text-slate-600 uppercase italic"><?php echo $p['status']; ?></p>
                    </div>
                </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>

        <div class="mt-8 p-6 bg-yellow-500/10 rounded-[2rem] border border-yellow-500/20 flex items-center gap-4">
            <div class="text-yellow-500 text-xl"><i class="fas fa-info-circle"></i></div>
            <p class="text-[10px] font-bold text-yellow-200/80 uppercase leading-relaxed">
                Precisa de mais créditos? Entre em contato com a <span class="text-yellow-500 font-black">OABCG</span> para recarregar via PIX.
            </p>
        </div>

    </div>


    <div class="fixed bottom-0 left-0 right-0 bg-slate-900/90 backdrop-blur-lg border-t border-white/5 p-4 flex justify-around items-center z-50">
        <a href="index.php" class="flex flex-col items-center text-slate-500 hover:text-blue-500 transition-all">
            <i class="fas fa-motorcycle text-lg"></i>
            <span class="text-[8px] font-black uppercase mt-1">Pedir</span>
        </a>
        <a href="acompanhamento.php" class="flex flex-col items-center text-blue-500 scale-110">
            <i class="fas fa-wallet text-lg"></i>
            <span class="text-[8px] font-black uppercase mt-1">Carteira</span>
        </a>
        <a href="perfil.php" class="flex flex-col items-center text-slate-500 hover:text-blue-500 transition-all">
            <i class="fas fa-cog text-lg"></i>
            <span class="text-[8px] font-black uppercase mt-1">Ajustes</span>
        </a>
    </div>

</body>
</html>