<?php
// ─── SunScope Extra — Restore Access ─────────────────────────────────────────
// JSON endpoint for the in-app "Already subscribed? Restore access" modal.
// The modal POSTs an email here and reads back {"active": bool, "error": str}.
// Paste your Stripe SECRET key below (never the publishable key).
// Swap sk_test_... for sk_live_... when you go live.

define('STRIPE_SECRET_KEY', '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');
define('SUNSCOPE_URL', 'https://sunscope.net');

// Direct visits no longer get a page — the restore flow is an in-app modal
// that POSTs here and reads back JSON. Send stray GETs home.
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: ' . SUNSCOPE_URL);
    exit;
}

$error    = '';
$isActive = false;

$email = trim(strtolower($_POST['email'] ?? ''));

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $error = 'Please enter a valid email address.';
} else {
    // Search Stripe for a customer with this email
    $ch = curl_init('https://api.stripe.com/v1/customers?email=' . urlencode($email) . '&limit=5');
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_USERPWD        => STRIPE_SECRET_KEY . ':',
    ]);
    $response = json_decode(curl_exec($ch), true);
    curl_close($ch);

    if (!empty($response['data'])) {
        foreach ($response['data'] as $customer) {
            // Check subscriptions for this customer
            $ch2 = curl_init('https://api.stripe.com/v1/subscriptions?customer=' . $customer['id'] . '&status=active&limit=5');
            curl_setopt_array($ch2, [
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_USERPWD        => STRIPE_SECRET_KEY . ':',
            ]);
            $subs = json_decode(curl_exec($ch2), true);
            curl_close($ch2);

            if (!empty($subs['data'])) {
                $isActive = true;
                break;
            }
        }
    }

    if (!$isActive) {
        $error = 'No active SunScope Extra subscription found for that email.';
    }
}

header('Content-Type: application/json');
echo json_encode(['active' => $isActive, 'error' => $error]);
