<?php
$pageTitle  = 'Subscriptions';
$activePage = 'subscriptions';

require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/../db.php';

$flash     = '';
$flashType = 'success';

// ─── POST actions ────────────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && csrf_verify()) {
    $action  = $_POST['action'] ?? '';
    $chat_id = (int)($_POST['chat_id'] ?? 0);

    if ($action === 'grant' && $chat_id) {
        $plan = $_POST['plan_type'] ?? 'monthly';
        $validPlans = ['monthly' => 30, '3month' => 90, '6month' => 180, '12month' => 365];
        if (!isset($validPlans[$plan])) {
            $plan = 'monthly';
        }
        $days = $validPlans[$plan];

        // Check if user exists
        $exists = $pdo->prepare("SELECT chat_id FROM users WHERE chat_id = ?");
        $exists->execute([$chat_id]);
        if (!$exists->fetchColumn()) {
            // Auto-create minimal user record so FK doesn't break
            $pdo->prepare("INSERT IGNORE INTO users (chat_id) VALUES (?)")->execute([$chat_id]);
        }

        // Extend or create subscription
        $existing = $pdo->prepare("SELECT id, expires_at FROM subscriptions WHERE chat_id = ? AND status = 'active' AND expires_at > NOW() LIMIT 1");
        $existing->execute([$chat_id]);
        $row = $existing->fetch(PDO::FETCH_ASSOC);

        if ($row) {
            $pdo->prepare("UPDATE subscriptions SET expires_at = DATE_ADD(expires_at, INTERVAL ? DAY), plan_type = ? WHERE id = ?")
                ->execute([$days, $plan, $row['id']]);
            $flash = "Extended subscription for #{$chat_id} by {$days} days (plan: {$plan}).";
        } else {
            $pdo->prepare("INSERT INTO subscriptions (chat_id, plan_type, status, expires_at, granted_by) VALUES (?, ?, 'active', DATE_ADD(NOW(), INTERVAL ? DAY), 'admin')")
                ->execute([$chat_id, $plan, $days]);
            $flash = "Granted {$plan} subscription to #{$chat_id}.";
        }

        // Notify user on Telegram
        $planLabels = ['monthly' => '1 Month', '3month' => '3 Months', '6month' => '6 Months', '12month' => '12 Months'];
        $notif = "⭐ <b>Premium Subscription Activated!</b>\n\nYour <b>{$planLabels[$plan]}</b> subscription has been granted by the admin.\n\nEnjoy unlimited diet &amp; workout plans!";
        @file_get_contents("https://api.telegram.org/bot{$config['telegram_token']}/sendMessage?" .
            http_build_query(['chat_id' => $chat_id, 'text' => $notif, 'parse_mode' => 'HTML']));

    } elseif ($action === 'revoke' && $chat_id) {
        $pdo->prepare("UPDATE subscriptions SET status = 'cancelled' WHERE chat_id = ? AND status = 'active'")
            ->execute([$chat_id]);
        $flash     = "Subscription revoked for #{$chat_id}.";
        $flashType = 'warning';

        $notif = "⚠️ Your Premium subscription has been cancelled by the admin.\n\nYou can still use the bot with credits, or contact support.";
        @file_get_contents("https://api.telegram.org/bot{$config['telegram_token']}/sendMessage?" .
            http_build_query(['chat_id' => $chat_id, 'text' => $notif, 'parse_mode' => 'HTML']));
    }
}

// ─── Filter & paginate ───────────────────────────────────────────────────────
$perPage   = 20;
$page      = max(1, (int)($_GET['page'] ?? 1));
$offset    = ($page - 1) * $perPage;
$filter    = $_GET['filter'] ?? 'active';

$where = match($filter) {
    'cancelled' => "s.status = 'cancelled'",
    'expired'   => "s.status = 'active' AND s.expires_at <= NOW()",
    default     => "s.status = 'active' AND s.expires_at > NOW()",
};

$total = $pdo->query("SELECT COUNT(*) FROM subscriptions s WHERE {$where}")->fetchColumn();
$totalPages = (int)ceil($total / $perPage);

$subs = $pdo->query("
    SELECT s.*, u.first_name
    FROM subscriptions s
    LEFT JOIN users u ON u.chat_id = s.chat_id
    WHERE {$where}
    ORDER BY s.expires_at DESC
    LIMIT {$perPage} OFFSET {$offset}
")->fetchAll(PDO::FETCH_ASSOC);

// ─── Summary stats ────────────────────────────────────────────────────────────
$activeCnt    = $pdo->query("SELECT COUNT(*) FROM subscriptions WHERE status='active' AND expires_at > NOW()")->fetchColumn();
$expiringSoon = $pdo->query("SELECT COUNT(*) FROM subscriptions WHERE status='active' AND expires_at > NOW() AND expires_at <= DATE_ADD(NOW(), INTERVAL 7 DAY)")->fetchColumn();
$cancelledCnt = $pdo->query("SELECT COUNT(*) FROM subscriptions WHERE status='cancelled'")->fetchColumn();

$planLabels = ['monthly' => '1 Month', '3month' => '3 Months', '6month' => '6 Months', '12month' => '12 Months'];

require_once __DIR__ . '/_header.php';
?>

<div class="page-header d-flex justify-content-between align-items-center">
    <h4 class="fw-bold mb-0">Subscriptions</h4>
    <button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#grantModal">
        <i class="bi bi-plus-circle me-1"></i>Grant Subscription
    </button>
</div>

<?php if ($flash): ?>
<div class="alert alert-<?= $flashType ?> alert-dismissible fade show py-2">
    <?= htmlspecialchars($flash) ?>
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
<?php endif; ?>

<!-- Stat cards -->
<div class="row g-3 mb-4">
    <div class="col-6 col-md-4">
        <div class="card stat-card">
            <div class="card-body d-flex align-items-center gap-3 py-3">
                <div class="icon-box bg-success bg-opacity-10 text-success">⭐</div>
                <div>
                    <div class="fw-bold fs-5 lh-1"><?= number_format($activeCnt) ?></div>
                    <div class="text-muted" style="font-size:.78rem">Active Subscribers</div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-6 col-md-4">
        <div class="card stat-card">
            <div class="card-body d-flex align-items-center gap-3 py-3">
                <div class="icon-box bg-warning bg-opacity-10 text-warning">⏳</div>
                <div>
                    <div class="fw-bold fs-5 lh-1"><?= number_format($expiringSoon) ?></div>
                    <div class="text-muted" style="font-size:.78rem">Expiring in 7 Days</div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-6 col-md-4">
        <div class="card stat-card">
            <div class="card-body d-flex align-items-center gap-3 py-3">
                <div class="icon-box bg-danger bg-opacity-10 text-danger">❌</div>
                <div>
                    <div class="fw-bold fs-5 lh-1"><?= number_format($cancelledCnt) ?></div>
                    <div class="text-muted" style="font-size:.78rem">Cancelled</div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Filter tabs -->
<div class="card table-card">
    <div class="card-header bg-white border-0 pt-3 pb-0">
        <ul class="nav nav-tabs card-header-tabs">
            <li class="nav-item">
                <a class="nav-link <?= $filter === 'active' ? 'active' : '' ?>" href="?filter=active">
                    Active <span class="badge bg-success-subtle text-success ms-1"><?= $activeCnt ?></span>
                </a>
            </li>
            <li class="nav-item">
                <a class="nav-link <?= $filter === 'expired' ? 'active' : '' ?>" href="?filter=expired">
                    Expired
                </a>
            </li>
            <li class="nav-item">
                <a class="nav-link <?= $filter === 'cancelled' ? 'active' : '' ?>" href="?filter=cancelled">
                    Cancelled <span class="badge bg-danger-subtle text-danger ms-1"><?= $cancelledCnt ?></span>
                </a>
            </li>
        </ul>
    </div>
    <div class="table-responsive">
        <table class="table table-hover mb-0">
            <thead>
                <tr>
                    <th>User</th>
                    <th>Plan</th>
                    <th>Status</th>
                    <th>Expires</th>
                    <th>Days Left</th>
                    <th>Granted By</th>
                    <th>Created</th>
                    <th></th>
                </tr>
            </thead>
            <tbody>
            <?php foreach ($subs as $sub):
                $daysLeft   = max(0, (int)ceil((strtotime($sub['expires_at']) - time()) / 86400));
                $isExpired  = strtotime($sub['expires_at']) <= time();
                $expiryClass = $isExpired ? 'text-danger' : ($daysLeft <= 7 ? 'text-warning' : 'text-success');
            ?>
            <tr>
                <td>
                    <a href="user.php?id=<?= $sub['chat_id'] ?>" class="text-decoration-none fw-semibold text-dark">
                        <?= htmlspecialchars($sub['first_name'] ?? 'Unknown') ?>
                    </a>
                    <div class="text-muted" style="font-size:.7rem"><?= $sub['chat_id'] ?></div>
                </td>
                <td>
                    <span class="badge bg-primary-subtle text-primary">
                        <?= htmlspecialchars($planLabels[$sub['plan_type']] ?? $sub['plan_type']) ?>
                    </span>
                </td>
                <td>
                    <?php if ($sub['status'] === 'cancelled'): ?>
                        <span class="badge bg-danger-subtle text-danger">Cancelled</span>
                    <?php elseif ($isExpired): ?>
                        <span class="badge bg-secondary-subtle text-secondary">Expired</span>
                    <?php else: ?>
                        <span class="badge bg-success-subtle text-success">Active</span>
                    <?php endif; ?>
                </td>
                <td class="<?= $expiryClass ?>" style="font-size:.82rem">
                    <?= date('d M Y', strtotime($sub['expires_at'])) ?>
                </td>
                <td>
                    <?php if ($isExpired || $sub['status'] === 'cancelled'): ?>
                        <span class="text-muted">—</span>
                    <?php else: ?>
                        <span class="fw-semibold <?= $daysLeft <= 7 ? 'text-warning' : '' ?>"><?= $daysLeft ?>d</span>
                    <?php endif; ?>
                </td>
                <td class="text-muted" style="font-size:.78rem"><?= htmlspecialchars($sub['granted_by'] ?? 'admin') ?></td>
                <td class="text-muted" style="font-size:.75rem"><?= date('d M Y', strtotime($sub['created_at'])) ?></td>
                <td>
                    <?php if ($sub['status'] === 'active' && !$isExpired): ?>
                    <div class="d-flex gap-1">
                        <button class="btn btn-sm btn-outline-primary py-0 px-2 grant-btn"
                                data-id="<?= $sub['chat_id'] ?>" title="Extend">
                            <i class="bi bi-plus"></i>
                        </button>
                        <form method="POST" onsubmit="return confirm('Revoke this subscription?')" class="d-inline">
                            <input type="hidden" name="_csrf" value="<?= csrf_token() ?>">
                            <input type="hidden" name="action" value="revoke">
                            <input type="hidden" name="chat_id" value="<?= $sub['chat_id'] ?>">
                            <button class="btn btn-sm btn-outline-danger py-0 px-2" title="Revoke">
                                <i class="bi bi-x"></i>
                            </button>
                        </form>
                    </div>
                    <?php else: ?>
                    <button class="btn btn-sm btn-outline-success py-0 px-2 grant-btn"
                            data-id="<?= $sub['chat_id'] ?>" title="Re-grant">
                        <i class="bi bi-arrow-repeat"></i>
                    </button>
                    <?php endif; ?>
                </td>
            </tr>
            <?php endforeach; ?>
            <?php if (empty($subs)): ?>
            <tr><td colspan="8" class="text-center text-muted py-4">No subscriptions found.</td></tr>
            <?php endif; ?>
            </tbody>
        </table>
    </div>

    <?php if ($totalPages > 1): ?>
    <div class="card-footer bg-white border-0 py-2">
        <nav>
            <ul class="pagination pagination-sm mb-0 justify-content-end flex-wrap gap-1">
            <?php for ($i = 1; $i <= min($totalPages, 30); $i++): ?>
                <li class="page-item <?= $i === $page ? 'active' : '' ?>">
                    <a class="page-link" href="?filter=<?= $filter ?>&page=<?= $i ?>"><?= $i ?></a>
                </li>
            <?php endfor; ?>
            </ul>
        </nav>
    </div>
    <?php endif; ?>
</div>

<!-- Grant Subscription Modal -->
<div class="modal fade" id="grantModal" tabindex="-1">
    <div class="modal-dialog modal-sm">
        <div class="modal-content">
            <div class="modal-header">
                <h6 class="modal-title fw-semibold">Grant Subscription</h6>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <input type="hidden" name="_csrf" value="<?= csrf_token() ?>">
                <input type="hidden" name="action" value="grant">
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label small fw-semibold">Telegram Chat ID</label>
                        <input type="number" id="grantChatId" name="chat_id" class="form-control" placeholder="e.g. 123456789" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label small fw-semibold">Plan</label>
                        <select name="plan_type" class="form-select">
                            <option value="monthly">1 Month (30 days)</option>
                            <option value="3month">3 Months (90 days)</option>
                            <option value="6month">6 Months (180 days)</option>
                            <option value="12month">12 Months (365 days)</option>
                        </select>
                    </div>
                    <div class="alert alert-info py-2" style="font-size:.8rem">
                        <i class="bi bi-info-circle me-1"></i>
                        If the user already has an active subscription, the selected duration will be <b>added</b> to their current expiry date.
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-secondary btn-sm" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary btn-sm">Grant</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
// Quick-grant buttons pre-fill the modal
document.querySelectorAll('.grant-btn').forEach(btn => {
    btn.addEventListener('click', () => {
        document.getElementById('grantChatId').value = btn.dataset.id;
        new bootstrap.Modal(document.getElementById('grantModal')).show();
    });
});
</script>

<?php require_once __DIR__ . '/_footer.php'; ?>
