<?php
require_once '../config/database.php';
require_once '../config/auth.php';
requireLogin('admin', 'index.php');

$db = Database::getInstance()->getConnection();

// Estatísticas gerais
$stats = [];

$stmt = $db->query("SELECT COUNT(*) as total FROM usuarios");
$stats['usuarios'] = $stmt->fetch()['total'];

$stmt = $db->query("SELECT COUNT(*) as total FROM entregadores");
$stats['entregadores'] = $stmt->fetch()['total'];

$stmt = $db->query("SELECT COUNT(*) as total FROM entregadores WHERE status = 'disponivel'");
$stats['entregadores_online'] = $stmt->fetch()['total'];

$stmt = $db->query("SELECT COUNT(*) as total FROM entregas");
$stats['entregas_total'] = $stmt->fetch()['total'];

$stmt = $db->query("SELECT COUNT(*) as total FROM entregas WHERE status = 'pendente'");
$stats['entregas_pendentes'] = $stmt->fetch()['total'];

$stmt = $db->query("SELECT COUNT(*) as total FROM entregas WHERE status = 'entregue'");
$stats['entregas_completas'] = $stmt->fetch()['total'];

$stmt = $db->query("SELECT COALESCE(SUM(valor), 0) as total FROM entregas WHERE status = 'entregue'");
$stats['faturamento'] = $stmt->fetch()['total'];

$stmt = $db->query("SELECT COALESCE(SUM(valor), 0) as total FROM entregas WHERE status = 'entregue' AND DATE(updated_at) = CURDATE()");
$stats['faturamento_hoje'] = $stmt->fetch()['total'];

// Últimas entregas
$stmt = $db->query("
    SELECT e.*, u.nome as cliente, ent.nome as entregador
    FROM entregas e
    LEFT JOIN usuarios u ON e.usuario_id = u.id
    LEFT JOIN entregadores ent ON e.entregador_id = ent.id
    ORDER BY e.created_at DESC
    LIMIT 10
");
$ultimasEntregas = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Dashboard - Já EntreGo</title>
    <link rel="stylesheet" href="../assets/css/style.css">
    <link rel="stylesheet" href="../assets/css/admin.css">
    <script src="../assets/js/admin-theme.js"></script>
</head>
<body class="admin-panel">
    <header class="header">
        <h1>⚙️ Já EntreGo Admin</h1>
        <nav>
            <a href="dashboard.php">Dashboard</a>
            <a href="entregas.php">Entregas</a>
            <a href="entregadores.php">Entregadores</a>
            <a href="usuarios.php">Usuários</a>
            <a href="parceiros.php">Parceiros</a>
            <a href="configuracoes.php">Configurações</a>
            <a href="perfil.php">Perfil</a>
            <a href="logout.php">Sair</a>
            <div class="theme-toggle">
                <button type="button" id="theme-toggle-btn" class="theme-toggle-btn" onclick="toggleTheme()" title="Alternar tema">🌙</button>
            </div>
        </nav>
    </header>
    
    <div class="container">
        <h2 style="margin-bottom: 20px;">Dashboard</h2>
        
        <!-- Estatísticas -->
        <div class="row">
            <div class="col">
                <div class="stat-card">
                    <div class="number"><?= $stats['usuarios'] ?></div>
                    <div class="label">Clientes</div>
                </div>
            </div>
            <div class="col">
                <div class="stat-card">
                    <div class="number"><?= $stats['entregadores'] ?></div>
                    <div class="label">Entregadores</div>
                </div>
            </div>
            <div class="col">
                <div class="stat-card">
                    <div class="number" style="color: #00c853;"><?= $stats['entregadores_online'] ?></div>
                    <div class="label">Online Agora</div>
                </div>
            </div>
        </div>
        
        <div class="row" style="margin-top: 10px;">
            <div class="col">
                <div class="stat-card">
                    <div class="number"><?= $stats['entregas_total'] ?></div>
                    <div class="label">Total Entregas</div>
                </div>
            </div>
            <div class="col">
                <div class="stat-card">
                    <div class="number" style="color: #ffc107;"><?= $stats['entregas_pendentes'] ?></div>
                    <div class="label">Pendentes</div>
                </div>
            </div>
            <div class="col">
                <div class="stat-card">
                    <div class="number" style="color: #00c853;"><?= $stats['entregas_completas'] ?></div>
                    <div class="label">Completas</div>
                </div>
            </div>
        </div>
        
        <div class="row" style="margin-top: 10px;">
            <div class="col">
                <div class="stat-card">
                    <div class="number">R$ <?= number_format($stats['faturamento_hoje'], 2, ',', '.') ?></div>
                    <div class="label">Faturamento Hoje</div>
                </div>
            </div>
            <div class="col">
                <div class="stat-card">
                    <div class="number">R$ <?= number_format($stats['faturamento'], 2, ',', '.') ?></div>
                    <div class="label">Faturamento Total</div>
                </div>
            </div>
        </div>
        
        <!-- Últimas Entregas -->
        <div class="card" style="margin-top: 20px;">
            <h3 class="card-title">Últimas Entregas</h3>
            <table class="table">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Cliente</th>
                        <th>Entregador</th>
                        <th>Origem</th>
                        <th>Destino</th>
                        <th>Valor</th>
                        <th>Status</th>
                        <th>Data</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($ultimasEntregas as $e): ?>
                    <tr>
                        <td>#<?= $e['id'] ?></td>
                        <td><?= htmlspecialchars($e['cliente']) ?></td>
                        <td><?= $e['entregador'] ? htmlspecialchars($e['entregador']) : '-' ?></td>
                        <td><?= htmlspecialchars(substr($e['origem_endereco'], 0, 30)) ?>...</td>
                        <td><?= htmlspecialchars(substr($e['destino_endereco'], 0, 30)) ?>...</td>
                        <td>R$ <?= number_format($e['valor'], 2, ',', '.') ?></td>
                        <td><span class="badge badge-<?= $e['status'] ?>"><?= ucfirst($e['status']) ?></span></td>
                        <td><?= date('d/m H:i', strtotime($e['created_at'])) ?></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</body>
</html>
