<?php
$pageTitle = 'Subscription Plans';
$breadcrumb = [['label' => 'Admin', 'url' => null], ['label' => 'Subscription Plans', 'url' => null]];
ob_start();
?>
<div class="page-header">
    <div>
        <h1 class="page-title">Subscription Plans</h1>
        <p class="page-subtitle">Manage the plans organizations can subscribe to</p>
    </div>
    <button type="button" class="btn btn-primary" onclick="openPlanModal()">+ New Plan</button>
</div>

<div class="card">
    <div class="table-responsive">
        <table class="table">
            <thead>
                <tr><th>Name</th><th>Price</th><th>Billing</th><th>Currency Pricing</th><th>Organizations</th><th>Status</th><th></th></tr>
            </thead>
            <tbody>
                <?php if (empty($plans)): ?>
                <tr><td colspan="7" class="text-center" style="padding:32px;color:var(--text-muted);">No plans yet.</td></tr>
                <?php else: ?>
                    <?php foreach ($plans as $plan): ?>
                    <?php $planPrices = $pricesByPlan[(int)$plan['id']] ?? []; ?>
                    <tr>
                        <td><?= htmlspecialchars($plan['name']) ?></td>
                        <td><?= formatCurrency((float)$plan['price']) ?></td>
                        <td><?= htmlspecialchars(ucfirst($plan['billing_type'])) ?></td>
                        <td>
                            <?php if (empty($planPrices)): ?>
                                <span style="color:var(--text-muted);font-size:0.8rem;">Default only</span>
                            <?php else: ?>
                                <?php foreach ($planPrices as $pp): ?>
                                    <span class="badge badge-secondary" style="margin:2px;"><?= htmlspecialchars($pp['currency_code']) ?> <?= formatCurrency((float)$pp['amount'], $pp['currency_code']) ?></span>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </td>
                        <td><?= (int)$plan['org_count'] ?></td>
                        <td><span class="badge badge-<?= $plan['is_active'] ? 'active' : 'secondary' ?>"><?= $plan['is_active'] ? 'Active' : 'Inactive' ?></span></td>
                        <td style="white-space:nowrap;">
                            <button type="button" class="btn btn-sm btn-secondary"
                                onclick='openPlanModal(<?= json_encode($plan) ?>)'>Edit</button>
                            <button type="button" class="btn btn-sm btn-secondary"
                                onclick='openPricingModal(<?= (int)$plan['id'] ?>, <?= htmlspecialchars(json_encode($plan['name']), ENT_QUOTES) ?>, <?= json_encode($planPrices) ?>)'>Pricing</button>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<div class="modal-overlay hidden" id="planModal">
    <div class="modal modal-sm">
        <div class="modal-header">
            <h4 class="modal-title" id="planModalTitle">New Plan</h4>
            <button class="modal-close" onclick="document.getElementById('planModal').classList.add('hidden')">&times;</button>
        </div>
        <form method="POST" action="<?= APP_URL ?>/admin/plans">
            <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($_SESSION[CSRF_TOKEN_NAME] ?? '') ?>">
            <input type="hidden" name="id" id="plan_id" value="0">
            <div class="modal-body">
                <div class="form-group">
                    <label class="form-label required">Name</label>
                    <input type="text" name="name" id="plan_name" class="form-control" required>
                </div>
                <div class="form-group">
                    <label class="form-label">Description</label>
                    <textarea name="description" id="plan_description" class="form-control" rows="2"></textarea>
                </div>
                <div class="form-group">
                    <label class="form-label">Price</label>
                    <input type="number" step="0.01" name="price" id="plan_price" class="form-control">
                </div>
                <div class="form-group">
                    <label class="form-label">Billing Type</label>
                    <select name="billing_type" id="plan_billing_type" class="form-control form-select">
                        <option value="monthly">Monthly</option>
                        <option value="annual">Annual</option>
                    </select>
                </div>
                <div class="form-group">
                    <label class="form-label">Features (one per line)</label>
                    <textarea name="features" id="plan_features" class="form-control" rows="3"></textarea>
                </div>
                <div class="form-group">
                    <label style="display:flex;align-items:center;gap:8px;">
                        <input type="checkbox" name="is_active" id="plan_is_active" value="1" checked>
                        Active
                    </label>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" onclick="document.getElementById('planModal').classList.add('hidden')">Cancel</button>
                <button type="submit" class="btn btn-primary">Save Plan</button>
            </div>
        </form>
    </div>
</div>

<div class="modal-overlay hidden" id="pricingModal">
    <div class="modal modal-sm">
        <div class="modal-header">
            <h4 class="modal-title" id="pricingModalTitle">Currency Pricing</h4>
            <button class="modal-close" onclick="document.getElementById('pricingModal').classList.add('hidden')">&times;</button>
        </div>
        <form method="POST" id="pricingForm">
            <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($_SESSION[CSRF_TOKEN_NAME] ?? '') ?>">
            <div class="modal-body">
                <p class="field-hint" style="margin-bottom:12px;">Set the amount charged in each currency. A visitor is billed in the currency their location resolves to; if none is listed here, the platform's default currency price is used instead — see Admin &gt; System Settings.</p>
                <table class="table" id="pricingRows">
                    <thead><tr><th>Currency</th><th>Amount</th><th></th></tr></thead>
                    <tbody id="pricingRowsBody"></tbody>
                </table>
                <button type="button" class="btn btn-sm btn-secondary" onclick="addPricingRow('', '')">+ Add Currency</button>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" onclick="document.getElementById('pricingModal').classList.add('hidden')">Cancel</button>
                <button type="submit" class="btn btn-primary">Save Pricing</button>
            </div>
        </form>
    </div>
</div>

<script>
function openPlanModal(plan) {
    document.getElementById('planModalTitle').textContent = plan ? 'Edit Plan' : 'New Plan';
    document.getElementById('plan_id').value = plan ? plan.id : 0;
    document.getElementById('plan_name').value = plan ? plan.name : '';
    document.getElementById('plan_description').value = plan ? plan.description : '';
    document.getElementById('plan_price').value = plan ? plan.price : '';
    document.getElementById('plan_billing_type').value = plan ? plan.billing_type : 'monthly';
    document.getElementById('plan_is_active').checked = plan ? !!parseInt(plan.is_active) : true;
    let features = [];
    try { features = plan && plan.features ? JSON.parse(plan.features) : []; } catch (e) {}
    document.getElementById('plan_features').value = features.join('\n');
    document.getElementById('planModal').classList.remove('hidden');
}

const KNOWN_CURRENCIES = <?= json_encode($currencies ?? []) ?>;

function addPricingRow(code, amount) {
    const tbody = document.getElementById('pricingRowsBody');
    const tr = document.createElement('tr');

    const currencyOptions = Object.keys(KNOWN_CURRENCIES).map(c =>
        `<option value="${c}" ${c === code ? 'selected' : ''}>${c} (${KNOWN_CURRENCIES[c]})</option>`
    ).join('');

    tr.innerHTML = `
        <td>
            <input type="text" name="currency[]" class="form-control" list="pricingCurrencyList" value="${code}" placeholder="e.g. GHS" maxlength="3" style="text-transform:uppercase;width:100px;">
        </td>
        <td><input type="number" step="0.01" min="0" name="amount[]" class="form-control" value="${amount}" style="width:130px;"></td>
        <td><button type="button" class="btn btn-sm btn-secondary" onclick="this.closest('tr').remove()">Remove</button></td>
    `;
    tbody.appendChild(tr);
}

function openPricingModal(planId, planName, prices) {
    document.getElementById('pricingModalTitle').textContent = 'Currency Pricing — ' + planName;
    document.getElementById('pricingForm').action = '<?= APP_URL ?>/admin/plans/' + planId + '/prices';
    document.getElementById('pricingRowsBody').innerHTML = '';
    (prices || []).forEach(p => addPricingRow(p.currency_code, p.amount));
    if (!prices || prices.length === 0) addPricingRow('', '');
    document.getElementById('pricingModal').classList.remove('hidden');
}
</script>
<datalist id="pricingCurrencyList">
    <?php foreach (($currencies ?? []) as $code => $symbol): ?>
        <option value="<?= htmlspecialchars($code) ?>"><?= htmlspecialchars($symbol . ' ' . $code) ?></option>
    <?php endforeach; ?>
</datalist>
<?php
$content = ob_get_clean();
require ROOT_PATH . '/modules/shared/views/layouts/main.php';
?>
