<?php
// ============================================================
//  Admin — Edit / Add a subscription plan
// ============================================================
//
//  POST processing and all redirects happen BEFORE _guard.php
//  is included, because _guard.php outputs HTML immediately
//  and header() won't work after that.
//
// ============================================================

// Auth + DB first — before any HTML
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/csrf.php';
auth_require_admin();

$plan_id = (int)($_GET['id'] ?? 0);
$action  = $_GET['action'] ?? 'edit';
$is_add  = ($action === 'add');

$plan = null;
if (!$is_add) {
    $plan = db_row('SELECT * FROM subscription_plans WHERE id = :id', ['id' => $plan_id]);
    if (!$plan) { http_response_code(404); echo 'Plan not found.'; exit; }
}

$errors = [];

// ============================================================
//  Handle POST — all redirects here, before any HTML output
// ============================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_verify();

    $name          = trim($_POST['name'] ?? '');
    $slug          = trim($_POST['slug'] ?? '');
    $price_rands   = trim($_POST['price_rands'] ?? '');
    $price_display = trim($_POST['price_display'] ?? '');
    $description   = trim($_POST['description'] ?? '');
    $badge         = trim($_POST['badge'] ?? '');
    $active        = !empty($_POST['active']) ? 1 : 0;
    $sort_order    = (int)($_POST['sort_order'] ?? 0);

    // Benefits — one per line
    $raw_benefits = $_POST['benefits'] ?? '';
    $benefits = array_values(array_filter(
        array_map('trim', explode("\n", $raw_benefits)),
        fn($b) => $b !== ''
    ));

    // Validate
    if (!$name) $errors[] = 'Plan name is required.';
    if (!$slug) $errors[] = 'Slug is required.';
    if (!preg_match('/^[a-z0-9\-]+$/', $slug)) {
        $errors[] = 'Slug may only contain lowercase letters, numbers, and hyphens.';
    }
    if ($price_rands === '' || !is_numeric($price_rands)) {
        $errors[] = 'Price is required (numbers only, e.g. 500).';
    }

    if (empty($errors)) {
        $existing_slug = db_row(
            'SELECT id FROM subscription_plans WHERE slug = :s AND id != :id',
            ['s' => $slug, 'id' => $plan_id ?: 0]
        );
        if ($existing_slug) $errors[] = 'That slug is already used by another plan.';
    }

    if (empty($errors)) {
        $price_cents = (int)round((float)$price_rands * 100);
        if (!$price_display) {
            $price_display = 'R ' . number_format((float)$price_rands, 0, '.', ' ') . ' / month';
        }

        $data = [
            'slug'          => $slug,
            'name'          => $name,
            'price_cents'   => $price_cents,
            'price_display' => $price_display,
            'description'   => $description ?: null,
            'benefits'      => json_encode($benefits, JSON_UNESCAPED_UNICODE),
            'badge'         => $badge ?: null,
            'active'        => $active,
            'sort_order'    => $sort_order,
        ];

        if ($is_add) {
            db_insert('subscription_plans', $data);
            header('Location: plans.php?msg=added');
            exit;
        } else {
            db_update('subscription_plans', $plan_id, $data);
            header('Location: plans.php?msg=saved');
            exit;
        }
    }

    // Validation failed — repopulate form fields for redisplay
    $plan = array_merge($plan ?? [], [
        'name'          => $name,
        'slug'          => $slug,
        'price_rands'   => $price_rands,
        'price_display' => $price_display,
        'description'   => $description,
        'badge'         => $badge,
        'active'        => $active,
        'sort_order'    => $sort_order,
        'benefits_text' => $raw_benefits,
    ]);
}

// ============================================================
//  Prepare display values (GET, or after failed POST)
// ============================================================
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    if ($plan) {
        $decoded = json_decode($plan['benefits'] ?? '[]', true) ?: [];
        $plan['price_rands']   = number_format($plan['price_cents'] / 100, 2, '.', '');
        $plan['benefits_text'] = implode("\n", $decoded);
    } else {
        // Add mode defaults
        $plan = [
            'name' => '', 'slug' => '', 'price_rands' => '',
            'price_display' => '', 'description' => '', 'badge' => '',
            'active' => 1, 'sort_order' => 0, 'benefits_text' => '',
        ];
    }
}

// ============================================================
//  HTML output — only after all redirects are done
// ============================================================
$page_title = $is_add ? 'Add plan' : 'Edit — ' . ($plan['name'] ?? '');
require __DIR__ . '/_guard.php';
?>

<section class="section">
    <div class="container" style="max-width:800px;">

        <p class="muted" style="margin:0;"><a href="plans.php">&larr; All plans</a></p>
        <h1><?= $is_add ? 'Add a plan' : 'Edit — ' . htmlspecialchars($plan['name']) ?></h1>

        <?php if (!empty($errors)): ?>
            <div class="alert alert-error">
                <?= implode('<br>', array_map('htmlspecialchars', $errors)) ?>
            </div>
        <?php endif; ?>

        <form method="post"
              action="plan-edit.php?<?= $is_add ? 'action=add' : 'id=' . $plan_id ?>">
            <?= csrf_field() ?>

            <div class="grid grid-2" style="gap:0 1.5rem;">

                <!-- Left column: basic info -->
                <div class="card">
                    <h2 style="margin-top:0;">Basic info</h2>

                    <label for="name">Plan name *
                        <small>shown on the join page</small>
                    </label>
                    <input type="text" id="name" name="name" required
                           value="<?= htmlspecialchars($plan['name']) ?>"
                           placeholder="e.g. Gold">

                    <label for="slug">Slug *
                        <small>URL-safe identifier — used internally</small>
                    </label>
                    <input type="text" id="slug" name="slug" required
                           value="<?= htmlspecialchars($plan['slug']) ?>"
                           placeholder="e.g. gold"
                           pattern="[a-z0-9\-]+"
                           title="Lowercase letters, numbers and hyphens only">

                    <label for="description">Tagline
                        <small>one sentence under the plan name</small>
                    </label>
                    <input type="text" id="description" name="description"
                           value="<?= htmlspecialchars($plan['description'] ?? '') ?>"
                           placeholder="e.g. Stand out in the directory.">

                    <label for="badge">Badge
                        <small>e.g. "Most popular" — leave blank for none</small>
                    </label>
                    <input type="text" id="badge" name="badge"
                           value="<?= htmlspecialchars($plan['badge'] ?? '') ?>"
                           placeholder="Most popular">

                    <div class="grid grid-2" style="gap:0 1rem;">
                        <div>
                            <label for="sort_order">Sort order
                                <small>lower = first</small>
                            </label>
                            <input type="number" id="sort_order" name="sort_order"
                                   min="0" value="<?= (int)($plan['sort_order'] ?? 0) ?>">
                        </div>
                        <div style="padding-top:2.2rem;">
                            <label style="font-weight:400;cursor:pointer;">
                                <input type="checkbox" name="active" value="1"
                                       <?= !empty($plan['active']) ? 'checked' : '' ?>>
                                Show on join page
                            </label>
                        </div>
                    </div>
                </div>

                <!-- Right column: pricing + benefits -->
                <div class="card">
                    <h2 style="margin-top:0;">Pricing</h2>

                    <label for="price_rands">Monthly price (R) *
                        <small>numbers only, e.g. 500</small>
                    </label>
                    <input type="number" id="price_rands" name="price_rands"
                           required min="0" step="0.01"
                           value="<?= htmlspecialchars($plan['price_rands'] ?? '') ?>"
                           placeholder="500">

                    <label for="price_display">Display price
                        <small>leave blank to auto-generate</small>
                    </label>
                    <input type="text" id="price_display" name="price_display"
                           value="<?= htmlspecialchars($plan['price_display'] ?? '') ?>"
                           placeholder="R 500 / month">

                    <p class="muted mt-2" style="font-size:.82rem;">
                        Changing the price only affects <strong>new</strong> signups.
                        Existing PayFast subscribers continue at their original amount.
                    </p>

                    <hr style="margin:1.25rem 0;border:none;border-top:1px solid var(--line);">

                    <label for="benefits">Benefits — one per line *</label>
                    <textarea id="benefits" name="benefits" rows="8"
                              placeholder="Basic directory listing&#10;Access to newsletter&#10;Member events"><?= htmlspecialchars($plan['benefits_text'] ?? '') ?></textarea>
                    <p class="muted" style="font-size:.8rem;margin-top:.25rem;">
                        Each line = one bullet point on the pricing card.
                    </p>
                </div>
            </div>

            <!-- Live preview -->
            <div class="card mt-3">
                <h3 style="margin-top:0;">Live preview</h3>
                <div style="max-width:300px;border:2px solid var(--line);border-radius:var(--radius);padding:1.5rem;position:relative;">
                    <div id="preview-badge"
                         style="display:none;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;"></div>
                    <div style="font-size:1.2rem;font-weight:800;" id="prev-name">—</div>
                    <div style="font-size:1.5rem;font-weight:900;color:var(--brand-primary);margin:.2rem 0;" id="prev-price">—</div>
                    <div style="font-size:.85rem;color:var(--ink-muted);margin-bottom:.75rem;" id="prev-desc"></div>
                    <ul style="padding-left:1.1rem;margin:.5rem 0;font-size:.85rem;" id="prev-benefits"></ul>
                </div>
            </div>

            <div class="mt-3">
                <button type="submit" class="btn">
                    <?= $is_add ? 'Create plan' : 'Save changes' ?>
                </button>
                <a href="plans.php" class="btn btn-outline">Cancel</a>
            </div>
        </form>
    </div>
</section>

<script>
function updatePreview() {
    document.getElementById('prev-name').textContent = document.getElementById('name').value || '—';
    document.getElementById('prev-desc').textContent = document.getElementById('description').value;

    const priceR  = parseFloat(document.getElementById('price_rands').value);
    const dispEl  = document.getElementById('price_display');
    const display = dispEl.value
        || (isNaN(priceR) ? '—' : 'R ' + priceR.toLocaleString('en-ZA', {minimumFractionDigits:0}) + ' / month');
    document.getElementById('prev-price').textContent = display;

    const badge   = document.getElementById('badge').value;
    const badgeEl = document.getElementById('preview-badge');
    badgeEl.textContent = badge;
    badgeEl.style.display = badge ? '' : 'none';

    const lines = document.getElementById('benefits').value
        .split('\n').map(l => l.trim()).filter(Boolean);
    const ul = document.getElementById('prev-benefits');
    ul.innerHTML = '';
    lines.forEach(l => {
        const li = document.createElement('li');
        li.textContent = l;
        ul.appendChild(li);
    });
}

['name','description','badge','price_rands','price_display','benefits'].forEach(id => {
    const el = document.getElementById(id);
    if (el) el.addEventListener('input', updatePreview);
});

// Auto-slug from name (only when slug hasn't been manually edited)
document.getElementById('name').addEventListener('input', function () {
    const slugEl = document.getElementById('slug');
    if (!slugEl.dataset.edited) {
        slugEl.value = this.value.toLowerCase()
            .replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
    }
});
document.getElementById('slug').addEventListener('input', function () {
    this.dataset.edited = '1';
});

updatePreview();
</script>

<?php require __DIR__ . '/_footer.php'; ?>