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

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

if (!isset($_SESSION['corridas_ignoradas'])) {
    $_SESSION['corridas_ignoradas'] = [];
}

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['acao']) && $_POST['acao'] == 'esconder') {
    $_SESSION['corridas_ignoradas'][] = $_POST['id_pedido'];
    header("Location: admin.php");
    exit;
}

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['id_pedido']) && !isset($_POST['acao'])) {
    $id = $_POST['id_pedido'];
    foreach ($pedidos as &$p) {
        if ($p['id'] == $id) {
            if (isset($_POST['novo_status'])) {
                if ($_POST['novo_status'] == 'cancelar') {
                    $p['status'] = "Procurando Entregador";
                    $p['entregador_id'] = null;
                } else {
                    $p['status'] = $_POST['novo_status'];
                    $p['entregador_id'] = $_SESSION['usuario_id'] ?? 'ID_OFFLINE';
                    $p['entregador_nome'] = $_SESSION['usuario_nome'] ?? 'Entregador';
                    if (!isset($p['codigo_entrega']) || empty($p['codigo_entrega'])) {
                        $p['codigo_entrega'] = (string)rand(1000, 9999);
                    }
                }
            }
            break;
        }
    }
    file_put_contents($arquivo, json_encode($pedidos, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
    header("Location: admin.php");
    exit;
}

$total_entregas_feitas = 0; 
$saldo_total = 0;
$pedido_em_foco = null;
$corridas_disponiveis = [];

if (is_array($pedidos)) {
    foreach ($pedidos as $p) {
        $st = $p['status'] ?? '';
        if ($st == "Procurando Entregador" && !in_array($p['id'], $_SESSION['corridas_ignoradas'])) { 
            $corridas_disponiveis[] = $p;
        }
        $id_meu = (string)($_SESSION['usuario_id'] ?? '');
        $id_p = (string)($p['entregador_id'] ?? '');
        if (!empty($id_meu) && $id_p === $id_meu) {
            if (in_array($st, ["A caminho da Estação", "Entregador no Local", "Em trânsito"])) {
                $pedido_em_foco = $p;
            }
            if (stripos($st, 'Recebido') !== false || stripos($st, 'Concluída') !== false) {
                $total_entregas_feitas++;
                $saldo_total += 5.00;
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <meta http-equiv="refresh" content="20">
    <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>99 OABCG | Entregador</title>
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;600;800&display=swap');
        body { font-family: 'Inter', sans-serif; background-color: #F4F4F4; color: #1A1A1A; }
        .bg-99 { background-color: #FFD100; } /* Amarelo 99 */
        .text-99 { color: #FFD100; }
        .btn-99 { background-color: #FFD100; color: #1A1A1A; font-weight: 800; }
        .shadow-99 { shadow-lg shadow-yellow-500/20; }
    </style>
</head>
<body class="pb-10">

    <nav class="bg-white px-6 py-4 flex justify-between items-center shadow-sm sticky top-0 z-50">
        <div class="flex items-center gap-3">
            <div class="w-10 h-10 bg-99 rounded-full flex items-center justify-center font-black text-xl">99</div>
            <div>
                <p class="text-[10px] font-bold text-gray-400 uppercase leading-none">Online</p>
                <h1 class="text-sm font-black uppercase tracking-tighter"><?php echo $_SESSION['usuario_nome'] ?? 'Parceiro'; ?></h1>
            </div>
        </div>
        <a href="login2.php?logout=1" class="text-gray-400 p-2"><i class="fas fa-sign-out-alt text-xl"></i></a>
    </nav>

    <div class="max-w-md mx-auto px-4 mt-4">
        
        <div class="bg-black text-white p-6 rounded-[2rem] flex justify-between items-center mb-6 shadow-2xl">
            <div>
                <p class="text-[10px] font-bold text-gray-400 uppercase mb-1">Ganhos do dia</p>
                <h2 class="text-3xl font-extrabold italic">R$ <?php echo number_format($saldo_total, 2, ',', '.'); ?></h2>
            </div>
            <div class="text-right">
                <p class="text-[10px] font-bold text-gray-400 uppercase mb-1">Entregas</p>
                <h2 class="text-3xl font-extrabold italic text-99"><?php echo $total_entregas_feitas; ?></h2>
            </div>
        </div>

        <?php if ($pedido_em_foco): ?>
            <div class="bg-white rounded-[2.5rem] shadow-xl overflow-hidden mb-8 border-2 border-99">
                <div class="bg-99 p-4 text-center">
                    <p class="text-[10px] font-black uppercase tracking-widest text-black/60">Corrida em Andamento</p>
                </div>
                
                <div class="p-6">
                    <div class="bg-gray-50 border-2 border-dashed border-gray-200 rounded-3xl p-5 mb-6 text-center">
                        <p class="text-[10px] font-bold text-gray-400 uppercase mb-1">Código de Confirmação</p>
                        <h2 class="text-4xl font-black text-black tracking-[0.2em] italic">
                            <?php echo $pedido_em_foco['codigo_entrega'] ?? '----'; ?>
                        </h2>
                    </div>

                    <div class="space-y-3 mb-6">
                        <?php if(!empty($pedido_em_foco['agendamento_data'])): ?>
                        <div class="flex items-center gap-3 bg-blue-50 p-3 rounded-2xl border border-blue-100">
                            <i class="fas fa-clock text-blue-600"></i>
                            <span class="text-xs font-bold text-blue-900 uppercase">
                                Agendado: <?php echo date('d/m', strtotime($pedido_em_foco['agendamento_data'])); ?> às <?php echo $pedido_em_foco['agendamento_hora']; ?>
                            </span>
                        </div>
                        <?php endif; ?>

                        <div class="flex items-center gap-3 bg-gray-50 p-3 rounded-2xl border border-gray-100">
                            <i class="fas fa-box text-gray-400"></i>
                            <span class="text-xs font-bold text-gray-800 uppercase italic">
                                Item: <?php echo htmlspecialchars($pedido_em_foco['produto'] ?? $pedido_em_foco['item'] ?? $pedido_em_foco['descricao'] ?? 'Sem Descrição'); ?>
                            </span>
                        </div>
                    </div>

                    <div class="relative pl-8 mb-6 before:content-[''] before:absolute before:left-3 before:top-2 before:bottom-2 before:w-0.5 before:bg-gray-200">
                        <div class="mb-6 relative">
                            <div class="absolute -left-7 top-1 w-3 h-3 rounded-full bg-blue-500 border-2 border-white shadow-sm"></div>
                            <p class="text-[9px] font-bold text-gray-400 uppercase">Partida (Estação)</p>
                            <p class="text-sm font-black text-gray-800 italic uppercase"><?php echo htmlspecialchars($pedido_em_foco['ponto_retirada'] ?? $pedido_em_foco['origem'] ?? 'Origem não informada'); ?></p>
                        </div>
                        <div class="relative">
                            <div class="absolute -left-7 top-1 w-3 h-3 rounded-full bg-99 border-2 border-white shadow-sm"></div>
                            <p class="text-[9px] font-bold text-gray-400 uppercase">Entrega (Destino)</p>
                            <p class="text-sm font-black text-gray-800 italic uppercase"><?php echo htmlspecialchars($pedido_em_foco['ponto_entrega'] ?? $pedido_em_foco['destino'] ?? 'Destino não informado'); ?></p>
                        </div>
                    </div>

                    <form method="POST" onsubmit="return confirm('Sair desta corrida?');">
                        <input type="hidden" name="id_pedido" value="<?php echo $pedido_em_foco['id']; ?>">
                        <button name="novo_status" value="cancelar" class="w-full py-4 text-red-500 font-bold text-[10px] uppercase tracking-widest border border-red-100 rounded-2xl hover:bg-red-50 transition-all mb-4">
                            Sair desta corrida
                        </button>
                    </form>

                    <div class="bg-gray-100 rounded-3xl p-4">
                        <div id="box-chat" class="h-48 overflow-y-auto mb-4 space-y-2 flex flex-col p-2 text-[11px]"></div>
                        <div class="flex gap-2">
                            <input type="text" id="input-msg" class="flex-1 bg-white p-4 rounded-2xl text-xs font-bold shadow-sm outline-none border border-transparent focus:border-99" placeholder="Fale com o cliente...">
                            <button id="btn-enviar" onclick="enviarMensagem()" class="bg-black text-99 w-12 h-12 rounded-2xl flex items-center justify-center shadow-lg active:scale-90 transition-transform">
                                <i class="fas fa-paper-plane"></i>
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        <?php endif; ?>

        <h3 class="text-xs font-black uppercase italic text-gray-500 tracking-widest mb-4 flex items-center gap-2">
            <span class="w-2 h-2 bg-green-500 rounded-full animate-ping"></span> Radar de Corridas
        </h3>

        <?php if (empty($corridas_disponiveis)): ?>
            <div class="text-center py-16 bg-white rounded-[2rem] border-2 border-dashed border-gray-200">
                <i class="fas fa-satellite-dish text-gray-300 text-4xl mb-4 animate-bounce"></i>
                <h2 class="text-sm font-bold text-gray-400 uppercase italic">Procurando pedidos ao redor...</h2>
            </div>
        <?php else: ?>
            <div class="space-y-4">
                <?php foreach (array_reverse($corridas_disponiveis) as $p): ?>
                    <div class="bg-white rounded-[2rem] p-6 shadow-md border border-gray-100 relative group">
                        
                        <form method="POST" class="absolute top-4 right-6">
                            <input type="hidden" name="id_pedido" value="<?php echo $p['id']; ?>">
                            <input type="hidden" name="acao" value="esconder">
                            <button type="submit" class="text-gray-300 hover:text-red-400"><i class="fas fa-times"></i></button>
                        </form>

                        <div class="flex items-center gap-2 mb-3">
                            <span class="bg-green-100 text-green-700 text-[8px] font-black px-2 py-0.5 rounded-full uppercase tracking-widest">Disponível</span>
                            <?php if(!empty($p['agendamento_data'])): ?>
                                <span class="bg-blue-100 text-blue-700 text-[8px] font-black px-2 py-0.5 rounded-full uppercase italic">
                                    <i class="fas fa-clock mr-1"></i><?php echo $p['agendamento_hora']; ?>
                                </span>
                            <?php endif; ?>
                        </div>

                        <div class="mb-4">
                            <p class="text-[9px] font-bold text-gray-400 uppercase">O que levar:</p>
                            <p class="text-sm font-black text-gray-800 italic uppercase">
                                <?php echo htmlspecialchars($p['produto'] ?? $p['item'] ?? $p['descricao'] ?? 'Pedido Express'); ?>
                            </p>
                        </div>

                        <div class="flex items-center justify-between mb-5">
                            <div>
                                <p class="text-[9px] font-bold text-gray-400 uppercase">Solicitante</p>
                                <p class="text-xs font-bold text-gray-700 uppercase italic"><?php echo htmlspecialchars($p['cliente'] ?? 'Usuário'); ?></p>
                            </div>
                            <div class="text-right">
                                <p class="text-[9px] font-bold text-gray-400 uppercase">Ganhos</p>
                                <p class="text-lg font-black text-green-600">R$ 5,00</p>
                            </div>
                        </div>

                        <form method="POST">
                            <input type="hidden" name="id_pedido" value="<?php echo $p['id']; ?>">
                            <button name="novo_status" value="Em trânsito" class="w-full btn-99 py-4 rounded-2xl shadow-99 uppercase italic text-xs tracking-widest active:scale-95 transition-all">
                                Aceitar Corrida
                            </button>
                        </form>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </div>

    <script>
        const pedidoAtivoId = "<?php echo $pedido_em_foco['id'] ?? ''; ?>";

        function enviarMensagem() {
            const input = document.getElementById('input-msg');
            const btn = document.getElementById('btn-enviar');
            const msg = input.value.trim();
            if (!msg || !pedidoAtivoId) return;

            btn.disabled = true;
            const params = new URLSearchParams();
            params.append('id', pedidoAtivoId);
            params.append('msg', msg);
            params.append('de', 'entregador');

            fetch('processar_chat.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: params.toString()
            })
            .then(() => {
                input.value = '';
                btn.disabled = false;
                carregarMensagens();
            })
            .catch(() => { btn.disabled = false; });
        }

        function carregarMensagens() {
            if (!pedidoAtivoId) return;
            fetch(`mensagens.json?t=${Date.now()}`).then(r => r.json()).then(data => {
                const box = document.getElementById('box-chat');
                if (!box) return;
                const msgs = data[pedidoAtivoId] || [];
                box.innerHTML = msgs.map(m => `
                    <div class="flex ${m.de === 'entregador' ? 'justify-end' : 'justify-start'} mb-2">
                        <div class="p-3 px-4 rounded-2xl ${m.de === 'entregador' ? 'bg-black text-99 rounded-tr-none' : 'bg-white text-gray-800 shadow-sm border border-gray-100 rounded-tl-none'} max-w-[85%] font-bold">
                            ${m.msg}
                        </div>
                    </div>
                `).join('');
                box.scrollTop = box.scrollHeight;
            });
        }

        document.getElementById('input-msg')?.addEventListener('keypress', (e) => { if (e.key === 'Enter') enviarMensagem(); });
        if (pedidoAtivoId) { carregarMensagens(); setInterval(carregarMensagens, 3500); }
    </script>
</body>
</html>


