<?php
// ============================================================
//  Admin — Subscription Plans
// ============================================================
//
//  Lists all plans stored in the subscription_plans table.
//  Changes made here reflect immediately on become-member.php.
//
// ============================================================

$page_title = 'Subscription Plans';
require __DIR__ . '/_guard.php';

// Handle quick-toggles (enable/disable, sort order)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_verify();
    $do = $_POST['do'] ?? '';

    if ($do === 'toggle') {
        $id  = (int)$_POST['plan_id'];
        $cur = (int)db_value('SELECT active FROM subscription_plans WHERE id = :id', ['id' => $id]);
        db_exec('UPDATE subscription_plans SET active = :a WHERE id = :id',
                ['a' => $cur ? 0 : 1, 'id' => $id]);
        header('Location: plans.php'); exit;
    }

    if ($do === 'delete') {
        $id = (int)$_POST['plan_id'];
        db_exec('DELETE FROM subscription_plans WHERE id = :id', ['id' => $id]);
        header('Location: plans.php?msg=deleted'); exit;
    }
}

$plans = db_all('SELECT * FROM subscription_plans ORDER BY sort_order, id');
?>

<?php
$settings_section = 'plans';
require __DIR__ . '/_settings_open.php';
?>

        <div class="settings-page-head" style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:1rem;">
            <div>
                <h1>Subscription Plans</h1>
                <p class="crumb">
                    These are the plans shown on your
                    <a href="../become-member.php" target="_blank">join page</a>.
                    Changes take effect immediately.
                </p>
            </div>
            <a href="plan-edit.php?action=add" class="btn">+ Add plan</a>
        </div>

        <?php if (isset($_GET['msg'])): ?>
            <div class="alert alert-success" data-autohide>
                <?php
                $msgs = [
                    'saved'   => 'Plan saved. The join page has been updated.',
                    'deleted' => 'Plan deleted.',
                    'added'   => 'Plan created and published to the join page.',
                ];
                echo htmlspecialchars($msgs[$_GET['msg']] ?? $_GET['msg']);
                ?>
            </div>
        <?php endif; ?>

        <?php if (empty($plans)): ?>
            <div class="alert alert-info">
                No plans yet.
                <a href="plan-edit.php?action=add">Add your first plan &rarr;</a>
            </div>
        <?php else: ?>
            <div class="grid grid-3" style="align-items:start;">
                <?php foreach ($plans as $p):
                    $benefits = json_decode($p['benefits'] ?? '[]', true) ?: [];
                ?>
                    <div class="card" style="position:relative;<?= !$p['active'] ? 'opacity:.6;' : '' ?>">

                        <?php if ($p['badge']): ?>
                            <div style="position:absolute;top:-1px;right:1.25rem;
                                        background:var(--brand-primary);color:white;
                                        font-size:.7rem;font-weight:700;
                                        padding:.2em .75em;border-radius:0 0 6px 6px;
                                        text-transform:uppercase;letter-spacing:.05em;">
                                <?= htmlspecialchars($p['badge']) ?>
                            </div>
                        <?php endif; ?>

                        <div style="display:flex;justify-content:space-between;align-items:flex-start;">
                            <div>
                                <h2 style="margin:0;"><?= htmlspecialchars($p['name']) ?></h2>
                                <p style="font-size:1.4rem;font-weight:800;color:var(--brand-primary);margin:.2rem 0;">
                                    <?= htmlspecialchars($p['price_display']) ?>
                                </p>
                            </div>
                            <span class="tag <?= $p['active'] ? 'tag-ok' : 'tag-err' ?>">
                                <?= $p['active'] ? 'Active' : 'Hidden' ?>
                            </span>
                        </div>

                        <?php if ($p['description']): ?>
                            <p class="muted" style="margin:.25rem 0 .75rem;font-size:.9rem;">
                                <?= htmlspecialchars($p['description']) ?>
                            </p>
                        <?php endif; ?>

                        <ul style="padding-left:1.1rem;margin:.5rem 0;font-size:.85rem;">
                            <?php foreach ($benefits as $b): ?>
                                <li><?= htmlspecialchars($b) ?></li>
                            <?php endforeach; ?>
                        </ul>

                        <div style="display:flex;gap:.5rem;margin-top:1rem;flex-wrap:wrap;">
                            <a href="plan-edit.php?id=<?= $p['id'] ?>" class="btn btn-outline"
                               style="padding:.3rem .75rem;font-size:.85rem;">Edit</a>

                            <form method="post" style="display:inline;">
                                <?= csrf_field() ?>
                                <input type="hidden" name="do" value="toggle">
                                <input type="hidden" name="plan_id" value="<?= $p['id'] ?>">
                                <button class="btn btn-outline"
                                        style="padding:.3rem .75rem;font-size:.85rem;">
                                    <?= $p['active'] ? 'Hide' : 'Show' ?>
                                </button>
                            </form>

                            <form method="post" style="display:inline;"
                                  onsubmit="return confirm('Delete this plan? This cannot be undone.');">
                                <?= csrf_field() ?>
                                <input type="hidden" name="do" value="delete">
                                <input type="hidden" name="plan_id" value="<?= $p['id'] ?>">
                                <button class="btn"
                                        style="padding:.3rem .75rem;font-size:.85rem;
                                               background:#fde0e0;border-color:#9b1c1c;color:#9b1c1c;">
                                    Delete
                                </button>
                            </form>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>

        <div class="card mt-3" style="font-size:.9rem;">
            <strong>How this works:</strong>
            The plans above are what members see on the
            <a href="../become-member.php" target="_blank">Join page</a>.
            When a member signs up and pays, the price comes from this table — not from config.php.
            Editing a plan price here will affect new signups immediately but won't change existing
            active subscriptions (PayFast bills at the original token amount).
        </div>

<?php require __DIR__ . '/_settings_close.php'; ?>

<?php require __DIR__ . '/_footer.php'; ?>