<?php
/**
 * Gerenciamento de Lojas - Super Admin
 */
require_once __DIR__ . '/../../../includes/config.php';

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

$superAdmin = getSuperAdmin();
$pdo = getDB();

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

// Construir query
$where = "WHERE deleted_at IS NULL";
$params = [];

if ($search) {
    $where .= " AND (name LIKE ? OR nome LIKE ? OR email LIKE ? OR slug LIKE ?)";
    $searchParam = "%{$search}%";
    $params = array_merge($params, [$searchParam, $searchParam, $searchParam, $searchParam]);
}

if ($statusFilter) {
    $where .= " AND status = ?";
    $params[] = $statusFilter;
}

// Total
$stmtCount = $pdo->prepare("SELECT COUNT(*) FROM stores {$where}");
$stmtCount->execute($params);
$total = $stmtCount->fetchColumn();
$totalPages = ceil($total / $perPage);

// Buscar lojas
$stmt = $pdo->prepare("
    SELECT s.*, p.name as plan_name,
           (SELECT COUNT(*) FROM orders o WHERE o.store_id = s.id) as orders_count,
           (SELECT COALESCE(SUM(total_amount), 0) FROM orders o WHERE o.store_id = s.id) as total_revenue
    FROM stores s
    LEFT JOIN plans p ON s.plan_id = p.id
    {$where}
    ORDER BY s.created_at DESC
    LIMIT {$perPage} OFFSET {$offset}
");
$stmt->execute($params);
$stores = $stmt->fetchAll(PDO::FETCH_ASSOC);

$pageTitle = 'Gerenciar Lojas';
$currentPage = 'stores';

include __DIR__ . '/../includes/header.php';
?>
    <div class="app-container">
        <?php include __DIR__ . '/../includes/sidebar.php'; ?>

        <main class="main-content">
            <?php include __DIR__ . '/../includes/topbar.php'; ?>

            <div class="content-area">
                <!-- Page Header -->

                <?php if (isset($_GET["success"])): ?>
                    <div style="background: rgba(34,197,94,0.1); border: 1px solid rgba(34,197,94,0.3); color: var(--success); padding: 1rem; border-radius: var(--radius-md); margin-bottom: 1.5rem; display: flex; align-items: center; gap: 0.75rem;">
                        <iconify-icon icon="solar:check-circle-bold" width="24"></iconify-icon>
                        <span><?php
                            if ($_GET["success"] === "store_deleted") echo "Loja excluída com sucesso!";
                        ?></span>
                    </div>
                <?php endif; ?>

                <?php if (isset($_GET["error"])): ?>
                    <div style="background: rgba(239,68,68,0.1); border: 1px solid rgba(239,68,68,0.3); color: var(--danger); padding: 1rem; border-radius: var(--radius-md); margin-bottom: 1.5rem; display: flex; align-items: center; gap: 0.75rem;">
                        <iconify-icon icon="solar:danger-circle-bold" width="24"></iconify-icon>
                        <span><?php
                            if ($_GET["error"] === "invalid_id") echo "ID inválido!";
                            elseif ($_GET["error"] === "store_not_found") echo "Loja não encontrada!";
                            elseif ($_GET["error"] === "delete_failed") echo "Erro ao excluir loja!";
                        ?></span>
                    </div>
                <?php endif; ?>
                
                <div class="page-header">
                    <div>
                        <h2>Gerenciar Lojas</h2>
                        <p><?= $total ?> lojas cadastradas</p>
                    </div>
                    <a href="/pages/superadmin/stores/create.php" class="btn btn-primary">
                        <iconify-icon icon="solar:add-circle-bold"></iconify-icon>
                        Nova Loja
                    </a>
                </div>

                <!-- Filters -->
                <div class="panel">
                    <form method="GET" class="flex gap-4 items-center" style="flex-wrap: wrap;">
                        <div style="flex: 1; min-width: 200px;">
                            <label class="form-label">Buscar</label>
                            <div style="position: relative;">
                                <iconify-icon icon="solar:magnifer-bold" style="position: absolute; left: 12px; top: 50%; transform: translateY(-50%); color: var(--text-muted);"></iconify-icon>
                                <input type="text" name="search" value="<?= htmlspecialchars($search) ?>"
                                       placeholder="Nome, email ou slug..."
                                       class="form-input" style="padding-left: 40px;">
                            </div>
                        </div>
                        <div style="width: 160px;">
                            <label class="form-label">Status</label>
                            <select name="status" class="form-select">
                                <option value="">Todos</option>
                                <option value="active" <?= $statusFilter === 'active' ? 'selected' : '' ?>>Ativos</option>
                                <option value="trial" <?= $statusFilter === 'trial' ? 'selected' : '' ?>>Trial</option>
                                <option value="suspended" <?= $statusFilter === 'suspended' ? 'selected' : '' ?>>Suspensos</option>
                                <option value="inactive" <?= $statusFilter === 'inactive' ? 'selected' : '' ?>>Inativos</option>
                            </select>
                        </div>
                        <div style="padding-top: 24px;">
                            <button type="submit" class="btn btn-primary">
                                <iconify-icon icon="solar:filter-bold"></iconify-icon>
                                Filtrar
                            </button>
                        </div>
                    </form>
                </div>

                <!-- Stores Table -->
                <div class="panel" style="padding: 0; overflow: hidden;">
                    <div class="table-responsive">
                        <table class="data-table">
                            <thead>
                                <tr>
                                    <th>Loja</th>
                                    <th>Status</th>
                                    <th>Plano</th>
                                    <th>Pedidos</th>
                                    <th>Faturamento</th>
                                    <th>Criada em</th>
                                    <th style="text-align: right;">Ações</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($stores as $store): ?>
                                <tr>
                                    <td>
                                        <div class="flex items-center gap-3">
                                            <?php
                                            $storeName = $store['name'] ?? $store['nome'] ?? 'Loja';
                                            $initial = strtoupper(substr($storeName, 0, 1));
                                            ?>
                                            <?php if (!empty($store['logo'])): ?>
                                            <img src="<?= htmlspecialchars($store['logo']) ?>" style="width: 40px; height: 40px; border-radius: 8px; object-fit: cover;">
                                            <?php else: ?>
                                            <div style="width: 40px; height: 40px; border-radius: 8px; background: var(--gold); display: flex; align-items: center; justify-content: center; color: #1A1A1A; font-weight: 700; flex-shrink: 0;">
                                                <?= $initial ?>
                                            </div>
                                            <?php endif; ?>
                                            <div style="min-width: 0;">
                                                <div class="font-medium"><?= htmlspecialchars($storeName) ?></div>
                                                <div class="text-muted text-sm"><?= htmlspecialchars($store['slug'] ?? $store['subdomain'] ?? '-') ?>.duolead.com.br</div>
                                            </div>
                                        </div>
                                    </td>
                                    <td data-label="Status">
                                        <?php
                                        $status = $store['status'] ?? 'active';
                                        $statusLabel = match($status) {
                                            'active' => 'Ativo',
                                            'trial' => 'Trial',
                                            'suspended' => 'Suspenso',
                                            default => 'Inativo'
                                        };
                                        ?>
                                        <span class="status-badge status-<?= $status ?>"><?= $statusLabel ?></span>
                                    </td>
                                    <td data-label="Plano">
                                        <span class="text-sm" style="color: var(--gold);"><?= htmlspecialchars($store['plan_name'] ?? 'Sem plano') ?></span>
                                    </td>
                                    <td data-label="Pedidos"><?= $store['orders_count'] ?? 0 ?></td>
                                    <td data-label="Faturamento" class="text-gold"><?= formatMoney($store['total_revenue'] ?? 0) ?></td>
                                    <td data-label="Criada em" class="text-muted"><?= date('d/m/Y', strtotime($store['created_at'] ?? 'now')) ?></td>
                                    <td>
                                        <div class="flex gap-2" style="justify-content: flex-end;">
                                            <a href="/pages/superadmin/stores/impersonate.php?store_id=<?= $store['id'] ?>"
                                               class="btn btn-secondary btn-sm" title="Acessar como dono">
                                                <iconify-icon icon="solar:eye-bold"></iconify-icon>
                                            </a>
                                            <a href="/pages/superadmin/stores/edit.php?id=<?= $store['id'] ?>"
                                               class="btn btn-secondary btn-sm" title="Editar">
                                                <iconify-icon icon="solar:pen-bold"></iconify-icon>
                                            </a>
                                            <button onclick="confirmDelete(<?= $store['id'] ?>)"
                                                    class="btn btn-danger btn-sm" title="Excluir">
                                                <iconify-icon icon="solar:trash-bin-trash-bold"></iconify-icon>
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                                <?php endforeach; ?>

                                <?php if (empty($stores)): ?>
                                <tr>
                                    <td colspan="7" style="text-align: center; padding: 3rem;">
                                        <iconify-icon icon="solar:shop-bold" style="font-size: 3rem; color: var(--text-muted); display: block; margin-bottom: 1rem;"></iconify-icon>
                                        <p class="text-muted">Nenhuma loja encontrada</p>
                                    </td>
                                </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>

                <!-- Pagination -->
                <?php if ($totalPages > 1): ?>
                <div class="flex gap-2" style="justify-content: center; margin-top: 1.5rem;">
                    <?php for ($i = 1; $i <= min($totalPages, 10); $i++): ?>
                    <a href="?page=<?= $i ?>&search=<?= urlencode($search) ?>&status=<?= urlencode($statusFilter) ?>"
                       class="btn <?= $i === $page ? 'btn-primary' : 'btn-secondary' ?> btn-sm">
                        <?= $i ?>
                    </a>
                    <?php endfor; ?>
                </div>
                <?php endif; ?>
            </div>
        </main>
    </div>

    <script>
        function confirmDelete(storeId) {
            if (confirm('Tem certeza que deseja excluir esta loja? Esta ação não pode ser desfeita.')) {
                window.location.href = '/pages/superadmin/stores/delete.php?id=' + storeId;
            }
        }
    </script>
<?php include __DIR__ . '/../includes/footer.php'; ?>
