<?php
// Configura o tempo de vida da sessão no servidor (60 segundos)
ini_set('session.gc_maxlifetime', 180);
session_set_cookie_params(180);

session_start();

// Define o tempo de expiração (1 minuto = 60 segundos)
$tempo_expiracao = 180; 

if (isset($_SESSION['ultimo_clique'])) {
    $inatividade = time() - $_SESSION['ultimo_clique'];
    
    if ($inatividade > $tempo_expiracao) {
        // Se passou de 1 minuto, destrói a sessão e manda para o login
        session_unset();
        session_destroy();
        header("Location: login.php?erro=sessao_expirada");
        exit;
    }
}

// Atualiza o tempo do último clique para agora
$_SESSION['ultimo_clique'] = time();
?>

<?php
session_start();
header("Cache-Control: no-cache, no-store, must-revalidate");
header("Pragma: no-cache");
header("Expires: 0");

$arquivo_pedidos = 'db_pedidos.json';
$arquivo_usuarios = 'usuarios.json';

$pedidos = file_exists($arquivo_pedidos) ? json_decode(file_get_contents($arquivo_pedidos), true) : [];
$usuarios = file_exists($arquivo_usuarios) ? json_decode(file_get_contents($arquivo_usuarios), true) : [];
$meu_id = $_SESSION['usuario_id'] ?? '';

// 1. LISTA DE STATUS QUE FINALIZAM UMA CORRIDA
$status_finalizados = ["viagem concluída", "viagem concluida", "cancelado pelo cliente", "cancelado", "concluído", "concluido", "finalizado"];

// --- LÓGICA DE CANCELAMENTO ADICIONADA ---
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['acao']) && $_POST['acao'] == 'cancelar_corrida') {
    foreach ($pedidos as &$p) {
        if ($p['id'] == ($_GET['id'] ?? '')) {
            $p['status'] = "Cancelado pelo Cliente";
            file_put_contents($arquivo_pedidos, json_encode($pedidos, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE), LOCK_EX);
            unset($_SESSION['pedido_ativo_id']);
            header("Location: index.php");
            exit;
        }
    }
}

// 2. BUSCAR SE O USUÁRIO TEM QUALQUER CORRIDA ATIVA NO SISTEMA
$corrida_ativa_global = null;
foreach (array_reverse($pedidos) as $p) {
    if (trim($p['cliente_id']) == trim($meu_id)) {
        $st = mb_strtolower(trim($p['status'] ?? ''));
        if (!in_array($st, $status_finalizados)) {
            $corrida_ativa_global = $p;
            break; 
        }
    }
}

// 3. LOGICA DE ACESSO
$id_url = $_GET['id'] ?? null;

if ($corrida_ativa_global) {
    if ($id_url !== $corrida_ativa_global['id']) {
        $_SESSION['pedido_ativo_id'] = $corrida_ativa_global['id'];
        header("Location: acompanhamento.php?id=" . $corrida_ativa_global['id']);
        exit;
    }
    $pedido = $corrida_ativa_global;
    $concluido = false;
} else {
    if ($id_url) {
        foreach ($pedidos as $p) {
            if ($p['id'] == $id_url) {
                $pedido = $p;
                break;
            }
        }
    }
    $concluido = true;
    unset($_SESSION['pedido_ativo_id']); 
}

if (!isset($pedido)) {
    header("Location: index.php");
    exit;
}

$id_pedido_atual = $pedido['id']; 
$status = $pedido['status'];

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['acao']) && $_POST['acao'] == 'concluir') {
    $codigo_digitado = $_POST['codigo_validacao'] ?? '';
    foreach ($pedidos as &$p) {
        if ($p['id'] == $pedido['id']) {
            if (isset($p['codigo_entrega']) && $codigo_digitado == $p['codigo_entrega']) {
                $p['status'] = "Viagem Concluída";
                file_put_contents($arquivo_pedidos, json_encode($pedidos, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE), LOCK_EX);
                unset($_SESSION['pedido_ativo_id']); 
                header("Location: index.php?status=sucesso&id_pedido=" . $id_pedido_atual);
                exit;
            }
        }
    }
}

$status_display = $pedido['status'];
$procurando = (stripos($status_display, 'Procurando') !== false);
$pct = $procurando ? "15%" : ($concluido ? "100%" : "65%");

// --- PARTE ACRESCENTADA: EXIBIÇÃO DA ROTA ---
?>













<!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">
    <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">
    <?php if (!$concluido): ?> <meta http-equiv="refresh" content="15"> <?php endif; ?>
    <title>BRT Express | Status</title>
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Montserrat:wght@400;700;900&display=swap');
        body { font-family: 'Montserrat', sans-serif; background-color: #f8f9fa; }
        .bg-99 { background-color: #FFD100; }
        .text-99 { color: #FFD100; }
        .radar-pulse { position: absolute; border: 2px solid #FFD100; border-radius: 50%; opacity: 0; animation: pulse 3s infinite cubic-bezier(0.215, 0.61, 0.355, 1); }
        @keyframes pulse { 0% { transform: scale(0.3); opacity: 0.8; } 100% { transform: scale(2.2); opacity: 0; } }
        .glass-header { background: rgba(0, 0, 0, 0.85); backdrop-filter: blur(10px); }
        .shadow-premium { box-shadow: 0 10px 40px -10px rgba(0,0,0,0.1); }
    </style>
</head>
<body class="pb-32">


<div class="flex flex-col text-left">
    <div class="flex items-center gap-1 text-gray-500 mb-1">
        <i class="far fa-clock text-[10px]"></i>
        <span class="text-[11px] font-bold uppercase italic tracking-tighter">
            Solicitado em:
        </span>
    </div>
    
    <div class="bg-gray-100 p-2 rounded-xl border-l-4 border-yellow-400">
        <span class="text-xs font-black text-gray-800">
            <?php echo $p['data']; ?> 
            </span>
    </div>
</div>




<div class="bg-white p-5 rounded-[2rem] shadow-xl border border-gray-100 mb-6">
    <div class="flex items-center gap-2 mb-4">
        <div class="w-8 h-8 bg-yellow-400 rounded-full flex items-center justify-center">
            <i class="fas fa-map-marker-alt text-black text-xs"></i>
        </div>
        <h3 class="text-xs font-black uppercase italic tracking-tighter text-black">Sua Rota</h3>
    </div>

    <div class="space-y-4 relative">
        <div class="absolute left-[13px] top-6 bottom-6 border-l-2 border-dotted border-gray-300"></div>

        <div class="flex items-start gap-4 relative z-10">
            <div class="w-7 h-7 bg-green-500 rounded-full flex-shrink-0 flex items-center justify-center border-4 border-white shadow-md">
                <div class="w-2 h-2 bg-white rounded-full"></div>
            </div>
            <div class="text-left">
                <p class="text-[9px] font-black uppercase text-gray-400 leading-none mb-1">Retirada</p>
                <p class="text-sm font-bold text-gray-800 leading-tight">
                    <?php echo htmlspecialchars($pedido['ponto_retirada'] ?? 'Não informado'); ?>
                </p>
            </div>
        </div>

        <div class="flex items-start gap-4 relative z-10">
            <div class="w-7 h-7 bg-red-500 rounded-full flex-shrink-0 flex items-center justify-center border-4 border-white shadow-md">
                <div class="w-2 h-2 bg-white rounded-full"></div>
            </div>
            <div class="text-left">
                <p class="text-[9px] font-black uppercase text-gray-400 leading-none mb-1">Destino</p>
                <p class="text-sm font-bold text-gray-800 leading-tight">
                    <?php echo htmlspecialchars($pedido['ponto_entrega'] ?? 'Não informado'); ?>
                </p>
            </div>
        </div>
    </div>

    <div class="mt-5 pt-4 border-t border-gray-50 flex justify-between items-center">
        <span class="text-[10px] font-black uppercase text-gray-400 italic">Total do Serviço</span>
        <span class="text-lg font-black text-green-600 tracking-tighter">
            R$ <?php echo number_format($pedido['valor'] ?? 0, 2, ',', '.'); ?>
        </span>
    </div>
</div>




























    <div class="glass-header text-white px-6 pt-12 pb-8 rounded-b-[3rem] sticky top-0 z-40 shadow-2xl">
        <div class="flex justify-between items-end">
            <div>
                <class=" "><?php echo $_SESSION['usuario_nome'] ?? 'Parceiro'; ?>
                <br>
                
                <span class="text-[10px] font-bold text-99 uppercase tracking-widest">Sua Carteira</span>
                <div class="flex items-center gap-2">
                    <h2 class="text-3xl font-black italic">
                        <span class="text-sm font-normal not-italic opacity-60">R$</span> 
                        <?php 
                        $meu_saldo = 0;
                        foreach($usuarios as $u) { if(trim($u['id'] ?? '') == trim($meu_id)) { $meu_saldo = $u['saldo']; break; } }
                        echo number_format($meu_saldo, 2, ',', '.'); 
                        ?>
                    </h2>
                </div>
            </div>
            <div class="text-right">
                <span class="text-[9px] block opacity-40 font-bold uppercase">ID Corrida</span>
                <span class="text-xs font-black text-99">#<?php echo $id_pedido_atual; ?></span>
            </div>
        </div>
    </div>

    <div class="max-w-md mx-auto px-4 -mt-4 relative z-50">
        <div class="bg-white rounded-[2.5rem] shadow-premium 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-pulse w-64 h-64"></div>
                    <div class="radar-pulse w-64 h-64" style="animation-delay: 1s"></div>
                    <div class="z-10 text-center">
                        <div class="w-24 h-24 bg-99 rounded-full flex items-center justify-center shadow-[0_0_60px_rgba(255,209,0,0.3)] mx-auto border-[6px] border-slate-900/50">
                            <i class="fas fa-user-clock text-black text-3xl"></i>
                        </div>
                        <p class="text-white font-black text-xs uppercase tracking-[0.2em] mt-6">Aguardando Aceite...</p>
                    </div>
                </div>
            <?php else: ?>
                <div class="p-8 text-center <?php echo $concluido ? 'bg-green-500' : 'bg-99'; ?> text-black transition-colors duration-500">
                    <h2 class="text-xl font-black uppercase italic leading-none"><?php echo htmlspecialchars($status); ?></h2>
                    <p class="text-[10px] font-bold opacity-60 mt-2 uppercase tracking-widest">
                        <?php echo $concluido ? 'Acesso Liberado' : 'Status da sua Entrega'; ?>
                    </p>
                </div>
            <?php endif; ?>

                <?php if (!$procurando): ?>
                    <div class="mb-6 p-5 bg-black shadow-xl">
                        <div class="flex items-center gap-3 mb-3">
                            <div class="relative">
                                <?php 
                                    // Busca a foto do entregador no db de usuários
                                    $foto_entregador = 'img/default-avatar.png'; // Fallback
                                    $ent_id_atual = trim($pedido['entregador_id'] ?? '');
                                    foreach($usuarios as $user_f) {
                                        if(trim($user_f['id'] ?? '') == $ent_id_atual) {
                                            $foto_entregador = !empty($user_f['foto']) ? $user_f['foto'] : $foto_entregador;
                                            break;
                                        }
                                    }
                                ?>
                                <div class="w-14 h-14 rounded-full border-2 border-99 overflow-hidden bg-slate-800">
                                    <img src="<?php echo $foto_entregador; ?>" class="w-full h-full object-cover" alt="Entregador">
                                </div>
                                <div class="absolute -bottom-1 -right-1 w-3 h-3 bg-green-500 border-2 border-black rounded-full"></div>
                            </div>
                            <div>
                                <p class="text-[9px] font-black text-white uppercase leading-none tracking-wider">Seu Entregador</p>
                                <p class="text-[14px] font-black text-white uppercase italic mt-1 leading-none">
                                    <?php echo $pedido['entregador_nome'] ?? 'deslogado'; ?>
                                </p>
                            </div>
                        </div>
                        <div class="h-[1px] bg-white/10 w-full my-3"></div>
                        <?php 
                            $ultima_estacao = "Iniciando Turno";
                            if(!empty($ent_id_atual)){
                                foreach(array_reverse($pedidos) as $h){
                                    if($h['id'] != $id_pedido_atual && trim($h['entregador_id'] ?? '') == $ent_id_atual && in_array(mb_strtolower(trim($h['status'] ?? '')), $status_finalizados)){
                                        $ultima_estacao = $h['ponto_entrega'];
                                        break;
                                    }
                                }
                            }
                        ?>
                        <div class="flex items-center gap-2">
                            <i class="fas fa-history text-99 text-[10px]"></i>
                            <p class="text-[9px] font-bold text-gray-400 uppercase">Última entrega:</p>
                            <span class="text-[10px] font-black text-99 uppercase italic"><?php echo $ultima_estacao; ?></span>
                        </div>
                    </div>
                <?php endif; ?>
                <div class="relative flex justify-between mb-8 mt-4 px-4">
                    <div class="absolute top-5 left-0 w-full h-1.5 bg-gray-100 rounded-full"></div>
                    <div class="absolute top-5 left-0 h-1.5 bg-99 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-2 border-99 flex items-center justify-center shadow-lg"><i class="fas fa-map-marker-alt text-xs text-black"></i></div>
                    <div class="relative z-10 w-10 h-10 rounded-full bg-white border-2 <?php echo !$procurando ? 'border-99' : 'border-gray-200'; ?> flex items-center justify-center shadow-lg"><i class="fas fa-user-clock text-xs <?php echo !$procurando ? 'text-black' : 'text-gray-300'; ?>"></i></div>
                    <div class="relative z-10 w-10 h-10 rounded-full bg-white border-2 <?php echo $concluido ? 'border-green-500' : 'border-gray-200'; ?> flex items-center justify-center shadow-lg"><i class="fas fa-check text-xs <?php echo $concluido ? 'text-green-500' : 'text-gray-300'; ?>"></i></div>
                </div>

                <div class="space-y-3 mb-8">
                    <div class="grid grid-cols-2 gap-3">
                        <div class="bg-slate-50 p-4 rounded-2xl border border-slate-100">
                            <p class="text-[10px] font-black text-slate-400 uppercase mb-1">Encomenda</p>
                            <p class="text-[11px] font-bold text-slate-700 truncate italic">
                                <i class="fas fa-box text-99 mr-1"></i> <?php echo $pedido['item'] ?? 'Não informado'; ?>
                            </p>
                        </div>
                        <div class="bg-slate-50 p-4 rounded-2xl border border-slate-100 flex items-center justify-between">
                            <div>
                                <p class="text-[10px] font-black text-slate-400 uppercase mb-1">Entregadores Online</p>
                                <p class="text-[11px] font-bold text-slate-700 italic">
                                    <span class="inline-block w-1.5 h-1.5 rounded-full bg-green-500 animate-pulse mr-1"></span>
                                    <?php echo rand(8, 53); ?> na sua região
                                </p>
                            </div>
                            <i class="fas fa-users text-slate-200 text-lg"></i>
                        </div>
                    </div>
                </div>

                <?php if (!$concluido): ?>
                    <form method="POST" onsubmit="return confirm('Deseja cancelar esta corrida?');" class="mb-4">
                        <input type="hidden" name="acao" value="cancelar_corrida">
                        <button type="submit" class="w-full py-4 rounded-2xl bg-gray-50 text-gray-400 font-bold text-[10px] uppercase tracking-widest border border-gray-100 hover:bg-red-50 hover:text-red-500 transition-all">
                            Cancelar Solicitação
                        </button>
                    </form>
                <?php endif; ?>

                <?php if (!$procurando && !$concluido): ?>
                    <div class="mb-8">
                        <form method="POST" class="bg-slate-50 p-6 rounded-[2rem] border border-slate-100">
                            <input type="hidden" name="acao" value="concluir">
                            <div class="text-center mb-4">
                                <label class="text-[9px] font-black uppercase text-slate-400 tracking-tighter italic">Código de Finalização:</label>
                                <input type="number" name="codigo_validacao" required class="w-full mt-3 p-4 rounded-2xl text-center text-3xl font-black tracking-[0.3em] border-2 border-transparent focus:border-99 bg-white shadow-inner transition-all" placeholder="0000">
                            </div>
                            <button type="submit" class="w-full bg-black text-99 font-black py-5 rounded-2xl shadow-xl uppercase text-xs tracking-widest active:scale-95 transition-all">
                                Confirmar Entrega <i class="fas fa-arrow-right ml-2"></i>
                            </button>
                        </form>
                    </div>
                <?php endif; ?>

                <?php if(!$procurando && !$concluido): ?>
                    <div class="bg-white rounded-3xl p-4 border border-slate-100 shadow-sm">
                        <div class="flex items-center gap-3 mb-4 px-2">
                            <div class="w-2 h-2 rounded-full bg-green-500 animate-pulse"></div>
                            <h4 class="text-[10px] font-black uppercase text-slate-800 italic">Chat com Motorista</h4>
                        </div>
                        <div id="box-chat" class="h-48 overflow-y-auto mb-4 space-y-3 p-3 bg-slate-50 rounded-2xl border border-slate-100/50"></div>
                        <div class="flex gap-2">
                            <input type="text" id="input-chat" class="flex-1 p-4 rounded-2xl text-xs outline-none bg-slate-50 border border-transparent focus:bg-white focus:border-99 transition-all" placeholder="Diga algo...">
                            <button onclick="enviarMsg()" class="bg-99 text-black w-12 h-12 rounded-2xl flex items-center justify-center shadow-lg active:scale-90 transition-all">
                                <i class="fas fa-paper-plane"></i>
                            </button>
                        </div>
                    </div>
                <?php endif; ?>

                <?php if($concluido): ?>
                    <div class="text-center p-4">
                        <a href="index.php" class="inline-block bg-black text-99 font-black px-10 py-4 rounded-2xl uppercase text-xs tracking-widest shadow-xl">
                            Voltar ao Início
                        </a>
                    </div>
                <?php endif; ?>

            </div>
        </div>
    </div>

    <nav class="fixed bottom-0 left-0 right-0 glass-header px-8 py-5 z-50 rounded-t-[2.5rem]">
        <div class="max-w-md mx-auto flex justify-between items-center text-white/40">
            <a href="index.php" class="flex flex-col items-center <?php echo $concluido ? 'text-white' : ''; ?>"><i class="fas fa-home text-lg"></i></a>
            <a href="acompanhamento.php" class="flex flex-col items-center text-99 scale-125"><i class="fas fa-route text-lg"></i></a>
            <a href="contacredito.php" class="flex flex-col items-center"><i class="fas fa-wallet text-lg"></i></a>
            <a href="perfil.php" class="flex flex-col items-center"><i class="fas fa-user text-lg"></i></a>
        </div>
   </nav>

   <script>
    <?php if (!$concluido): ?>
    history.pushState(null, null, location.href);
    window.onpopstate = function () {
        history.go(1);
    };

    document.addEventListener("DOMContentLoaded", function() {
        const navLinks = document.querySelectorAll('nav a');
        navLinks.forEach(link => {
            if (!link.href.includes('acompanhamento.php')) {
                link.style.opacity = '0.3';
                link.style.pointerEvents = 'none';
                link.onclick = function(e) { e.preventDefault(); return false; };
            }
        });
    });
    <?php endif; ?>

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

    function enviarMsg() {
        const input = document.getElementById('input-chat');
        if(!input.value.trim()) return;
        
        const formData = new URLSearchParams();
        formData.append('id', pid);
        formData.append('msg', input.value);
        formData.append('de', 'cliente');

        fetch('processar_chat.php', { 
            method: 'POST', 
            headers: {'Content-Type': 'application/x-www-form-urlencoded'}, 
            body: formData.toString() 
        }).then(() => { 
            input.value = ''; 
            carregarMsg(); 
        });
    }
    
    <?php if(!$procurando && !$concluido): ?> 
        setInterval(carregarMsg, 3000); 
        carregarMsg(); 
        document.getElementById('input-chat').addEventListener('keypress', function(e) {
            if(e.key === 'Enter') enviarMsg();
        });
    <?php endif; ?>
</script>

<script>
    (function() {
        let tempoInatividade;
        const deslogarUsuario = () => {
            window.location.href = 'login.php?erro=inatividade';
        };
        const resetarTimer = () => {
            clearTimeout(tempoInatividade);
            tempoInatividade = setTimeout(deslogarUsuario, 60000);
        };
        const eventos = ['mousedown', 'mousemove', 'keypress', 'scroll', 'touchstart'];
        eventos.forEach(evento => {
            document.addEventListener(evento, resetarTimer, true);
        });
        resetarTimer();
    })();
</script>




<script>
   let ultimaModificacao = null;

function vigilanciaAtiva() {
    // O 'HEAD' apenas pergunta ao servidor: "O arquivo mudou?" 
    // É 10x mais rápido que ler o conteúdo.
    fetch('db_pedidos.json', { method: 'HEAD' })
        .then(res => {
            const dataHeader = res.headers.get('Last-Modified');
            if (ultimaModificacao && dataHeader !== ultimaModificacao) {
                // MUDOU! Toca o alerta e atualiza
                tocarSom(); 
                setTimeout(() => { window.location.reload(); }, 500); 
            }
            ultimaModificacao = dataHeader;
        });
}

// Verifica a cada 1 segundo (1000ms)
setInterval(vigilanciaAtiva, 1000);











</script>












</body>
</html>