<?php
/**
 * ============================================================
 * Super Admin - Gestão de Lojas
 * ============================================================
 */

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

$isSuperAdmin = true;

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

// Filtros
$search = $_GET['search'] ?? '';
$status = $_GET['status'] ?? '';
$type = $_GET['type'] ?? '';
$page = max(1, (int)($_GET['page'] ?? 1));
$perPage = 20;
$offset = ($page - 1) * $perPage;

try {
    $db = getDB();
    
    // Construir query
    $where = ["deleted_at IS NULL"];
    $params = [];
    
    if ($search) {
        $where[] = "(name LIKE ? OR slug LIKE ? OR email LIKE ?)";
        $params[] = "%{$search}%";
        $params[] = "%{$search}%";
        $params[] = "%{$search}%";
    }
    
    if ($status) {
        $where[] = "status = ?";
        $params[] = $status;
    }
    
    if ($type) {
        $where[] = "type = ?";
        $params[] = $type;
    }
    
    $whereClause = implode(' AND ', $where);
    
    // Total de registros
    $stmt = $db->prepare("SELECT COUNT(*) as total FROM stores WHERE {$whereClause}");
    $stmt->execute($params);
    $total = $stmt->fetch()['total'];
    $totalPages = ceil($total / $perPage);
    
    // Buscar lojas
    $stmt = $db->prepare("
        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,
               (SELECT COUNT(*) FROM users u WHERE u.store_id = s.id) as users_count
        FROM stores s
        WHERE {$whereClause}
        ORDER BY s.created_at DESC
        LIMIT {$perPage} OFFSET {$offset}
    ");
    $stmt->execute($params);
    $stores = $stmt->fetchAll();
    
} catch (Exception $e) {
    $stores = [];
    $total = 0;
    $totalPages = 0;
}

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 = 'Gestão de Lojas';
?>
<!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 Admin</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/iconify-icon@1.0.7/dist/iconify-icon.min.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;
        }
        
        .layout {
            display: flex;
            min-height: 100vh;
        }
        
        /* Sidebar - simplificado */
        .sidebar {
            width: 280px;
            background: var(--bg-panel);
            border-right: 1px solid var(--border-light);
            position: fixed;
            height: 100vh;
            padding: 1.5rem;
        }
        
        .sidebar-logo {
            display: flex;
            align-items: center;
            gap: 12px;
            margin-bottom: 2rem;
        }
        
        .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;
        }
        
        .logo-text {
            font-size: 1.25rem;
            font-weight: 700;
        }
        
        .nav-link {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 0.75rem 1rem;
            border-radius: 8px;
            color: var(--text-secondary);
            text-decoration: none;
            margin-bottom: 4px;
            transition: all 0.2s;
        }
        
        .nav-link:hover, .nav-link.active {
            background: var(--gold-light);
            color: var(--gold);
        }
        
        /* Main */
        .main {
            flex: 1;
            margin-left: 280px;
        }
        
        .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;
        }
        
        .content {
            padding: 2rem;
        }
        
        /* Filters */
        .filters {
            display: flex;
            gap: 1rem;
            margin-bottom: 1.5rem;
            flex-wrap: wrap;
        }
        
        .search-box {
            flex: 1;
            min-width: 250px;
            position: relative;
        }
        
        .search-box input {
            width: 100%;
            padding: 0.75rem 1rem 0.75rem 2.5rem;
            background: var(--bg-panel);
            border: 1px solid var(--border-light);
            border-radius: 8px;
            color: var(--text-primary);
            font-size: 0.875rem;
        }
        
        .search-box iconify-icon {
            position: absolute;
            left: 0.75rem;
            top: 50%;
            transform: translateY(-50%);
            color: var(--text-muted);
        }
        
        .filter-select {
            padding: 0.75rem 1rem;
            background: var(--bg-panel);
            border: 1px solid var(--border-light);
            border-radius: 8px;
            color: var(--text-primary);
            font-size: 0.875rem;
            min-width: 150px;
        }
        
        .btn {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            padding: 0.75rem 1.25rem;
            border-radius: 8px;
            font-size: 0.875rem;
            font-weight: 500;
            cursor: pointer;
            border: none;
            transition: all 0.2s;
            text-decoration: none;
        }
        
        .btn-primary {
            background: linear-gradient(135deg, var(--gold), #B8962F);
            color: #000;
        }
        
        /* Table */
        .panel {
            background: var(--bg-panel);
            border-radius: 16px;
            border: 1px solid var(--border-light);
            overflow: hidden;
        }
        
        .table {
            width: 100%;
            border-collapse: collapse;
        }
        
        .table th, .table td {
            padding: 1rem 1.25rem;
            text-align: left;
            border-bottom: 1px solid var(--border-light);
        }
        
        .table th {
            font-size: 0.75rem;
            text-transform: uppercase;
            letter-spacing: 0.05em;
            color: var(--text-muted);
            background: var(--bg-panel-hover);
        }
        
        .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;
        }
        
        .store-slug {
            font-size: 0.75rem;
            color: var(--text-muted);
        }
        
        .store-type {
            font-size: 0.75rem;
            padding: 4px 8px;
            border-radius: 4px;
        }
        
        .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: transparent;
            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);
        }
        
        /* Pagination */
        .pagination {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 1rem 1.25rem;
            border-top: 1px solid var(--border-light);
        }
        
        .pagination-info {
            font-size: 0.875rem;
            color: var(--text-muted);
        }
        
        .pagination-links {
            display: flex;
            gap: 4px;
        }
        
        .pagination-links a, .pagination-links span {
            padding: 0.5rem 0.75rem;
            border-radius: 6px;
            font-size: 0.875rem;
            text-decoration: none;
            color: var(--text-secondary);
        }
        
        .pagination-links a:hover {
            background: var(--bg-panel-hover);
        }
        
        .pagination-links .active {
            background: var(--gold);
            color: #000;
        }
        
        /* Empty state */
        .empty-state {
            text-align: center;
            padding: 4rem 2rem;
            color: var(--text-muted);
        }
        
        .empty-state iconify-icon {
            font-size: 4rem;
            margin-bottom: 1rem;
            opacity: 0.5;
        }
    </style>
</head>
<body>
    <div class="layout">
        <!-- Sidebar -->
        <aside class="sidebar">
            <div class="sidebar-logo">
                <div class="logo-icon">
                    <iconify-icon icon="solar:crown-bold"></iconify-icon>
                </div>
                <span class="logo-text">BarberFlow</span>
            </div>
            
            <nav>
                <a href="/superadmin/" class="nav-link">
                    <iconify-icon icon="solar:chart-bold"></iconify-icon>
                    Dashboard
                </a>
                <a href="/superadmin/stores.php" class="nav-link active">
                    <iconify-icon icon="solar:shop-2-bold"></iconify-icon>
                    Lojas
                </a>
                <a href="/superadmin/subscriptions.php" class="nav-link">
                    <iconify-icon icon="solar:card-bold"></iconify-icon>
                    Assinaturas
                </a>
                <a href="/superadmin/plans.php" class="nav-link">
                    <iconify-icon icon="solar:tag-price-bold"></iconify-icon>
                    Planos
                </a>
                <a href="/superadmin/settings.php" class="nav-link">
                </a>
                    <iconify-icon icon="solar:settings-bold"></iconify-icon>
                </a>
                    Configurações
                <a href="/superadmin/gateways.php" class="nav-link">
                    <iconify-icon icon="solar:card-transfer-bold"></iconify-icon>
                    Gateways de Pagamento
                </a>
                </a>
                </a>
                </a>
            </nav>
        </aside>
        
        <!-- Main -->
        <main class="main">
            <header class="header">
                <h1 class="header-title">Gestão de Lojas</h1>
                <button class="btn btn-primary">
                    <iconify-icon icon="solar:add-circle-bold"></iconify-icon>
                    Nova Loja
                </button>
            </header>
            
            <div class="content">
                <!-- Filters -->
                <form class="filters" method="GET">
                    <div class="search-box">
                        <iconify-icon icon="solar:magnifer-bold"></iconify-icon>
                        <input type="text" name="search" placeholder="Buscar por nome, slug ou email..." value="<?= htmlspecialchars($search) ?>">
                    </div>
                    
                    <select name="status" class="filter-select" onchange="this.form.submit()">
                        <option value="">Todos os status</option>
                        <option value="active" <?= $status === 'active' ? 'selected' : '' ?>>Ativo</option>
                        <option value="trial" <?= $status === 'trial' ? 'selected' : '' ?>>Trial</option>
                        <option value="past_due" <?= $status === 'past_due' ? 'selected' : '' ?>>Inadimplente</option>
                        <option value="suspended" <?= $status === 'suspended' ? 'selected' : '' ?>>Suspenso</option>
                        <option value="cancelled" <?= $status === 'cancelled' ? 'selected' : '' ?>>Cancelado</option>
                    </select>
                    
                    <select name="type" class="filter-select" onchange="this.form.submit()">
                        <option value="">Todos os tipos</option>
                        <option value="barbershop" <?= $type === 'barbershop' ? 'selected' : '' ?>>Barbearia</option>
                        <option value="store" <?= $type === 'store' ? 'selected' : '' ?>>Loja</option>
                    </select>
                </form>
                
                <!-- Table -->
                <div class="panel">
                    <?php if (empty($stores)): ?>
                        <div class="empty-state">
                            <iconify-icon icon="solar:shop-2-bold"></iconify-icon>
                            <h3>Nenhuma loja encontrada</h3>
                            <p>Tente ajustar os filtros ou criar uma nova loja.</p>
                        </div>
                    <?php else: ?>
                        <table class="table">
                            <thead>
                                <tr>
                                    <th>Loja</th>
                                    <th>Tipo</th>
                                    <th>Status</th>
                                    <th>Pedidos</th>
                                    <th>Produtos</th>
                                    <th>Criada em</th>
                                    <th>Ações</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($stores 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']) ?>.barberflow.com</div>
                                                </div>
                                            </div>
                                        </td>
                                        <td>
                                            <span class="store-type <?= $store['type'] ?>">
                                                <?= $store['type'] === 'barbershop' ? '💈 Barbearia' : '🛒 Loja' ?>
                                            </span>
                                        </td>
                                        <td><?= getStatusBadge($store['status']) ?></td>
                                        <td><?= number_format($store['orders_count']) ?></td>
                                        <td><?= number_format($store['products_count']) ?></td>
                                        <td><?= date('d/m/Y', strtotime($store['created_at'])) ?></td>
                                        <td>
                                            <button class="action-btn" title="Acessar como Dono" onclick="window.location.href='/superadmin/impersonate.php?store_id=<?= $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" title="Ver detalhes">
                                                <iconify-icon icon="solar:eye-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>
                        
                        <!-- Pagination -->
                        <div class="pagination">
                            <div class="pagination-info">
                                Mostrando <?= count($stores) ?> de <?= $total ?> lojas
                            </div>
                            <div class="pagination-links">
                                <?php if ($page > 1): ?>
                                    <a href="?page=<?= $page - 1 ?>&search=<?= urlencode($search) ?>&status=<?= urlencode($status) ?>&type=<?= urlencode($type) ?>">← Anterior</a>
                                <?php endif; ?>
                                
                                <?php for ($i = max(1, $page - 2); $i <= min($totalPages, $page + 2); $i++): ?>
                                    <?php if ($i === $page): ?>
                                        <span class="active"><?= $i ?></span>
                                    <?php else: ?>
                                        <a href="?page=<?= $i ?>&search=<?= urlencode($search) ?>&status=<?= urlencode($status) ?>&type=<?= urlencode($type) ?>"><?= $i ?></a>
                                    <?php endif; ?>
                                <?php endfor; ?>
                                
                                <?php if ($page < $totalPages): ?>
                                    <a href="?page=<?= $page + 1 ?>&search=<?= urlencode($search) ?>&status=<?= urlencode($status) ?>&type=<?= urlencode($type) ?>">Próxima →</a>
                                <?php endif; ?>
                            </div>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </main>
    </div>
</body>
</html>
