<?php
session_start();
date_default_timezone_set('America/Sao_Paulo');

$arquivo = 'db_pedidos.json';
$pedidos = file_exists($arquivo) ? json_decode(file_get_contents($arquivo), true) : [];

// 1. CAPTURA DO ID (URL ou SESSÃO)
if (isset($_GET['id'])) {
    $_SESSION['pedido_ativo_id'] = $_GET['id'];
}
$id_pedido_atual = $_SESSION['pedido_ativo_id'] ?? ''; 

// 2. BUSCA DO PEDIDO
$pedido = null;
if (!empty($id_pedido_atual)) {
    foreach ($pedidos as $p) {
        if ($p['id'] == $id_pedido_atual) {
            $pedido = $p;
            break;
        }
    }
}

// 3. SE NÃO EXISTE PEDIDO, VOLTA PARA O INÍCIO
if (!$pedido) { 
    header("Location: index.php"); 
    exit; 
}

// 4. LÓGICA PARA O CLIENTE FINALIZAR A CORRIDA (Botão Confirmar)
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['acao']) && $_POST['acao'] == 'concluir') {
    foreach ($pedidos as &$p) { 
        if ($p['id'] == $id_pedido_atual) { 
            $p['status'] = "Recebido"; // Status que libera o bloqueio no index.php
            break; 
        } 
    }
    file_put_contents($arquivo, json_encode($pedidos, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
    unset($_SESSION['pedido_ativo_id']); // Limpa a sessão para permitir nova corrida
    header("Location: index.php"); // Volta liberado para pedir outra
    exit;
}

// --- LÓGICA DE USUÁRIOS ONLINE ---
$arquivo_online = 'usuarios_online.json';
$usuarios_online = file_exists($arquivo_online) ? json_decode(file_get_contents($arquivo_online), true) : [];

$id_sessao = session_id();
$nome_cli = $_SESSION['usuario_nome'] ?? "Cliente";
$usuarios_online[$id_sessao] = [
    'nome' => $nome_cli,
    'ultimo_acesso' => time(),
    'tipo' => 'Cliente'
];

foreach ($usuarios_online as $id => $dados) {
    if (time() - $dados['ultimo_acesso'] > 30) { unset($usuarios_online[$id]); }
}
file_put_contents($arquivo_online, json_encode($usuarios_online));
$total_online = count($usuarios_online);

// ANTI-CACHE
header("Cache-Control: no-cache, no-store, must-revalidate");
header("Pragma: no-cache");
header("Expires: 0");

// 5. STATUS PARA EXIBIÇÃO
$status = $pedido['status'] ?? 'Procurando Entregador...';
$st_limpo = trim(str_replace('.', '', $status));

$procurando = (stripos($st_limpo, 'Procurando') !== false);
$concluido = in_array($st_limpo, ["Recebido", "Concluído", "Viagem Concluída", "Cancelado"]);
$aceito = (!$procurando && !$concluido);

$pct = "10%";
if (!$procurando) $pct = "55%";
if ($concluido) $pct = "100%";

// MOTORISTAS SIMULADOS (Apenas se estiver procurando)
if ($procurando) {
    $nomes = ['Marcos Silva', 'Lucas Lima','Rogerio Lima', 'Aline Maia', 'André Santos', 'Adriana Santos'];
    $locais = ['Terminal Alvorada', 'Jardim Oceânico', 'Terminal Recreio', 'Paulo da Portela'];
    shuffle($nomes);
    $motoristas_simulados = [];
    for ($i = 0; $i < 4; $i++) {
        $motoristas_simulados[] = [
            'nome' => $nomes[$i], 
            'veiculo' => $locais[array_rand($locais)], 
            'tempo' => rand(2, 10)
        ];
    }
}
?>

<!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.0.0/css/all.min.css">
    <meta http-equiv="refresh" content="15"> 
    <title>BRT Express | Status</title>
    <style>
        .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; } }
        .delay-1 { animation-delay: 1s; } .delay-2 { animation-delay: 2s; }
        .animate-fadeIn { animation: fadeIn 0.5s ease-in; }
        @keyframes fadeIn { from { opacity: 0; transform: translateY(15px); } to { opacity: 1; transform: translateY(0); } }
    </style>
</head>
<body class="bg-gray-100 p-4 pb-12 font-sans">
    <div class="max-w-md mx-auto">
        
        <?php if(!empty($pedido['recado'])): ?>
        <div class="mb-4 animate-bounce">
            <div class="bg-orange-500 text-white p-4 rounded-3xl shadow-xl flex items-center gap-3 border-b-4 border-orange-700">
                <i class="fas fa-bullhorn text-xl"></i>
                <div class="text-sm font-black uppercase"><?php echo htmlspecialchars($pedido['recado']); ?></div>
            </div>
        </div>
        <?php endif; ?>

        <div class="bg-white rounded-3xl p-4 shadow-sm border border-slate-100 mb-6 flex justify-between items-center">
            <div class="flex items-center gap-2">
                <span class="relative flex h-3 w-3">
                    <span class="animate-ping absolute inline-flex h-full w-full rounded-full bg-green-400 opacity-75"></span>
                    <span class="relative inline-flex rounded-full h-3 w-3 bg-green-500"></span>
                </span>
                <h4 class="text-[12px] font-black uppercase tracking-widest text-slate-800">Monitoramento Ativo</h4>
            </div>
            <span class="text-[11px] font-bold bg-blue-50 text-blue-700 px-2 py-1 rounded-lg">ID: #<?php echo substr($id_pedido_atual, -5); ?></span>
        </div>

        <div class="bg-white rounded-[2.5rem] shadow-2xl overflow-hidden border border-white">
            
            <?php if($procurando): ?>
                <div class="relative h-64 bg-slate-900 flex items-center justify-center overflow-hidden">
                    <div class="radar-ring w-64 h-64"></div>
                    <div class="radar-ring w-64 h-64 delay-1"></div>
                    <div class="radar-ring w-64 h-64 delay-2"></div>
                    <div class="z-10 text-center">
                        <div class="w-20 h-20 bg-blue-600 rounded-full flex items-center justify-center shadow-[0_0_30px_rgba(37,99,235,0.6)] animate-pulse mx-auto">
                            <i class="fas fa-motorcycle text-white text-3xl"></i>
                        </div>
                        <p class="text-blue-400 font-black text-[13px] uppercase tracking-[0.2em] mt-4 animate-pulse">Buscando Entregador...</p>
                    </div>
                </div>
            <?php else: ?>
                <div class="p-8 text-center <?php echo ($concluido)?'bg-green-500':'bg-[#003964]'; ?> text-white transition-all">
                    <h2 class="text-2xl font-black italic tracking-tighter uppercase leading-none"><?php echo htmlspecialchars($status); ?></h2>
                    <p class="text-[11px] opacity-70 mt-2 uppercase font-bold italic tracking-widest">Item: <?php echo htmlspecialchars($pedido['item'] ?? 'Entrega'); ?></p>

                    <div class="mt-6 flex flex-col gap-3 text-left bg-black/20 p-5 rounded-[2rem] border border-white/10 shadow-inner">
                        <div class="flex items-start gap-4">
                            <div class="w-6 h-6 bg-blue-500 rounded-full flex items-center justify-center text-[10px] shadow-lg mt-1 shrink-0"><i class="fas fa-arrow-up"></i></div>
                            <div>
                                <p class="text-[9px] uppercase font-black opacity-60 leading-none mb-1">Retirada:</p>
                                <p class="text-[12px] font-bold leading-tight"><?php echo htmlspecialchars($pedido['ponto_retirada'] ?? 'Não informado'); ?></p>
                            </div>
                        </div>
                        <div class="ml-3 h-3 border-l-2 border-dashed border-white/20"></div>
                        <div class="flex items-start gap-4">
                            <div class="w-6 h-6 bg-green-500 rounded-full flex items-center justify-center text-[10px] shadow-lg mt-1 shrink-0"><i class="fas fa-map-marker-alt"></i></div>
                            <div>
                                <p class="text-[9px] uppercase font-black opacity-60 leading-none mb-1">Destino Final:</p>
                                <p class="text-[12px] font-bold leading-tight"><?php echo htmlspecialchars($pedido['ponto_entrega'] ?? 'Não informado'); ?></p>
                            </div>
                        </div>
                    </div>
                </div>
            <?php endif; ?>

            <div class="p-6">
                <div class="relative flex justify-between mb-10 mt-2 px-2">
                    <div class="absolute top-5 left-0 w-full h-1 bg-gray-100 rounded-full"></div>
                    <div class="absolute top-5 left-0 h-1 bg-blue-600 rounded-full transition-all duration-1000" style="width: <?php echo $pct; ?>"></div>
                    
                    <div class="relative z-10 w-10 h-10 rounded-full bg-white border-4 border-blue-600 flex items-center justify-center shadow-sm">
                        <i class="fas fa-clipboard-check text-xs text-blue-600"></i>
                    </div>
                    <div class="relative z-10 w-10 h-10 rounded-full bg-white border-4 <?php echo (!$procurando) ? 'border-blue-600' : 'border-gray-100'; ?> flex items-center justify-center shadow-sm">
                        <i class="fas fa-motorcycle text-xs <?php echo ($aceito)?'text-blue-600 animate-pulse':'text-gray-300'; ?>"></i>
                    </div>
                    <div class="relative z-10 w-10 h-10 rounded-full bg-white border-4 <?php echo ($concluido) ? 'border-green-500' : 'border-gray-100'; ?> flex items-center justify-center shadow-sm">
                        <i class="fas fa-check text-xs <?php echo ($concluido)?'text-green-500':'text-gray-300'; ?>"></i>
                    </div>
                </div>

                <?php if($procurando): ?>
                    <div class="mb-2 space-y-3">
                        <h4 class="text-[11px] font-black text-gray-400 uppercase tracking-widest text-center mb-4 italic">Entregadores próximos:</h4>
                        <?php foreach($motoristas_simulados as $mot): ?>
                        <div class="flex items-center justify-between p-3 bg-gray-50 rounded-2xl border border-gray-100 animate-fadeIn">
                            <div class="flex items-center gap-3">
                                <img src="https://ui-avatars.com/api/?name=<?php echo urlencode($mot['nome']); ?>&background=003964&color=fff" class="w-8 h-8 rounded-full">
                                <div>
                                    <p class="text-[12px] font-bold text-gray-800 leading-none"><?php echo $mot['nome']; ?></p>
                                    <p class="text-[10px] text-gray-500 mt-1"><?php echo $mot['veiculo']; ?> • <?php echo $mot['tempo']; ?> min</p>
                                </div>
                            </div>
                            <span class="text-[9px] bg-blue-100 text-blue-600 px-2 py-0.5 rounded-full font-black uppercase italic">Online</span>
                        </div>
                        <?php endforeach; ?>
                    </div>
                <?php else: ?>
                    
                    <?php if (!empty($pedido['entregador_nome'])): ?>
                    <div class="bg-slate-50 p-4 rounded-3xl mb-6 flex items-center justify-between border border-slate-100">
                        <div class="flex items-center gap-3">
                            <img src="https://ui-avatars.com/api/?name=<?php echo urlencode($pedido['entregador_nome']); ?>&background=003964&color=fff" class="w-10 h-10 rounded-xl">
                            <div>
                                <p class="text-[9px] font-black text-blue-600 uppercase italic">Seu Entregador</p>
                                <h3 class="text-sm font-bold text-slate-800 uppercase"><?php echo htmlspecialchars($pedido['entregador_nome']); ?></h3>
                            </div>
                        </div>
                        <a href="tel:<?php echo $pedido['entregador_telefone'] ?? ''; ?>" class="w-10 h-10 bg-white shadow-sm rounded-xl flex items-center justify-center text-blue-600">
                            <i class="fas fa-phone-alt"></i>
                        </a>
                    </div>
                    <?php endif; ?>

                    <?php if (!$concluido): ?>
                        <form method="POST" class="mb-6 animate-fadeIn">
                            <input type="hidden" name="acao" value="concluir">
                            <button type="submit" class="w-full bg-green-500 text-white font-black py-4 rounded-[2rem] shadow-xl active:scale-95 transition-all uppercase text-xs tracking-widest italic border-b-4 border-green-700">
                                <i class="fas fa-check-circle mr-2"></i> CONFIRMAR RECEBIMENTO
                            </button>
                        </form>
                    <?php else: ?>
                        <div class="text-center py-6 animate-fadeIn">
                            <div class="bg-green-100 text-green-700 p-4 rounded-[2rem] text-[11px] font-black uppercase tracking-widest border-2 border-green-200">
                                <i class="fas fa-handshake mr-2"></i> Entrega Finalizada!
                            </div>
                            <a href="index.php" class="inline-block mt-4 text-[13px] font-black text-blue-600 uppercase border-b-2 border-blue-600 pb-1 italic">Novo Pedido</a>
                        </div>
                    <?php endif; ?>

                    <div class="bg-blue-50 rounded-[2.2rem] p-5 border-2 border-blue-100 mt-4">
                        <div id="box-chat" class="h-44 overflow-y-auto mb-4 space-y-2 p-2 text-xs bg-white/50 rounded-2xl shadow-inner scroll-smooth"></div>
                        <div class="flex gap-2">
                            <input type="text" id="input-chat" class="flex-1 p-3 rounded-2xl text-[12px] outline-none border border-transparent" placeholder="Mande uma mensagem...">
                            <button onclick="enviarMsg()" class="bg-blue-600 text-white w-12 h-12 rounded-2xl shadow-lg flex items-center justify-center active:scale-90 transition-all">
                                <i class="fas fa-paper-plane text-sm"></i>
                            </button>
                        </div>
                    </div>
                <?php endif; ?>

            </div>
        </div>
        <p class="text-center text-[10px] text-gray-400 mt-8 uppercase font-black tracking-[0.3em]">© BRT EXPRESS - TECNOLOGIA</p>
    </div>

    <script>
        const pid = '<?php echo $id_pedido_atual; ?>';
        
        function enviarMsg() {
            const input = document.getElementById('input-chat');
            if(!input.value.trim()) return;
            
            fetch('processar_chat.php', { 
                method: 'POST', 
                headers: {'Content-Type': 'application/x-www-form-urlencoded'}, 
                body: `id=${pid}&msg=${encodeURIComponent(input.value)}&de=cliente` 
            })
            .then(() => { 
                input.value = ''; 
                carregarMsg(); 
            });
        }

        function carregarMsg() {
            fetch(`mensagens.json?t=${Date.now()}`)
            .then(r => r.json())
            .then(d => {
                const box = document.getElementById('box-chat');
                if(!box) return;
                const msgs = d[pid] || [];
                box.innerHTML = msgs.map(m => `
                    <div class="flex ${m.de=='cliente'?'justify-end':'justify-start'}">
                        <div class="p-3 rounded-2xl ${m.de=='cliente'?'bg-blue-600 text-white rounded-br-none':'bg-white text-gray-800 border border-gray-100 rounded-bl-none'} max-w-[85%] font-bold shadow-sm text-[11px]">
                            ${m.msg}
                        </div>
                    </div>
                `).join('');
                box.scrollTop = box.scrollHeight;
            }).catch(() => {});
        }

        <?php if(!$procurando): ?>
            setInterval(carregarMsg, 3000); 
            carregarMsg();
        <?php endif; ?>
    </script>
</body>
</html>
