<?php
// ============================================================
//  Checkout: monthly recurring membership subscription
// ============================================================
//
//  Two flows live here:
//    1. Gateway picker (default GET)  — show available payment
//       options (PayFast / Netcash) when both are configured
//    2. Gateway redirect (?go=payfast|netcash) — build the
//       gateway-specific form and auto-submit
//
//  Invoices are created by the respective notify/ITN handler
//  AFTER the gateway confirms a successful payment. This page
//  does NOT touch the database.
//
// ============================================================

require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/payfast.php';
require_once __DIR__ . '/../includes/netcash.php';

auth_require_login();
$member = auth_user();

// Look up plan price
$plan = db_row(
    'SELECT * FROM subscription_plans WHERE slug = :s AND active = 1',
    ['s' => strtolower($member['tier'])]
);
$price_cents = $plan
    ? (int)$plan['price_cents']
    : ([
          'Bronze'   =>  50000, 'Silver'  => 120000,
          'Gold'     => 250000, 'Platinum' => 500000, 'Diamond' => 1000000,
      ][$member['tier']] ?? 50000);

$is_new      = !empty($_GET['new']);
$is_reactiv  = !empty($_GET['reactivate']);
$amount_str  = pf_cents_to_amount($price_cents);
$go          = $_GET['go'] ?? '';   // empty = picker, payfast/netcash = redirect

// Which gateways are configured?
$pf_available = defined('PF_MERCHANT_ID') && PF_MERCHANT_ID !== '';
$nc_available = nc_is_configured();

if (!$pf_available && !$nc_available) {
    http_response_code(503);
    echo 'No payment gateway is configured. Please contact support.';
    exit;
}

// If only one gateway is available, auto-redirect to it
if ($go === '' && $pf_available && !$nc_available) $go = 'payfast';
if ($go === '' && $nc_available && !$pf_available) $go = 'netcash';

// ── Gateway-specific build ──────────────────────────────────
$pf_fields = $pf_action = $nc_fields = $nc_action = null;

if ($go === 'payfast') {
    $m_payment_id = 'MBR-' . $member['id'] . '-' . time();
    $pf_fields = pf_build_payment_fields([
        'm_payment_id'     => $m_payment_id,
        'amount'           => $amount_str,
        'item_name'        => 'Buy Local Lowveld — ' . $member['tier'] . ' membership',
        'item_description' => 'Monthly membership, auto-renews. Cancel any time.',
        'name_first'       => $member['first_name'],
        'name_last'        => $member['last_name'],
        'email_address'    => $member['email'],
        'subscription_type' => '1',
        'billing_date'     => date('Y-m-d'),
        'recurring_amount' => $amount_str,
        'frequency'        => '3',
        'cycles'           => '0',
        'custom_str2'      => 'member:' . $member['id'],
        'custom_str3'      => 'type:membership',
        'custom_str4'      => 'tier:' . $member['tier'],
    ]);
    $pf_action = pf_process_url();
}

if ($go === 'netcash') {
    $reference = nc_generate_reference((int)$member['id']);
    $nc_fields = nc_build_payment_fields([
        'reference'    => $reference,
        'description'  => 'Buy Local Lowveld — ' . $member['tier'] . ' membership ('
                          . $member['first_name'] . ' ' . $member['last_name'] . ')',
        'amount_cents' => $price_cents,
        'email'        => $member['email'],
        'mobile'       => $member['phone'] ?? null,
        // Round-trip data on the Notify post — used to find the member + tier
        'extra1'       => 'member:' . $member['id'],
        'extra2'       => 'tier:'   . $member['tier'],
        'extra3'       => 'type:membership',
        // Request a CC token on first successful charge — enables future
        // headless recurring charges (Phase 2 will add the cron for that)
        'request_token' => true,
    ]);
    $nc_action = nc_paynow_url();
}
?><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Complete your membership — Buy Local Lowveld</title>
    <link rel="stylesheet" href="../assets/css/style.css">
    <style>
    .gw-picker{display:grid;grid-template-columns:1fr 1fr;gap:1rem;margin-top:1.25rem;}
    @media(max-width:520px){.gw-picker{grid-template-columns:1fr;}}
    .gw-card{display:block;text-decoration:none;background:#fff;border:2px solid var(--line);
             border-radius:10px;padding:1.5rem 1.25rem;text-align:left;transition:.15s;color:var(--ink);}
    .gw-card:hover{border-color:var(--brand-primary);transform:translateY(-2px);
                   box-shadow:0 6px 18px rgba(0,0,0,.06);}
    .gw-card h3{margin:0 0 .25rem;font-size:1rem;}
    .gw-card .gw-sub{font-size:.78rem;color:var(--ink-muted);margin:0 0 .65rem;}
    .gw-card .gw-pill{display:inline-block;font-size:.7rem;background:#dbeafe;color:#1e40af;
                      padding:.1em .55em;border-radius:999px;font-weight:600;margin-top:.4rem;}
    .gw-pill.alt{background:#dcfce7;color:#166534;}
    </style>
</head>
<body>
<section class="section">
    <div class="container" style="max-width:560px;text-align:center;">

        <?php if ($is_new): ?>
            <h1>One last step</h1>
            <p class="muted">Your account is created. Complete payment to go live in the directory.</p>
        <?php elseif ($is_reactiv): ?>
            <h1>Welcome back</h1>
            <p class="muted">Set up a fresh subscription to reactivate your membership.</p>
        <?php elseif ($go === ''): ?>
            <h1>Choose how to pay</h1>
            <p class="muted">Pick the payment provider you'd like to use. You can change later.</p>
        <?php else: ?>
            <h1>Redirecting&hellip;</h1>
            <p class="muted">Please wait. If nothing happens, click the button below.</p>
        <?php endif; ?>

        <div class="card mt-3" style="text-align:left;">
            <p style="margin:0;"><strong>Package:</strong> <?= htmlspecialchars($member['tier']) ?></p>
            <p style="margin:.3rem 0;"><strong>Amount:</strong> R<?= $amount_str ?>/month</p>
            <p style="margin:.3rem 0 0;font-size:.85rem;" class="muted">
                Billed monthly. Cancel any time from your dashboard.
            </p>
        </div>

        <?php if ($go === ''): ?>
            <!-- Gateway picker — both available -->
            <div class="gw-picker">
                <?php if ($pf_available): ?>
                    <a href="?go=payfast<?= $is_new?'&new=1':'' ?><?= $is_reactiv?'&reactivate=1':'' ?>"
                       class="gw-card">
                        <h3>PayFast</h3>
                        <p class="gw-sub">Card, Instant EFT, SnapScan, MoMo</p>
                        <span class="gw-pill">Auto-recurring</span>
                    </a>
                <?php endif; ?>
                <?php if ($nc_available): ?>
                    <a href="?go=netcash<?= $is_new?'&new=1':'' ?><?= $is_reactiv?'&reactivate=1':'' ?>"
                       class="gw-card">
                        <h3>Netcash</h3>
                        <p class="gw-sub">Card, EFT, Retail, Mobicred, Payflex</p>
                        <span class="gw-pill alt">Card token saved</span>
                    </a>
                <?php endif; ?>
            </div>

        <?php elseif ($go === 'payfast' && $pf_fields): ?>
            <form id="gw-form" method="post" action="<?= htmlspecialchars($pf_action) ?>" class="mt-3">
                <?php foreach ($pf_fields as $k => $v): ?>
                    <input type="hidden" name="<?= htmlspecialchars($k) ?>"
                           value="<?= htmlspecialchars((string)$v) ?>">
                <?php endforeach; ?>
                <button type="submit" class="btn" style="width:100%;">
                    Pay R<?= $amount_str ?>/month with PayFast →
                </button>
            </form>
            <p class="mt-3" style="font-size:.85rem;">
                <a href="?<?= $is_new?'new=1':'' ?>">← Use a different payment provider</a>
            </p>

        <?php elseif ($go === 'netcash' && $nc_fields): ?>
            <form id="gw-form" method="post" action="<?= htmlspecialchars($nc_action) ?>"
                  target="_top" class="mt-3">
                <?php foreach ($nc_fields as $k => $v): ?>
                    <input type="hidden" name="<?= htmlspecialchars($k) ?>"
                           value="<?= htmlspecialchars((string)$v) ?>">
                <?php endforeach; ?>
                <button type="submit" class="btn" style="width:100%;">
                    Pay R<?= $amount_str ?> with Netcash →
                </button>
            </form>
            <p class="mt-3" style="font-size:.85rem;">
                <a href="?<?= $is_new?'new=1':'' ?>">← Use a different payment provider</a>
            </p>

        <?php endif; ?>

        <?php if ($is_new): ?>
            <p class="muted mt-3" style="font-size:.85rem;">
                Your sign-in details have been emailed to
                <strong><?= htmlspecialchars($member['email']) ?></strong>.
            </p>
        <?php endif; ?>

        <p class="mt-3" style="font-size:.85rem;">
            <a href="../become-member.php">Wrong package? Go back</a>
        </p>
    </div>
</section>

<?php if ($go !== ''): ?>
<script>
    // Auto-submit the gateway form after a brief pause
    setTimeout(function () {
        document.getElementById('gw-form').submit();
    }, <?= $is_new ? 1500 : 600 ?>);
</script>
<?php endif; ?>
</body>
</html>