<?php
session_start();

// --- LÓGICA DE LOGOUT ---
if (isset($_GET['acao']) && $_GET['acao'] === 'logout') {
    session_destroy();
    header("Location: login.php");
    exit();
}

// Configuração de Arquivos
$db_entregadores = 'db_entregadores.json';
$db_clientes = 'usuarios.json';
$db_movimentacoes = 'historico_financeiro.json';
$file_ads = 'ads.json'; 
$arquivo_creditos = 'creditos.json'; 
$arquivo_saques = 'saques.json';

// --- FUNÇÃO DE CARREGAMENTO INTELIGENTE ---
function carregar($arq) {
    if (!file_exists($arq)) return [];
    $conteudo = trim(file_get_contents($arq));
    if (empty($conteudo)) return [];
    
    $decodificado = json_decode($conteudo, true);
    if (is_array($decodificado)) return $decodificado;
    
    return array_filter(array_map(function($l) {
        return json_decode(trim($l), true);
    }, file($arq, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES)));
}

// --- LÓGICA DE SALVAMENTO ---
function salvar($arq, $dados_array, $tipo) {
    if (in_array($tipo, ['cliente', 'ads', 'creditos', 'saques'])) {
        $json = json_encode(array_values($dados_array), JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
        if ($tipo === 'creditos') {
             $json = json_encode($dados_array, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
        }
        file_put_contents($arq, $json);
    } else {
        $linhas = array_map(fn($d) => json_encode($d, JSON_UNESCAPED_UNICODE), $dados_array);
        file_put_contents($arq, implode(PHP_EOL, $linhas) . PHP_EOL);
    }
}

// --- LÓGICA DE PROCESSAMENTO DE ADS (PUBLICIDADE) ---
if ($tab_ativa = $_GET['tab'] ?? 'entregadores') {
    if (isset($_POST['add_ad'])) {
        $ads = carregar($file_ads);
        $novo_ad = [
            'id' => uniqid(),
            'titulo' => $_POST['titulo'],
            'imagem' => $_POST['url_imagem'],
            'link' => $_POST['url_link']
        ];
        $ads[] = $novo_ad;
        salvar($file_ads, $ads, 'ads');
        header("Location: admin_master.php?tab=ads&msg=ok");
        exit;
    }

    if (isset($_GET['del_ad'])) {
        $id_del = $_GET['del_ad'];
        $ads = carregar($file_ads);
        $ads = array_filter($ads, function($a) use ($id_del) { return $a['id'] !== $id_del; });
        salvar($file_ads, $ads, 'ads');
        header("Location: admin_master.php?tab=ads&msg=del");
        exit;
    }
}

// --- CARREGAMENTO INICIAL ---
$saques = carregar($arquivo_saques);
$todos_creditos = carregar($arquivo_creditos);
$tab_ativa = $_GET['tab'] ?? 'entregadores';

// --- LÓGICA DE PAGAMENTO DE SAQUE ---
if(isset($_GET['pagar'])) {
    $id_saque = $_GET['pagar'];
    $houve_pagamento = false;
    foreach($saques as &$s) {
        if($s['id'] == $id_saque) {
            $s['status'] = 'pago';
            $houve_pagamento = true;
            break;
        }
    }
    if($houve_pagamento) {
        salvar($arquivo_saques, $saques, 'saques');
        header("Location: admin_master.php?tab=financeiro&msg=pago");
        exit;
    }
}

// --- LÓGICA DE PROCESSAMENTO USUÁRIOS ---
if (isset($_GET['acao']) && isset($_GET['cpf'])) {
    $cpf = $_GET['cpf'];
    $tipo = $_GET['tipo'] ?? 'entregador';
    $tab_atual = $_GET['tab'] ?? 'entregadores';
    $arquivo = ($tipo === 'cliente') ? $db_clientes : $db_entregadores;

    if (file_exists($arquivo)) {
        $dados_lista = carregar($arquivo);
        $houve_alteracao = false;

        foreach ($dados_lista as $key => &$dados) {
            $id_vinc = $dados['cpf'] ?? $dados['usuario'] ?? $dados['id'] ?? null;
            if ($id_vinc === $cpf) {
                $houve_alteracao = true;
                if ($_GET['acao'] === 'excluir') { unset($dados_lista[$key]); continue; }
                if ($_GET['acao'] === 'aprovar') $dados['status'] = 'aprovado';
                if ($_GET['acao'] === 'reprovar') $dados['status'] = 'reprovado';
                if ($_GET['acao'] === 'salvar_edicao') {
                    if (!empty($_POST['edit_nome'])) {
                        $novo_nome = mb_strtoupper($_POST['edit_nome'], 'UTF-8');
                        if (isset($dados['usuario'])) $dados['usuario'] = $novo_nome;
                        else $dados['nome'] = $novo_nome;
                    }
                    if (!empty($_POST['edit_senha'])) {
                        $dados['senha'] = password_hash($_POST['edit_senha'], PASSWORD_DEFAULT);
                    }
                    if ($tipo === 'cliente' && isset($_POST['add_saldo']) && $_POST['add_saldo'] !== '') {
                        $valor = (float)$_POST['add_saldo'];
                        $creditos_db = carregar($arquivo_creditos);
                        $saldo_atual = (float)($creditos_db[$cpf] ?? 0);
                        $creditos_db[$cpf] = $saldo_atual + $valor;
                        salvar($arquivo_creditos, $creditos_db, 'creditos');
                        $log_entry = ["data" => date('d/m/Y H:i'), "cpf" => $cpf, "valor" => $valor, "descricao" => "Crédito Master"];
                        file_put_contents($db_movimentacoes, json_encode($log_entry, JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
                    }
                }
            }
        }
        if ($houve_alteracao) {
            salvar($arquivo, array_values($dados_lista), $tipo);
            header("Location: admin_master.php?tab=$tab_atual&msg=ok");
            exit();
        }
    }
}

// Carregar Listas
$entregadores = carregar($db_entregadores);
$clientes = carregar($db_clientes);
$movimentacoes = array_reverse(carregar($db_movimentacoes));
$ads_list = carregar($file_ads);
?>

<!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>Admin Master | BRT PRO</title>
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;700;900&display=swap');
        body { font-family: 'Inter', sans-serif; background: #f1f5f9; }
        .tab-active { background: rgba(255,255,255,0.15); border-left: 4px solid #facc15; }
    </style>
</head>
<body class="min-h-screen flex flex-col md:flex-row">

    <aside class="w-full md:w-64 bg-[#003964] text-white p-6 shadow-2xl flex flex-col">
        <div class="mb-10 text-center">
            <h1 class="text-2xl font-black italic uppercase">BRT <span class="text-yellow-400">PRO</span></h1>
        </div>
        <nav class="space-y-2 flex-1 text-xs font-bold uppercase italic">
            <a href="?tab=entregadores" class="flex items-center gap-3 p-4 rounded-xl hover:bg-white/10 <?php echo $tab_ativa == 'entregadores' ? 'tab-active' : ''; ?>">
                <i class="fas fa-motorcycle text-lg"></i> Entregadores
            </a>
            <a href="?tab=clientes" class="flex items-center gap-3 p-4 rounded-xl hover:bg-white/10 <?php echo $tab_ativa == 'clientes' ? 'tab-active' : ''; ?>">
                <i class="fas fa-user-friends text-lg"></i> Clientes
            </a>
            <a href="?tab=ads" class="flex items-center gap-3 p-4 rounded-xl hover:bg-white/10 <?php echo $tab_ativa == 'ads' ? 'tab-active' : ''; ?>">
                <i class="fas fa-ad text-lg"></i> Publicidade (ADS)
            </a>
            <a href="?tab=financeiro" class="flex items-center gap-3 p-4 rounded-xl hover:bg-white/10 <?php echo $tab_ativa == 'financeiro' ? 'tab-active' : ''; ?>">
                <i class="fas fa-wallet text-lg"></i> Financeiro / Saques
            </a>
        </nav>
        <a href="?acao=logout" class="p-4 text-red-400 font-black text-[10px] uppercase italic mt-auto"><i class="fas fa-power-off"></i> Sair do Painel</a>
    </aside>

    <main class="flex-1 p-6 md:p-12">
        <h2 class="text-3xl font-black text-[#003964] uppercase italic mb-8">
            <?php 
                if($tab_ativa == 'ads') echo 'Gerenciar ADS';
                elseif($tab_ativa == 'financeiro') echo 'Financeiro e Saques';
                else echo 'Gerenciar ' . ucfirst($tab_ativa); 
            ?>
        </h2>

        <?php if($tab_ativa == 'ads'): ?>
            <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
                <div class="lg:col-span-1 bg-white p-6 rounded-[2rem] shadow-sm border h-fit">
                    <h3 class="text-lg font-black text-[#003964] uppercase italic mb-4">Novo Anúncio</h3>
                    <form method="POST" class="space-y-4">
                        <input type="text" name="titulo" placeholder="Título" class="w-full p-4 bg-slate-100 rounded-xl text-xs font-bold uppercase" required>
                        <input type="text" name="url_imagem" placeholder="URL da Imagem" class="w-full p-4 bg-slate-100 rounded-xl text-xs font-bold uppercase" required>
                        <input type="text" name="url_link" placeholder="Link (http://...)" class="w-full p-4 bg-slate-100 rounded-xl text-xs font-bold uppercase" required>
                        <button type="submit" name="add_ad" class="w-full bg-yellow-400 text-[#003964] font-black py-4 rounded-xl uppercase italic text-xs shadow-lg">Publicar Anúncio</button>
                    </form>
                </div>

                <div class="lg:col-span-2 space-y-4">
                    <?php if(empty($ads_list)): ?>
                        <p class="text-gray-400 font-bold bg-white p-10 rounded-[2rem] border text-center">Nenhum anúncio ativo.</p>
                    <?php endif; ?>
                    <?php foreach($ads_list as $ad): ?>
                    <div class="bg-white p-4 rounded-[2rem] shadow-sm border flex items-center gap-4">
                        <img src="<?php echo $ad['imagem']; ?>" class="w-20 h-20 rounded-2xl object-cover border">
                        <div class="flex-1">
                            <h4 class="font-black text-[#003964] uppercase text-xs"><?php echo $ad['titulo']; ?></h4>
                            <p class="text-[10px] text-blue-500 font-bold truncate max-w-[200px]"><?php echo $ad['link']; ?></p>
                        </div>
                        <a href="?tab=ads&del_ad=<?php echo $ad['id']; ?>" class="bg-red-50 text-red-500 p-4 rounded-2xl hover:bg-red-500 hover:text-white transition-all">
                            <i class="fas fa-trash-alt"></i>
                        </a>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>

        <?php elseif($tab_ativa == 'financeiro'): ?>
            <div class="space-y-6">
                <div class="flex items-center gap-4 mb-4">
                    <div class="bg-[#003964] p-3 rounded-2xl"><i class="fas fa-hand-holding-usd text-white text-xl"></i></div>
                    <h3 class="text-xl font-black text-[#003964] uppercase tracking-tighter">Solicitações de Saque</h3>
                </div>
                <div class="grid gap-4">
                    <?php 
                    $lista_saques = is_array($saques) ? array_reverse($saques) : [];
                    foreach($lista_saques as $s): ?>
                        <div class="bg-white p-5 rounded-[1.5rem] shadow-sm border-l-8 <?php echo ($s['status'] ?? '') == 'pago' ? 'border-green-500' : 'border-yellow-500'; ?> flex justify-between items-center">
                            <div class="space-y-1">
                                <p class="font-black text-gray-900 uppercase italic"><?php echo $s['nome'] ?? 'Desconhecido'; ?></p>
                                <p class="text-xl font-black text-[#003964]">R$ <?php echo number_format($s['valor'] ?? 0, 2, ',', '.'); ?></p>
                                <p class="text-[11px] font-bold text-gray-500 italic">PIX: <?php echo $s['pix_cpf'] ?? '---'; ?></p>
                            </div>
                            <?php if(($s['status'] ?? 'pendente') == 'pendente'): ?>
                                <a href="?pagar=<?php echo $s['id']; ?>" class="bg-green-500 text-white px-5 py-3 rounded-2xl font-black text-[10px] uppercase shadow-lg">LIBERAR</a>
                            <?php else: ?>
                                <span class="bg-green-100 text-green-700 px-3 py-1 rounded-full text-[9px] font-black uppercase">PAGO</span>
                            <?php endif; ?>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>

        <?php else: ?>
            <div class="bg-white rounded-[2rem] shadow-sm overflow-hidden border">
                <table class="w-full text-left">
                    <thead>
                        <tr class="bg-slate-50 border-b text-[10px] font-black uppercase text-slate-400 italic">
                            <th class="p-6">Nome / ID</th>
                            <th class="p-6">Info / Saldo</th>
                            <?php if($tab_ativa == 'entregadores'): ?> <th class="p-6">Status</th> <?php endif; ?>
                            <th class="p-6 text-center">Ações</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y">
                        <?php 
                        $lista = ($tab_ativa == 'clientes') ? $clientes : $entregadores;
                        $tipo_g = ($tab_ativa == 'clientes') ? 'cliente' : 'entregador';
                        foreach($lista as $u): 
                            $nome = $u['nome'] ?? $u['usuario'] ?? 'SEM NOME';
                            $id = $u['cpf'] ?? $u['usuario'] ?? $u['id'] ?? '---';
                        ?>
                        <tr class="hover:bg-slate-50">
                            <td class="p-6">
                                <p class="text-xs font-black text-[#003964] uppercase"><?php echo $nome; ?></p>
                                <p class="text-[9px] text-slate-400 font-bold"><?php echo $id; ?></p>
                            </td>
                            <td class="p-6">
                                <?php if($tipo_g == 'cliente'): ?>
                                    <span class="text-green-600 font-black italic">R$ <?php echo number_format($todos_creditos[$id] ?? 0, 2, ',', '.'); ?></span>
                                <?php else: ?>
                                    <a href="uploads/selfies/<?php echo $u['foto_selfie'] ?? ''; ?>" target="_blank" class="text-[10px] font-bold text-blue-500 uppercase italic">Ver Selfie</a>
                                <?php endif; ?>
                            </td>
                            <?php if($tab_ativa == 'entregadores'): ?>
                            <td class="p-6 text-[9px] font-black uppercase">
                                <span class="px-3 py-1 rounded-full <?php echo (strtolower($u['status'] ?? '') == 'aprovado') ? 'bg-green-100 text-green-600' : 'bg-yellow-100 text-yellow-600'; ?>">
                                    <?php echo $u['status'] ?? 'pendente'; ?>
                                </span>
                            </td>
                            <?php endif; ?>
                            <td class="p-6 flex justify-center gap-2">
                                <button onclick="abrirModal('<?php echo $id; ?>', '<?php echo addslashes($nome); ?>', '<?php echo $tipo_g; ?>')" class="bg-blue-600 text-white px-3 py-2 rounded-lg text-[10px] font-black uppercase italic">EDITAR</button>
                                <a href="?acao=excluir&cpf=<?php echo $id; ?>&tipo=<?php echo $tipo_g; ?>&tab=<?php echo $tab_ativa; ?>" onclick="return confirm('Excluir?')" class="bg-red-500 text-white p-2 rounded-lg text-xs"><i class="fas fa-trash"></i></a>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>
    </main>

    <div id="modalMaster" class="hidden fixed inset-0 bg-black/80 backdrop-blur-sm flex items-center justify-center p-4 z-50">
        <div class="bg-white rounded-[2rem] w-full max-w-sm overflow-hidden shadow-2xl border">
            <div class="bg-[#003964] p-6 text-white text-center font-black uppercase italic" id="modalNome">EDITAR</div>
            <form id="formMaster" method="POST" class="p-8 space-y-4">
                <input type="text" name="edit_nome" id="inputNome" class="w-full p-4 bg-slate-100 rounded-xl text-xs font-bold uppercase" required>
                <input type="password" name="edit_senha" class="w-full p-4 bg-slate-100 rounded-xl text-xs font-bold" placeholder="NOVA SENHA (OPCIONAL)">
                <div id="areaSaldo" class="p-4 bg-blue-50 rounded-xl border border-blue-100 hidden">
                    <label class="text-[9px] font-black text-blue-400 block mb-1 uppercase">Adicionar Saldo (R$)</label>
                    <input type="number" step="0.01" name="add_saldo" class="w-full bg-transparent text-xl font-black text-blue-600 outline-none" placeholder="0.00">
                </div>
                <button type="submit" class="w-full bg-yellow-400 text-[#003964] font-black py-4 rounded-xl uppercase italic text-xs shadow-lg">Salvar Alterações</button>
                <button type="button" onclick="document.getElementById('modalMaster').classList.add('hidden')" class="w-full text-slate-400 text-[10px] font-black uppercase text-center mt-2">Fechar</button>
            </form>
        </div>
    </div>

    <script>
        function abrirModal(cpf, nome, tipo) {
            document.getElementById('modalNome').innerText = nome;
            document.getElementById('inputNome').value = nome;
            document.getElementById('formMaster').action = `?acao=salvar_edicao&cpf=${cpf}&tipo=${tipo}&tab=${tipo === 'cliente' ? 'clientes' : 'entregadores'}`;
            const areaSaldo = document.getElementById('areaSaldo');
            if (tipo === 'cliente') { areaSaldo.classList.remove('hidden'); } else { areaSaldo.classList.add('hidden'); }
            document.getElementById('modalMaster').classList.remove('hidden');
        }
    </script>
</body>
</html>