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

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

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

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

// Query base
$where = "WHERE 1=1";
$params = [];

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

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

// Buscar assinaturas
$stmt = $pdo->prepare("
    SELECT sub.*, 
           s.name as store_name, s.slug,
           p.name as plan_name, p.price_monthly
    FROM subscriptions sub
    LEFT JOIN stores s ON sub.store_id = s.id
    LEFT JOIN plans p ON sub.plan_id = p.id
    {$where}
    ORDER BY sub.created_at DESC
    LIMIT {$perPage} OFFSET {$offset}
");
$stmt->execute($params);
$subscriptions = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Métricas
$mrrResult = $pdo->query("SELECT COALESCE(SUM(p.price_monthly), 0) as mrr FROM subscriptions s JOIN plans p ON s.plan_id = p.id WHERE s.status = 'active'")->fetch();
$mrr = $mrrResult['mrr'] ?? 0;
$totalActive = $pdo->query("SELECT COUNT(*) FROM subscriptions WHERE status = 'active'")->fetchColumn();
$totalTrial = $pdo->query("SELECT COUNT(*) FROM subscriptions WHERE status = 'trialing'")->fetchColumn();
$totalCanceled = $pdo->query("SELECT COUNT(*) FROM subscriptions WHERE status = 'canceled'")->fetchColumn();

$pageTitle = 'Gerenciar Assinaturas';
$currentPage = 'subscriptions';

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">
                <!-- KPIs -->
                <div class="kpi-grid" style="grid-template-columns: repeat(4, 1fr);">
                    <div class="kpi-card highlight">
                        <div class="kpi-label">MRR Total</div>
                        <div class="kpi-value gold"><?= formatMoney($mrr) ?></div>
                    </div>
                    <div class="kpi-card">
                        <div class="kpi-label">Assinaturas Ativas</div>
                        <div class="kpi-value"><?= $totalActive ?></div>
                    </div>
                    <div class="kpi-card">
                        <div class="kpi-label">Em Trial</div>
                        <div class="kpi-value"><?= $totalTrial ?></div>
                    </div>
                    <div class="kpi-card">
                        <div class="kpi-label">Canceladas</div>
                        <div class="kpi-value text-danger"><?= $totalCanceled ?></div>
                    </div>
                </div>

                <!-- Page Header -->
                <div class="page-header">
                    <div>
                        <h2>Assinaturas</h2>
                        <p><?= $total ?> assinaturas no total</p>
                    </div>
                </div>

                <!-- Filters -->
                <div class="panel">
                    <form method="GET" class="flex gap-4 items-center">
                        <div style="width: 200px;">
                            <label class="form-label">Status</label>
                            <select name="status" class="form-select" onchange="this.form.submit()">
                                <option value="">Todos</option>
                                <option value="active" <?= $statusFilter === 'active' ? 'selected' : '' ?>>Ativas</option>
                                <option value="trialing" <?= $statusFilter === 'trialing' ? 'selected' : '' ?>>Trial</option>
                                <option value="past_due" <?= $statusFilter === 'past_due' ? 'selected' : '' ?>>Inadimplentes</option>
                                <option value="canceled" <?= $statusFilter === 'canceled' ? 'selected' : '' ?>>Canceladas</option>
                            </select>
                        </div>
                    </form>
                </div>

                <!-- Subscriptions Table -->
                <div class="panel" style="padding: 0; overflow: hidden;">
                    <table class="data-table">
                        <thead>
                            <tr>
                                <th>Loja</th>
                                <th>Plano</th>
                                <th>Valor</th>
                                <th>Status</th>
                                <th>Início</th>
                                <th>Próx. Cobrança</th>
                                <th style="text-align: right;">Ações</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($subscriptions as $sub): ?>
                            <tr>
                                <td>
                                    <div class="font-medium"><?= htmlspecialchars($sub['store_name'] ?? 'N/A') ?></div>
                                    <div class="text-muted text-sm"><?= htmlspecialchars($sub['slug'] ?? '-') ?></div>
                                </td>
                                <td>
                                    <span class="text-gold font-medium"><?= htmlspecialchars($sub['plan_name'] ?? 'N/A') ?></span>
                                </td>
                                <td><?= formatMoney($sub['price_monthly'] ?? 0) ?>/mês</td>
                                <td>
                                    <?php 
                                    $status = $sub['status'] ?? 'active';
                                    $statusClass = match($status) {
                                        'active' => 'status-active',
                                        'trialing' => 'status-trial',
                                        'past_due' => 'status-past_due',
                                        default => 'status-inactive'
                                    };
                                    $statusLabel = match($status) {
                                        'active' => 'Ativa',
                                        'trialing' => 'Trial',
                                        'past_due' => 'Inadimplente',
                                        'canceled' => 'Cancelada',
                                        default => ucfirst($status)
                                    };
                                    ?>
                                    <span class="status-badge <?= $statusClass ?>"><?= $statusLabel ?></span>
                                </td>
                                <td class="text-muted"><?= date('d/m/Y', strtotime($sub['created_at'] ?? 'now')) ?></td>
                                <td class="text-muted"><?= $sub['next_billing_date'] ? date('d/m/Y', strtotime($sub['next_billing_date'])) : '-' ?></td>
                                <td>
                                    <div class="flex gap-2" style="justify-content: flex-end;">
                                        <a href="/pages/superadmin/subscription-edit.php?id=<?= $sub['id'] ?>" 
                                           class="btn btn-secondary btn-sm" title="Editar">
                                            <iconify-icon icon="solar:pen-bold"></iconify-icon>
                                        </a>
                                        <?php if ($sub['status'] === 'active'): ?>
                                        <button onclick="cancelSubscription(<?= $sub['id'] ?>)" 
                                                class="btn btn-danger btn-sm" title="Cancelar">
                                            <iconify-icon icon="solar:close-circle-bold"></iconify-icon>
                                        </button>
                                        <?php endif; ?>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>

                            <?php if (empty($subscriptions)): ?>
                            <tr>
                                <td colspan="7" style="text-align: center; padding: 3rem;">
                                    <iconify-icon icon="solar:wallet-bold" style="font-size: 3rem; color: var(--text-muted); margin-bottom: 1rem;"></iconify-icon>
                                    <p class="text-muted">Nenhuma assinatura encontrada</p>
                                </td>
                            </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </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 ?>&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 cancelSubscription(subId) {
            if (confirm('Tem certeza que deseja cancelar esta assinatura?')) {
                window.location.href = '/pages/superadmin/subscription-cancel.php?id=' + subId;
            }
        }
    </script>
<?php include __DIR__ . '/../includes/footer.php'; ?>
