<?php
/**
 * ============================================================
 * Super Admin Dashboard - BarberFlow SaaS
 * ============================================================
 * Visão do CEO do SaaS - Métricas globais, gestão de tenants
 */

session_start();
require_once __DIR__ . '/../includes/config.php';

// Verificar se é Super Admin
// TODO: Implementar autenticação de super admin
$isSuperAdmin = true; // Por enquanto, permitir acesso

if (!$isSuperAdmin) {
    header('Location: /admin/login.php');
    exit;
}

// Buscar métricas do SaaS
try {
    $db = getDB();
    
    // Total de lojas
    $stmt = $db->query("SELECT COUNT(*) as total FROM stores WHERE deleted_at IS NULL");
    $totalStores = $stmt->fetch()['total'] ?? 0;
    
    // Lojas ativas (com assinatura ativa)
    $stmt = $db->query("SELECT COUNT(*) as total FROM stores WHERE status = 'active' AND deleted_at IS NULL");
    $activeStores = $stmt->fetch()['total'] ?? 0;
    
    // Lojas em trial
    $stmt = $db->query("SELECT COUNT(*) as total FROM stores WHERE status = 'trial' AND deleted_at IS NULL");
    $trialStores = $stmt->fetch()['total'] ?? 0;
    
    // Lojas inadimplentes
    $stmt = $db->query("SELECT COUNT(*) as total FROM stores WHERE status = 'past_due' AND deleted_at IS NULL");
    $pastDueStores = $stmt->fetch()['total'] ?? 0;
    
    // MRR (Monthly Recurring Revenue) - simulado
    $mrr = $activeStores * 99.90; // Média por loja
    
    // Novas lojas este mês
    $stmt = $db->query("SELECT COUNT(*) as total FROM stores WHERE MONTH(created_at) = MONTH(CURRENT_DATE()) AND YEAR(created_at) = YEAR(CURRENT_DATE()) AND deleted_at IS NULL");
    $newStoresThisMonth = $stmt->fetch()['total'] ?? 0;
    
    // Total de pedidos no sistema
    $stmt = $db->query("SELECT COUNT(*) as total FROM orders WHERE deleted_at IS NULL");
    $totalOrders = $stmt->fetch()['total'] ?? 0;
    
    // Total de produtos
    $stmt = $db->query("SELECT COUNT(*) as total FROM products WHERE deleted_at IS NULL");
    $totalProducts = $stmt->fetch()['total'] ?? 0;
    
    // Listar últimas lojas cadastradas
    $stmt = $db->query("
        SELECT s.*, 
               (SELECT COUNT(*) FROM orders o WHERE o.store_id = s.id) as orders_count,
               (SELECT COUNT(*) FROM products p WHERE p.store_id = s.id) as products_count
        FROM stores s 
        WHERE s.deleted_at IS NULL 
        ORDER BY s.created_at DESC 
        LIMIT 10
    ");
    $recentStores = $stmt->fetchAll();
    
    // Lojas inadimplentes
    $stmt = $db->query("
        SELECT s.*, 
               sub.current_period_end,
               sub.status as subscription_status
        FROM stores s 
        LEFT JOIN subscriptions sub ON sub.store_id = s.id
        WHERE s.status IN ('past_due', 'suspended') 
        AND s.deleted_at IS NULL 
        ORDER BY s.updated_at DESC 
        LIMIT 5
    ");
    $delinquentStores = $stmt->fetchAll();
    
} catch (Exception $e) {
    // Valores padrão em caso de erro
    $totalStores = 0;
    $activeStores = 0;
    $trialStores = 0;
    $pastDueStores = 0;
    $mrr = 0;
    $newStoresThisMonth = 0;
    $totalOrders = 0;
    $totalProducts = 0;
    $recentStores = [];
    $delinquentStores = [];
}

// Helper para formatar moeda
function formatMoney($value) {
    return 'R$ ' . number_format($value, 2, ',', '.');
}

// Helper para status badge
function getStatusBadge($status) {
    $badges = [
        'active' => '<span class="status-badge status-active">Ativo</span>',
        'trial' => '<span class="status-badge status-trial">Trial</span>',
        'past_due' => '<span class="status-badge status-past-due">Inadimplente</span>',
        'cancelled' => '<span class="status-badge status-cancelled">Cancelado</span>',
        'suspended' => '<span class="status-badge status-suspended">Suspenso</span>',
    ];
    return $badges[$status] ?? '<span class="status-badge">' . ucfirst($status) . '</span>';
}

$pageTitle = 'Super Admin Dashboard';
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= $pageTitle ?> - BarberFlow</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="/assets/css/style.css">
    <script src="https://cdn.jsdelivr.net/npm/iconify-icon@1.0.7/dist/iconify-icon.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        :root {
            --gold: #CCA43B;
            --gold-light: rgba(204, 164, 59, 0.15);
            --bg-dark: #0D0D0D;
            --bg-panel: #1A1A1A;
            --bg-panel-hover: #242424;
            --text-primary: #FFFFFF;
            --text-secondary: #B3B3B3;
            --text-muted: #666666;
            --border-light: rgba(255, 255, 255, 0.08);
            --success: #22C55E;
            --danger: #EF4444;
            --warning: #F59E0B;
            --info: #3B82F6;
        }
        
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Inter', sans-serif;
            background: var(--bg-dark);
            color: var(--text-primary);
            min-height: 100vh;
        }
        
        .superadmin-layout {
            display: flex;
            min-height: 100vh;
        }
        
        /* Sidebar */
        .superadmin-sidebar {
            width: 280px;
            background: var(--bg-panel);
            border-right: 1px solid var(--border-light);
            display: flex;
            flex-direction: column;
            position: fixed;
            height: 100vh;
            z-index: 100;
        }
        
        .sidebar-header {
            padding: 1.5rem;
            border-bottom: 1px solid var(--border-light);
        }
        
        .sidebar-logo {
            display: flex;
            align-items: center;
            gap: 12px;
        }
        
        .sidebar-logo-icon {
            width: 40px;
            height: 40px;
            background: linear-gradient(135deg, var(--gold), #B8962F);
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #000;
            font-size: 1.25rem;
        }
        
        .sidebar-logo-text {
            font-size: 1.25rem;
            font-weight: 700;
            color: var(--text-primary);
        }
        
        .sidebar-logo-badge {
            font-size: 0.6rem;
            background: var(--gold);
            color: #000;
            padding: 2px 6px;
            border-radius: 4px;
            font-weight: 600;
            margin-left: auto;
        }
        
        .sidebar-nav {
            flex: 1;
            padding: 1rem;
            overflow-y: auto;
        }
        
        .nav-section {
            margin-bottom: 1.5rem;
        }
        
        .nav-section-title {
            font-size: 0.7rem;
            text-transform: uppercase;
            letter-spacing: 0.1em;
            color: var(--text-muted);
            padding: 0 0.75rem;
            margin-bottom: 0.5rem;
        }
        
        .nav-link {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 0.75rem;
            border-radius: 8px;
            color: var(--text-secondary);
            text-decoration: none;
            transition: all 0.2s;
            margin-bottom: 4px;
        }
        
        .nav-link:hover {
            background: var(--bg-panel-hover);
            color: var(--text-primary);
        }
        
        .nav-link.active {
            background: var(--gold-light);
            color: var(--gold);
        }
        
        .nav-link iconify-icon {
            font-size: 1.25rem;
        }
        
        .sidebar-footer {
            padding: 1rem;
            border-top: 1px solid var(--border-light);
        }
        
        .admin-profile {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 0.75rem;
            border-radius: 8px;
            background: var(--bg-panel-hover);
        }
        
        .admin-avatar {
            width: 40px;
            height: 40px;
            border-radius: 10px;
            background: linear-gradient(135deg, var(--gold), #B8962F);
            display: flex;
            align-items: center;
            justify-content: center;
            color: #000;
            font-weight: 600;
        }
        
        .admin-info {
            flex: 1;
        }
        
        .admin-name {
            font-size: 0.875rem;
            font-weight: 600;
            color: var(--text-primary);
        }
        
        .admin-role {
            font-size: 0.75rem;
            color: var(--gold);
        }
        
        /* Main Content */
        .superadmin-main {
            flex: 1;
            margin-left: 280px;
            min-height: 100vh;
        }
        
        .superadmin-header {
            background: var(--bg-panel);
            border-bottom: 1px solid var(--border-light);
            padding: 1rem 2rem;
            display: flex;
            align-items: center;
            justify-content: space-between;
            position: sticky;
            top: 0;
            z-index: 50;
        }
        
        .header-title {
            font-size: 1.5rem;
            font-weight: 700;
        }
        
        .header-actions {
            display: flex;
            align-items: center;
            gap: 1rem;
        }
        
        .btn {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            padding: 0.625rem 1.25rem;
            border-radius: 8px;
            font-size: 0.875rem;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.2s;
            border: none;
            text-decoration: none;
        }
        
        .btn-primary {
            background: linear-gradient(135deg, var(--gold), #B8962F);
            color: #000;
        }
        
        .btn-primary:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(204, 164, 59, 0.3);
        }
        
        .btn-secondary {
            background: var(--bg-panel-hover);
            color: var(--text-primary);
            border: 1px solid var(--border-light);
        }
        
        .superadmin-content {
            padding: 2rem;
        }
        
        /* KPI Cards */
        .kpi-grid {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 1.5rem;
            margin-bottom: 2rem;
        }
        
        .kpi-card {
            background: var(--bg-panel);
            border-radius: 16px;
            padding: 1.5rem;
            border: 1px solid var(--border-light);
        }
        
        .kpi-card.highlight {
            background: linear-gradient(135deg, rgba(204, 164, 59, 0.1), rgba(204, 164, 59, 0.05));
            border-color: rgba(204, 164, 59, 0.3);
        }
        
        .kpi-header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-bottom: 1rem;
        }
        
        .kpi-icon {
            width: 48px;
            height: 48px;
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.5rem;
        }
        
        .kpi-icon.gold {
            background: var(--gold-light);
            color: var(--gold);
        }
        
        .kpi-icon.green {
            background: rgba(34, 197, 94, 0.15);
            color: var(--success);
        }
        
        .kpi-icon.blue {
            background: rgba(59, 130, 246, 0.15);
            color: var(--info);
        }
        
        .kpi-icon.orange {
            background: rgba(245, 158, 11, 0.15);
            color: var(--warning);
        }
        
        .kpi-icon.red {
            background: rgba(239, 68, 68, 0.15);
            color: var(--danger);
        }
        
        .kpi-trend {
            display: flex;
            align-items: center;
            gap: 4px;
            font-size: 0.75rem;
            padding: 4px 8px;
            border-radius: 20px;
        }
        
        .kpi-trend.up {
            background: rgba(34, 197, 94, 0.15);
            color: var(--success);
        }
        
        .kpi-trend.down {
            background: rgba(239, 68, 68, 0.15);
            color: var(--danger);
        }
        
        .kpi-value {
            font-size: 2rem;
            font-weight: 700;
            color: var(--text-primary);
            margin-bottom: 0.25rem;
        }
        
        .kpi-label {
            font-size: 0.875rem;
            color: var(--text-secondary);
        }
        
        /* Content Grid */
        .content-grid {
            display: grid;
            grid-template-columns: 2fr 1fr;
            gap: 1.5rem;
        }
        
        .panel {
            background: var(--bg-panel);
            border-radius: 16px;
            border: 1px solid var(--border-light);
            overflow: hidden;
        }
        
        .panel-header {
            padding: 1.25rem 1.5rem;
            border-bottom: 1px solid var(--border-light);
            display: flex;
            align-items: center;
            justify-content: space-between;
        }
        
        .panel-title {
            font-size: 1rem;
            font-weight: 600;
        }
        
        .panel-action {
            font-size: 0.875rem;
            color: var(--gold);
            text-decoration: none;
        }
        
        .panel-action:hover {
            text-decoration: underline;
        }
        
        .panel-body {
            padding: 1.5rem;
        }
        
        /* Store Table */
        .stores-table {
            width: 100%;
            border-collapse: collapse;
        }
        
        .stores-table th,
        .stores-table td {
            padding: 1rem;
            text-align: left;
            border-bottom: 1px solid var(--border-light);
        }
        
        .stores-table th {
            font-size: 0.75rem;
            text-transform: uppercase;
            letter-spacing: 0.05em;
            color: var(--text-muted);
            font-weight: 500;
        }
        
        .stores-table tr:last-child td {
            border-bottom: none;
        }
        
        .stores-table tr:hover td {
            background: var(--bg-panel-hover);
        }
        
        .store-info {
            display: flex;
            align-items: center;
            gap: 12px;
        }
        
        .store-avatar {
            width: 40px;
            height: 40px;
            border-radius: 10px;
            background: var(--bg-panel-hover);
            display: flex;
            align-items: center;
            justify-content: center;
            color: var(--gold);
            font-weight: 600;
        }
        
        .store-name {
            font-weight: 500;
            color: var(--text-primary);
        }
        
        .store-slug {
            font-size: 0.75rem;
            color: var(--text-muted);
        }
        
        .store-type {
            font-size: 0.75rem;
            padding: 4px 8px;
            border-radius: 4px;
            background: var(--bg-panel-hover);
            color: var(--text-secondary);
        }
        
        .store-type.barbershop {
            background: rgba(139, 92, 246, 0.15);
            color: #A78BFA;
        }
        
        .store-type.store {
            background: rgba(59, 130, 246, 0.15);
            color: #60A5FA;
        }
        
        .status-badge {
            font-size: 0.75rem;
            padding: 4px 10px;
            border-radius: 20px;
            font-weight: 500;
        }
        
        .status-active {
            background: rgba(34, 197, 94, 0.15);
            color: var(--success);
        }
        
        .status-trial {
            background: rgba(59, 130, 246, 0.15);
            color: var(--info);
        }
        
        .status-past-due {
            background: rgba(239, 68, 68, 0.15);
            color: var(--danger);
        }
        
        .status-cancelled {
            background: rgba(107, 114, 128, 0.15);
            color: #9CA3AF;
        }
        
        .status-suspended {
            background: rgba(245, 158, 11, 0.15);
            color: var(--warning);
        }
        
        .action-btn {
            width: 32px;
            height: 32px;
            border-radius: 8px;
            border: none;
            background: var(--bg-panel-hover);
            color: var(--text-secondary);
            cursor: pointer;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            transition: all 0.2s;
        }
        
        .action-btn:hover {
            background: var(--gold-light);
            color: var(--gold);
        }
        
        .action-btn.danger:hover {
            background: rgba(239, 68, 68, 0.15);
            color: var(--danger);
        }
        
        /* Delinquent List */
        .delinquent-list {
            display: flex;
            flex-direction: column;
            gap: 1rem;
        }
        
        .delinquent-item {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 1rem;
            background: var(--bg-panel-hover);
            border-radius: 12px;
            border-left: 3px solid var(--danger);
        }
        
        .delinquent-info {
            flex: 1;
        }
        
        .delinquent-name {
            font-weight: 500;
            color: var(--text-primary);
            margin-bottom: 4px;
        }
        
        .delinquent-details {
            font-size: 0.75rem;
            color: var(--text-muted);
        }
        
        .delinquent-actions {
            display: flex;
            gap: 8px;
        }
        
        /* Chart */
        .chart-container {
            height: 300px;
            position: relative;
        }
        
        /* Empty State */
        .empty-state {
            text-align: center;
            padding: 3rem;
            color: var(--text-muted);
        }
        
        .empty-state iconify-icon {
            font-size: 3rem;
            margin-bottom: 1rem;
            opacity: 0.5;
        }
        
        /* Responsive */
        @media (max-width: 1200px) {
            .kpi-grid {
                grid-template-columns: repeat(2, 1fr);
            }
            
            .content-grid {
                grid-template-columns: 1fr;
            }
        }
        
        @media (max-width: 768px) {
            .superadmin-sidebar {
                display: none;
            }
            
            .superadmin-main {
                margin-left: 0;
            }
            
            .kpi-grid {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>
<body>
    <div class="superadmin-layout">
        <!-- Sidebar -->
        <aside class="superadmin-sidebar">
            <div class="sidebar-header">
                <div class="sidebar-logo">
                    <div class="sidebar-logo-icon">
                        <iconify-icon icon="solar:crown-bold"></iconify-icon>
                    </div>
                    <span class="sidebar-logo-text">BarberFlow</span>
                    <span class="sidebar-logo-badge">ADMIN</span>
                </div>
            </div>
            
            <nav class="sidebar-nav">
                <div class="nav-section">
                    <div class="nav-section-title">Principal</div>
                    <a href="/superadmin/" class="nav-link active">
                        <iconify-icon icon="solar:chart-bold"></iconify-icon>
                        <span>Dashboard</span>
                    </a>
                    <a href="/superadmin/stores.php" class="nav-link">
                        <iconify-icon icon="solar:shop-2-bold"></iconify-icon>
                        <span>Lojas</span>
                    </a>
                    <a href="/superadmin/users.php" class="nav-link">
                        <iconify-icon icon="solar:users-group-rounded-bold"></iconify-icon>
                        <span>Usuários</span>
                    </a>
                </div>
                
                <div class="nav-section">
                    <div class="nav-section-title">Financeiro</div>
                    <a href="/superadmin/subscriptions.php" class="nav-link">
                        <iconify-icon icon="solar:card-bold"></iconify-icon>
                        <span>Assinaturas</span>
                    </a>
                    <a href="/superadmin/invoices.php" class="nav-link">
                        <iconify-icon icon="solar:document-bold"></iconify-icon>
                        <span>Faturas</span>
                    </a>
                    <a href="/superadmin/revenue.php" class="nav-link">
                        <iconify-icon icon="solar:wallet-money-bold"></iconify-icon>
                        <span>Receita</span>
                    </a>
                </div>
                
                <div class="nav-section">
                    <div class="nav-section-title">Sistema</div>
                    <a href="/superadmin/plans.php" class="nav-link">
                        <iconify-icon icon="solar:tag-price-bold"></iconify-icon>
                        <span>Planos</span>
                    </a>
                    <a href="/superadmin/features.php" class="nav-link">
                        <iconify-icon icon="solar:flag-bold"></iconify-icon>
                        <span>Feature Flags</span>
                    </a>
                    <a href="/superadmin/settings.php" class="nav-link">
                    </a>
                        <iconify-icon icon="solar:settings-bold"></iconify-icon>
                    </a>
                        <span>Configurações</span>
                    <a href="/superadmin/gateways.php" class="nav-link">
                        <iconify-icon icon="solar:card-transfer-bold"></iconify-icon>
                        <span>Gateways de Pagamento</span>
                    </a>
                    </a>
                    </a>
                    </a>
                </div>
                
                <div class="nav-section">
                    <div class="nav-section-title">Logs</div>
                    <a href="/superadmin/audit.php" class="nav-link">
                        <iconify-icon icon="solar:clipboard-list-bold"></iconify-icon>
                        <span>Auditoria</span>
                    </a>
                    <a href="/superadmin/impersonations.php" class="nav-link">
                        <iconify-icon icon="solar:user-check-bold"></iconify-icon>
                        <span>Impersonations</span>
                    </a>
                </div>
            </nav>
            
            <div class="sidebar-footer">
                <div class="admin-profile">
                    <div class="admin-avatar">SA</div>
                    <div class="admin-info">
                        <div class="admin-name">Super Admin</div>
                        <div class="admin-role">Administrador Global</div>
                    </div>
                </div>
            </div>
        </aside>
        
        <!-- Main Content -->
        <main class="superadmin-main">
            <header class="superadmin-header">
                <h1 class="header-title">Dashboard</h1>
                <div class="header-actions">
                    <button class="btn btn-secondary">
                        <iconify-icon icon="solar:refresh-bold"></iconify-icon>
                        Atualizar
                    </button>
                    <button class="btn btn-primary">
                        <iconify-icon icon="solar:add-circle-bold"></iconify-icon>
                        Nova Loja
                    </button>
                </div>
            </header>
            
            <div class="superadmin-content">
                <!-- KPIs -->
                <div class="kpi-grid">
                    <div class="kpi-card highlight">
                        <div class="kpi-header">
                            <div class="kpi-icon gold">
                                <iconify-icon icon="solar:wallet-money-bold"></iconify-icon>
                            </div>
                            <span class="kpi-trend up">
                                <iconify-icon icon="solar:arrow-up-bold"></iconify-icon>
                                12%
                            </span>
                        </div>
                        <div class="kpi-value"><?= formatMoney($mrr) ?></div>
                        <div class="kpi-label">MRR (Receita Mensal)</div>
                    </div>
                    
                    <div class="kpi-card">
                        <div class="kpi-header">
                            <div class="kpi-icon green">
                                <iconify-icon icon="solar:shop-2-bold"></iconify-icon>
                            </div>
                            <span class="kpi-trend up">
                                <iconify-icon icon="solar:arrow-up-bold"></iconify-icon>
                                +<?= $newStoresThisMonth ?>
                            </span>
                        </div>
                        <div class="kpi-value"><?= $activeStores ?></div>
                        <div class="kpi-label">Lojas Ativas</div>
                    </div>
                    
                    <div class="kpi-card">
                        <div class="kpi-header">
                            <div class="kpi-icon blue">
                                <iconify-icon icon="solar:hourglass-bold"></iconify-icon>
                            </div>
                        </div>
                        <div class="kpi-value"><?= $trialStores ?></div>
                        <div class="kpi-label">Em Trial</div>
                    </div>
                    
                    <div class="kpi-card">
                        <div class="kpi-header">
                            <div class="kpi-icon red">
                                <iconify-icon icon="solar:danger-triangle-bold"></iconify-icon>
                            </div>
                        </div>
                        <div class="kpi-value"><?= $pastDueStores ?></div>
                        <div class="kpi-label">Inadimplentes</div>
                    </div>
                </div>
                
                <!-- Content Grid -->
                <div class="content-grid">
                    <!-- Recent Stores -->
                    <div class="panel">
                        <div class="panel-header">
                            <h2 class="panel-title">Lojas Recentes</h2>
                            <a href="/superadmin/stores.php" class="panel-action">Ver todas</a>
                        </div>
                        <div class="panel-body" style="padding: 0;">
                            <?php if (empty($recentStores)): ?>
                                <div class="empty-state">
                                    <iconify-icon icon="solar:shop-2-bold"></iconify-icon>
                                    <p>Nenhuma loja cadastrada ainda</p>
                                </div>
                            <?php else: ?>
                                <table class="stores-table">
                                    <thead>
                                        <tr>
                                            <th>Loja</th>
                                            <th>Tipo</th>
                                            <th>Status</th>
                                            <th>Pedidos</th>
                                            <th>Ações</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($recentStores as $store): ?>
                                            <tr>
                                                <td>
                                                    <div class="store-info">
                                                        <div class="store-avatar">
                                                            <?= strtoupper(substr($store['name'], 0, 2)) ?>
                                                        </div>
                                                        <div>
                                                            <div class="store-name"><?= htmlspecialchars($store['name']) ?></div>
                                                            <div class="store-slug"><?= htmlspecialchars($store['slug']) ?></div>
                                                        </div>
                                                    </div>
                                                </td>
                                                <td>
                                                    <span class="store-type <?= $store['type'] ?>">
                                                        <?= $store['type'] === 'barbershop' ? 'Barbearia' : 'Loja' ?>
                                                    </span>
                                                </td>
                                                <td><?= getStatusBadge($store['status']) ?></td>
                                                <td><?= $store['orders_count'] ?? 0 ?></td>
                                                <td>
                                                    <button class="action-btn" title="Impersonar" onclick="impersonate(<?= $store['id'] ?>)">
                                                        <iconify-icon icon="solar:login-2-bold"></iconify-icon>
                                                    </button>
                                                    <button class="action-btn" title="Editar">
                                                        <iconify-icon icon="solar:pen-bold"></iconify-icon>
                                                    </button>
                                                    <button class="action-btn danger" title="Suspender">
                                                        <iconify-icon icon="solar:lock-bold"></iconify-icon>
                                                    </button>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            <?php endif; ?>
                        </div>
                    </div>
                    
                    <!-- Delinquent Stores -->
                    <div class="panel">
                        <div class="panel-header">
                            <h2 class="panel-title">⚠️ Inadimplentes</h2>
                        </div>
                        <div class="panel-body">
                            <?php if (empty($delinquentStores)): ?>
                                <div class="empty-state">
                                    <iconify-icon icon="solar:check-circle-bold"></iconify-icon>
                                    <p>Nenhuma loja inadimplente</p>
                                </div>
                            <?php else: ?>
                                <div class="delinquent-list">
                                    <?php foreach ($delinquentStores as $store): ?>
                                        <div class="delinquent-item">
                                            <div class="store-avatar">
                                                <?= strtoupper(substr($store['name'], 0, 2)) ?>
                                            </div>
                                            <div class="delinquent-info">
                                                <div class="delinquent-name"><?= htmlspecialchars($store['name']) ?></div>
                                                <div class="delinquent-details">
                                                    Vencido há <?= isset($store['current_period_end']) ? floor((time() - strtotime($store['current_period_end'])) / 86400) : '?' ?> dias
                                                </div>
                                            </div>
                                            <div class="delinquent-actions">
                                                <button class="action-btn" title="Enviar lembrete">
                                                    <iconify-icon icon="solar:letter-bold"></iconify-icon>
                                                </button>
                                                <button class="action-btn danger" title="Bloquear">
                                                    <iconify-icon icon="solar:lock-bold"></iconify-icon>
                                                </button>
                                            </div>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
                
                <!-- Charts Row -->
                <div class="content-grid" style="margin-top: 1.5rem;">
                    <div class="panel">
                        <div class="panel-header">
                            <h2 class="panel-title">Crescimento de Lojas</h2>
                        </div>
                        <div class="panel-body">
                            <div class="chart-container">
                                <canvas id="growthChart"></canvas>
                            </div>
                        </div>
                    </div>
                    
                    <div class="panel">
                        <div class="panel-header">
                            <h2 class="panel-title">Distribuição por Tipo</h2>
                        </div>
                        <div class="panel-body">
                            <div class="chart-container">
                                <canvas id="typeChart"></canvas>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </main>
    </div>
    
    <script>
        // Growth Chart
        const growthCtx = document.getElementById('growthChart').getContext('2d');
        new Chart(growthCtx, {
            type: 'line',
            data: {
                labels: ['Jan', 'Fev', 'Mar', 'Abr', 'Mai', 'Jun', 'Jul', 'Ago', 'Set', 'Out', 'Nov', 'Dez'],
                datasets: [{
                    label: 'Lojas Ativas',
                    data: [5, 8, 12, 18, 25, 32, 40, 48, 55, 62, 70, <?= $activeStores ?>],
                    borderColor: '#CCA43B',
                    backgroundColor: 'rgba(204, 164, 59, 0.1)',
                    tension: 0.4,
                    fill: true
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        display: false
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        grid: {
                            color: 'rgba(255, 255, 255, 0.05)'
                        },
                        ticks: {
                            color: '#666'
                        }
                    },
                    x: {
                        grid: {
                            display: false
                        },
                        ticks: {
                            color: '#666'
                        }
                    }
                }
            }
        });
        
        // Type Distribution Chart
        const typeCtx = document.getElementById('typeChart').getContext('2d');
        new Chart(typeCtx, {
            type: 'doughnut',
            data: {
                labels: ['Barbearias', 'Lojas'],
                datasets: [{
                    data: [35, 65],
                    backgroundColor: ['#A78BFA', '#60A5FA'],
                    borderWidth: 0
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        position: 'bottom',
                        labels: {
                            color: '#B3B3B3',
                            padding: 20
                        }
                    }
                },
                cutout: '70%'
            }
        });
        
        // Impersonate function
        function impersonate(storeId) {
            if (confirm('Deseja acessar esta loja como administrador?')) {
                window.location.href = '/superadmin/impersonate.php?store_id=' + storeId;
            }
        }
    </script>
</body>
</html>
