<?php
session_start();
// Proteção de acesso: apenas administradores
if (!isset($_SESSION['usuario_id']) || $_SESSION['tipo'] !== 'admin') {
    header("Location: index.php");
    exit;
}

// Carregar dados reais
$pedidos = json_decode(file_get_contents('db/pedidos.json'), true) ?? [];
$usuarios = json_decode(file_get_contents('db/usuarios.json'), true) ?? [];

// Cálculos para os Cards do Topo
$totalPedidos = count($pedidos);
$faturamento = 0;
foreach($pedidos as $p) { if($p['status'] == 'pago') $faturamento += ($p['valor'] ?? 0); }
$saquesPendentes = 0;
foreach($usuarios as $u) { if(isset($u['tipo']) && $u['tipo'] == 'entregador' && ($u['saldo'] ?? 0) >= 50) $saquesPendentes++; }
?>

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin | OABCG Soluções Digitais</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root { --primary: #003964; --accent: #00a8ff; }
        body { background: #f4f7f6; font-family: 'Segoe UI', sans-serif; }
        .navbar-admin { background: var(--primary); color: white; padding: 15px; }
        .card-stat { border: none; border-radius: 12px; transition: transform 0.2s; }
        .card-stat:hover { transform: translateY(-5px); }
        .table-container { background: white; border-radius: 15px; padding: 20px; box-shadow: 0 4px 12px rgba(0,0,0,0.05); }
        .status-badge { font-size: 0.75em; padding: 5px 12px; border-radius: 20px; text-transform: uppercase; }
    </style>
</head>
<body>

<div class="navbar-admin d-flex justify-content-between align-items-center shadow">
    <h4 class="mb-0"><i class="fas fa-shield-halved me-2"></i> Painel Administrativo</h4>
    <div>
        <span>Olá, <b><?php echo $_SESSION['nome']; ?></b></span>
        <a href="logout.php" class="btn btn-sm btn-outline-light ms-3"><i class="fas fa-sign-out-alt"></i> Sair</a>
    </div>
</div>

<div class="container-fluid px-4 py-4">
    
    <div class="row mb-4">
        <div class="col-md-3">
            <div class="card card-stat bg-primary text-white shadow-sm p-3">
                <small class="opacity-75">Total de Pedidos</small>
                <h3 class="fw-bold mb-0"><?php echo $totalPedidos; ?></h3>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card card-stat bg-success text-white shadow-sm p-3">
                <small class="opacity-75">Faturamento Total</small>
                <h3 class="fw-bold mb-0">R$ <?php echo number_format($faturamento, 2, ',', '.'); ?></h3>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card card-stat bg-danger text-white shadow-sm p-3">
                <small class="opacity-75">Saques Pendentes</small>
                <h3 class="fw-bold mb-0"><?php echo $saquesPendentes; ?></h3>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card card-stat bg-info text-white shadow-sm p-3">
                <small class="opacity-75">Sistema Online</small>
                <h3 class="fw-bold mb-0">Ativo</h3>
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-lg-8 mb-4">
            <div class="table-container shadow-sm">
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <h5 class="mb-0 text-primary fw-bold"><i class="fas fa-print me-2"></i> Produção Gráfica</h5>
                    <input type="text" id="filtroPedido" class="form-control form-control-sm w-25" placeholder="Buscar pedido...">
                </div>
                <div class="table-responsive">
                    <table class="table align-middle table-hover">
                        <thead class="table-light">
                            <tr>
                                <th>ID</th>
                                <th>Material</th>
                                <th>Estação</th>
                                <th>Arte</th>
                                <th>Status</th>
                                <th>Ação</th>
                            </tr>
                        </thead>
                        <tbody id="listaPedidos">
                            <?php foreach($pedidos as $p): ?>
                            <tr>
                                <td><b>#<?php echo $p['id']; ?></b></td>
                                <td><?php echo $p['produto']; ?></td>
                                <td><small><?php echo $p['estacao'] ?? 'Pendente'; ?></small></td>
                                <td>
                                    <a href="<?php echo $p['arquivo_arte']; ?>" class="btn btn-sm btn-light border" download title="Baixar Arte">
                                        <i class="fas fa-download text-primary"></i>
                                    </a>
                                </td>
                                <td>
                                    <span id="badge_<?php echo $p['id']; ?>" class="status-badge badge <?php echo ($p['status'] == 'pago') ? 'bg-success' : 'bg-warning text-dark'; ?>">
                                        <?php echo $p['status']; ?>
                                    </span>
                                </td>
                                <td>
                                    <?php if($p['status'] != 'pago'): ?>
                                    <button class="btn btn-sm btn-success" onclick="confirmarAcao('<?php echo $p['id']; ?>', 'pago')">
                                        <i class="fas fa-check"></i>
                                    </button>
                                    <?php endif; ?>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <div class="col-lg-4">
            <div class="table-container shadow-sm">
                <h5 class="mb-4 text-danger fw-bold"><i class="fas fa-wallet me-2"></i> Pagamentos Entregadores</h5>
                <div class="list-group list-group-flush">
                    <?php foreach($usuarios as $u): ?>
                        <?php if(isset($u['tipo']) && $u['tipo'] == 'entregador' && ($u['saldo'] ?? 0) >= 50): ?>
                        <div class="list-group-item border-bottom py-3 px-0">
                            <div class="d-flex justify-content-between align-items-center">
                                <div>
                                    <h6 class="mb-0 fw-bold"><?php echo $u['nome']; ?></h6>
                                    <small class="text-muted">Pix: <?php echo $u['chave_pix']; ?></small>
                                </div>
                                <div class="text-end">
                                    <span class="d-block fw-bold text-success">R$ <?php echo number_format($u['saldo'], 2, ',', '.'); ?></span>
                                    <button class="btn btn-sm btn-outline-success mt-1" onclick="alert('Funcionalidade de Saque: Processar via Banco e deduzir no JSON')">
                                        Pagar
                                    </button>
                                </div>
                            </div>
                        </div>
                        <?php endif; ?>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
// Função AJAX para confirmar pagamento sem atualizar a página
function confirmarAcao(idPedido, novoStatus) {
    if(confirm("Confirmar pagamento manual do pedido #" + idPedido + "?")) {
        fetch('atualizar_status.php?id=' + idPedido + '&status=' + novoStatus)
        .then(response => response.text())
        .then(data => {
            if(data.trim() === "sucesso") {
                const badge = document.getElementById('badge_' + idPedido);
                badge.innerText = "pago";
                badge.className = "status-badge badge bg-success";
                alert("Status atualizado!");
            } else {
                alert("Erro: " + data);
            }
        });
    }
}

// Filtro de Busca Simples
document.getElementById('filtroPedido').addEventListener('keyup', function() {
    let valor = this.value.toLowerCase();
    let linhas = document.querySelectorAll('#listaPedidos tr');
    linhas.forEach(linha => {
        linha.style.display = linha.innerText.toLowerCase().includes(valor) ? '' : 'none';
    });
});
</script>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>