<?php
session_start();

// --- 1. CONFIGURAÇÕES DE ARQUIVOS ---
$file_pedidos = 'db_pedidos.json';
$file_usuarios = 'usuarios.json';
$file_online = 'usuarios_online.json';

// Verificação de Login
if (!isset($_SESSION['usuario_id'])) { header("Location: login.php"); exit; }
$usuario_id = $_SESSION['usuario_id'];

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

// --- 2. LÓGICA DE DÉBITO (QUANDO O CLIENTE SOLICITA) ---
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['solicitar_corrida'])) {
    $valor_corrida = (float)($_POST['valor_total'] ?? 10.00);
    $debito_sucesso = false;

    foreach ($usuarios as &$u) {
        if ($u['id'] == $usuario_id) {
            if ($u['saldo'] >= $valor_corrida) {
                $u['saldo'] -= $valor_corrida;
                $debito_sucesso = true;
                break;
            } else {
                $erro_saldo = "Saldo insuficiente! Recarregue via PIX.";
            }
        }
    }

    if ($debito_sucesso) {
        file_put_contents($file_usuarios, json_encode($usuarios, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
        
        $novo_id = uniqid();
        $novo_pedido = [
            'id' => $novo_id,
            'cliente_id' => $usuario_id,
            'valor' => $valor_corrida,
            'status' => 'Procurando Entregador...',
            'data' => date('Y-m-d H:i:s'),
            'estacao' => $_POST['estacao'] ?? 'S/N'
        ];
        $pedidos[] = $novo_pedido;
        file_put_contents($file_pedidos, json_encode($pedidos, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
        $_SESSION['pedido_ativo_id'] = $novo_id;
        header("Location: acompanhamento.php?id=".$novo_id);
        exit;
    }
}

// --- 3. TRAVA E RECUPERAÇÃO DO PEDIDO ATIVO ---
if (isset($_GET['id'])) { $_SESSION['pedido_ativo_id'] = $_GET['id']; }
$id_atual = $_SESSION['pedido_ativo_id'] ?? '';
$pedido = null;
foreach ($pedidos as $p) { if ($p['id'] == $id_atual) { $pedido = $p; break; } }

// Buscar Saldo Atual para exibição
$user_logado = null;
foreach ($usuarios as $u) { if ($u['id'] == $usuario_id) { $user_logado = $u; break; } }

// --- 4. FINALIZAÇÃO PELO CLIENTE ---
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['acao']) && $_POST['acao'] == 'concluir') {
    foreach ($pedidos as &$p) {
        if ($p['id'] == $id_atual) {
            $p['status'] = "Viagem Concluída";
            break;
        }
    }
    file_put_contents($file_pedidos, json_encode($pedidos, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
    unset($_SESSION['pedido_ativo_id']);
    header("Location: acompanhamento.php");
    exit;
}

$status = $pedido['status'] ?? 'Nenhum pedido ativo';
$procurando = (stripos($status, 'Procurando') !== false);
$concluido = (stripos($status, 'Conclu') !== false);
?>

<!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>Carteira & Status | BRT Express</title>
    <style>
        body { background-color: #0f172a; font-family: 'Inter', sans-serif; color: white; }
        .radar-ring { position: absolute; border: 2px solid #3b82f6; border-radius: 50%; opacity: 0; animation: pulse 3s infinite; }
        @keyframes pulse { 0% { transform: scale(0.1); opacity: 0.8; } 100% { transform: scale(1.5); opacity: 0; } }
    </style>
</head>
<body class="pb-24">

    <div class="max-w-md mx-auto p-6">
        
        <div class="bg-gradient-to-br from-[#003964] to-blue-900 p-6 rounded-[2.5rem] shadow-2xl mb-8 border-b-4 border-blue-400/20">
            <p class="text-[10px] font-black uppercase tracking-widest text-blue-200/50">Meu Saldo BRT</p>
            <div class="flex items-center justify-between mt-2">
                <h2 class="text-3xl font-black italic">R$ <?php echo number_format($user_logado['saldo'] ?? 0, 2, ',', '.'); ?></h2>
                <button onclick="document.getElementById('modalPix').classList.remove('hidden')" class="bg-yellow-500 text-[#003964] px-4 py-2 rounded-2xl text-[10px] font-black uppercase italic shadow-lg animate-bounce">
                    <i class="fab fa-pix"></i> Recarregar
                </button>
            </div>
        </div>

        <?php if($pedido): ?>
        <div class="bg-white rounded-[2.5rem] overflow-hidden shadow-xl text-slate-900 mb-6">
            <?php if($procurando): ?>
                <div class="relative h-48 bg-slate-900 flex items-center justify-center">
                    <div class="radar-ring w-64 h-64"></div>
                    <div class="z-10 text-center">
                        <i class="fas fa-motorcycle text-blue-500 text-3xl animate-pulse"></i>
                        <p class="text-blue-400 font-black text-[10px] uppercase mt-4">Procurando Entregador...</p>
                    </div>
                </div>
            <?php else: ?>
                <div class="p-6 text-center <?php echo $concluido ? 'bg-green-500 text-white' : 'bg-blue-600 text-white'; ?>">
                    <h3 class="font-black uppercase italic text-lg"><?php echo $status; ?></h3>
                </div>
            <?php endif; ?>

            <div class="p-6">
                <div class="flex justify-between items-center mb-6 bg-slate-50 p-4 rounded-2xl border border-slate-100">
                    <div>
                        <p class="text-[9px] font-black text-slate-400 uppercase">Valor do Serviço</p>
                        <p class="text-sm font-black">R$ <?php echo number_format($pedido['valor'], 2, ',', '.'); ?></p>
                    </div>
                    <div class="text-right">
                        <p class="text-[9px] font-black text-slate-400 uppercase">Estação</p>
                        <p class="text-sm font-black uppercase italic"><?php echo $pedido['estacao']; ?></p>
                    </div>
                </div>

                <?php if(!$concluido && !$procurando): ?>
                    <form method="POST">
                        <input type="hidden" name="acao" value="concluir">
                        <button type="submit" class="w-full bg-green-500 text-white font-black py-4 rounded-2xl shadow-lg uppercase text-xs tracking-widest border-b-4 border-green-700 active:scale-95 transition-all">
                            <i class="fas fa-check-circle mr-2"></i> CONFIRMAR RECEBIMENTO
                        </button>
                    </form>
                <?php elseif($concluido): ?>
                    <div class="text-center">
                        <p class="text-green-600 font-black uppercase text-xs">Corrida Finalizada!</p>
                        <a href="index.php" class="inline-block mt-2 text-blue-600 font-bold text-xs border-b border-blue-600">Fazer novo pedido</a>
                    </div>
                <?php endif; ?>
            </div>
        </div>
        <?php else: ?>
            <div class="text-center p-10 bg-slate-800/50 rounded-[2.5rem] border border-dashed border-slate-700">
                <i class="fas fa-ghost text-slate-600 text-3xl mb-4"></i>
                <p class="text-xs font-bold text-slate-500 uppercase tracking-widest">Nenhuma corrida ativa no momento.</p>
            </div>
        <?php endif; ?>

    </div>

    <div id="modalPix" class="fixed inset-0 bg-black/90 backdrop-blur-sm z-[100] hidden flex items-center justify-center p-6">
        <div class="bg-white text-slate-900 rounded-[3rem] w-full max-w-sm p-8 text-center relative border-b-[10px] border-[#003964]">
            <button onclick="document.getElementById('modalPix').classList.add('hidden')" class="absolute top-6 right-6 text-slate-300"><i class="fas fa-times"></i></button>
            <div class="w-16 h-16 bg-emerald-100 rounded-2xl flex items-center justify-center mx-auto mb-4">
                <i class="fab fa-pix text-emerald-600 text-3xl"></i>
            </div>
            <h3 class="font-black uppercase italic text-[#003964]">Recarga OABCG</h3>
            <p class="text-[10px] font-bold text-slate-400 uppercase mb-6 tracking-tighter">Pague o valor e envie o comprovante</p>
            <div class="bg-slate-100 p-4 rounded-3xl mb-6">
                <img src="https://api.qrserver.com/v1/create-qr-code/?size=180x180&data=CHAVE_PIX" class="mx-auto">
            </div>
            <p class="text-[9px] font-black text-slate-400 uppercase mb-2">Chave PIX:</p>
            <p class="text-[#003964] font-black text-[11px] mb-6">pix@oabcg.com</p>
            <button class="w-full bg-[#003964] text-white font-black py-4 rounded-2xl text-xs uppercase italic">Copiar Chave</button>
        </div>
    </div>

    <div class="fixed bottom-0 left-0 right-0 bg-slate-900/90 backdrop-blur-md border-t border-white/5 p-4 flex justify-around items-center">
        <a href="index.php" class="text-slate-500"><i class="fas fa-motorcycle"></i></a>
        <a href="acompanhamento.php" class="text-blue-500"><i class="fas fa-wallet"></i></a>
        <a href="perfil.php" class="text-slate-500"><i class="fas fa-user"></i></a>
    </div>

</body>
</html>
