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

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

// Forçamos o ID da sessão a ser uma string limpa para comparar melhor
$usuario_id = trim((string)$_SESSION['usuario_id']);

$file_usuarios = 'usuarios.json';
$file_pedidos = 'db_pedidos.json';

// LER DADOS (Tratamento para não dar erro se o arquivo não existir)
$usuarios = file_exists($file_usuarios) ? json_decode(file_get_contents($file_usuarios), true) : [];
$pedidos = file_exists($file_pedidos) ? json_decode(file_get_contents($file_pedidos), true) : [];

// BUSCAR DADOS DO USUÁRIO LOGADO (Busca mais agressiva)
$user_logado = null;
if (is_array($usuarios)) {
    foreach ($usuarios as $u) {
        $id_json = isset($u['id']) ? trim((string)$u['id']) : '';
        if ($id_json === $usuario_id) {
            $user_logado = $u;
            break;
        }
    }
}

// Se não achou no loop, criamos um padrão para não quebrar a página
if (!$user_logado) {
    $user_logado = [
        'nome' => 'Usuário',
        'saldo' => 0,
        'email' => 'Não identificado',
        'id' => $usuario_id
    ];
}

// CONTAR TOTAL DE CORRIDAS (Verifica se o cliente_id bate com o ID logado)
$total_corridas = 0;
if (is_array($pedidos)) {
    foreach ($pedidos as $p) {
        $cliente_id_pedido = isset($p['cliente_id']) ? trim((string)$p['cliente_id']) : '';
        if ($cliente_id_pedido === $usuario_id) {
            $total_corridas++;
        }
    }
}
?>

<!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>Meu Perfil | 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; }
        .profile-gradient { background: linear-gradient(180deg, #003964 0%, #0f172a 100%); }
        .glass { background: rgba(255, 255, 255, 0.03); border: 1px solid rgba(255, 255, 255, 0.05); backdrop-filter: blur(10px); }
    </style>
</head>
<body class="pb-24">

    <div class="profile-gradient h-48 w-full relative flex items-end justify-center pb-10">
        <div class="absolute top-6 right-6">
            <a href="logout.php" class="bg-red-500/20 text-red-500 px-4 py-2 rounded-xl text-[10px] font-black uppercase tracking-widest border border-red-500/20">
                Sair <i class="fas fa-sign-out-alt ml-2"></i>
            </a>
        </div>
        
        <div class="relative">
            <div class="w-24 h-24 bg-slate-800 rounded-[2rem] border-4 border-[#0f172a] shadow-2xl flex items-center justify-center overflow-hidden">
                <img src="https://ui-avatars.com/api/?name=<?php echo urlencode($user_logado['nome']); ?>&background=003964&color=fff&size=128" alt="Avatar">
            </div>
            <div class="absolute -bottom-1 -right-1 w-8 h-8 bg-emerald-500 rounded-full border-4 border-[#0f172a] flex items-center justify-center text-[10px]">
                <i class="fas fa-check text-white"></i>
            </div>
        </div>
    </div>

    <div class="px-6 -mt-4 text-center">
        <h1 class="text-xl font-black italic uppercase tracking-tighter"><?php echo htmlspecialchars($user_logado['nome']); ?></h1>
        <p class="text-slate-500 text-[10px] font-bold uppercase tracking-[0.3em] mt-1">Cliente VIP BRT Express</p>
    </div>

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

        <div class="grid grid-cols-2 gap-4">
            <div class="glass p-5 rounded-[2rem] text-center">
                <p class="text-[9px] font-black text-slate-500 uppercase tracking-widest mb-1 italic">Saldo Atual</p>
                <p class="text-lg font-black text-blue-500 italic">R$ <?php echo number_format($user_logado['saldo'] ?? 0, 2, ',', '.'); ?></p>
            </div>
            <div class="glass p-5 rounded-[2rem] text-center">
                <p class="text-[9px] font-black text-slate-500 uppercase tracking-widest mb-1 italic">Corridas</p>
                <p class="text-lg font-black text-yellow-500 italic"><?php echo $total_corridas; ?></p>
            </div>
        </div>

        <div class="glass rounded-[2.5rem] overflow-hidden">
            <div class="p-6 space-y-6">
                
                <div class="flex items-center gap-4">
                    <div class="w-10 h-10 bg-blue-500/10 rounded-xl flex items-center justify-center text-blue-500 border border-blue-500/10">
                        <i class="fas fa-envelope text-xs"></i>
                    </div>
                    <div class="text-left">
                        <p class="text-[8px] font-black text-slate-500 uppercase">E-mail de Acesso</p>
                        <p class="text-xs font-bold text-slate-200"><?php echo htmlspecialchars($user_logado['email']); ?></p>
                    </div>
                </div>

                <div class="flex items-center gap-4">
                    <div class="w-10 h-10 bg-yellow-500/10 rounded-xl flex items-center justify-center text-yellow-500 border border-yellow-500/10">
                        <i class="fas fa-id-card text-xs"></i>
                    </div>
                    <div class="text-left">
                        <p class="text-[8px] font-black text-slate-500 uppercase">ID do Usuário</p>
                        <p class="text-xs font-bold text-slate-200">#<?php echo $user_logado['id']; ?></p>
                    </div>
                </div>

                <div class="flex items-center gap-4">
                    <div class="w-10 h-10 bg-emerald-500/10 rounded-xl flex items-center justify-center text-emerald-500 border border-emerald-500/10">
                        <i class="fas fa-shield-alt text-xs"></i>
                    </div>
                    <div class="text-left">
                        <p class="text-[8px] font-black text-slate-500 uppercase">Status da Conta</p>
                        <p class="text-xs font-bold text-emerald-400 uppercase italic">Verificada</p>
                    </div>
                </div>

            </div>
        </div>

        <div class="space-y-3 pt-4">
            <a href="contacredito.php" class="w-full bg-[#003964] text-white font-black py-5 rounded-2xl flex items-center justify-center gap-3 uppercase italic text-[11px] tracking-widest border-b-4 border-blue-900 shadow-xl">
                <i class="fas fa-wallet text-yellow-500"></i> Ver Minha Carteira
            </a>
            
            <a href="https://wa.me/5521986297787" class="w-full glass text-slate-300 font-black py-5 rounded-2xl flex items-center justify-center gap-3 uppercase italic text-[11px] tracking-widest">
                <i class="fab fa-whatsapp text-emerald-500 text-lg"></i> Suporte Encomendas
            </a>
        </div>

        <p class="text-center text-[9px] text-slate-600 font-black uppercase tracking-[0.4em] pt-8 italic">
            BRT Express • Encomendas
        </p>

    </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">
            <i class="fas fa-motorcycle text-lg"></i>
            <span class="text-[8px] font-black uppercase mt-1">Pedir</span>
        </a>
        <a href="contacredito.php" class="flex flex-col items-center text-slate-500">
            <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-blue-500 scale-110">
            <i class="fas fa-user text-lg"></i>
            <span class="text-[8px] font-black uppercase mt-1">Perfil</span>
        </a>
    </div>

</body>
</html>