<?php
// ─── SunScope Extra — Verify Checkout Session ────────────────────────────────
// JSON endpoint hit right after a Stripe Payment Link redirect
// (?session_id={CHECKOUT_SESSION_ID}). Confirms server-side that the
// session was actually paid before the app unlocks Pro - a bare ?pro=1
// URL param can no longer grant access on its own.
//
// Returns {"paid": bool, "mode": "subscription"|"payment"|null, "customer": string|null}

require __DIR__ . '/secrets.local.php';

header('Content-Type: application/json');

$sessionId = trim($_GET['session_id'] ?? $_POST['session_id'] ?? '');

if ($sessionId === '' || !preg_match('/^cs_[A-Za-z0-9_]+$/', $sessionId)) {
    echo json_encode(['paid' => false, 'mode' => null, 'customer' => null]);
    exit;
}

$ch = curl_init('https://api.stripe.com/v1/checkout/sessions/' . urlencode($sessionId));
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_USERPWD        => STRIPE_SECRET_KEY . ':',
]);
$session = json_decode(curl_exec($ch), true);
curl_close($ch);

$paid = ($session['payment_status'] ?? '') === 'paid';

echo json_encode([
    'paid'     => $paid,
    'mode'     => $paid ? ($session['mode'] ?? null) : null,
    'customer' => $paid ? ($session['customer'] ?? null) : null,
]);
