<?php

declare(strict_types=1);

require __DIR__ . '/../vendor/autoload.php';

use Sethrey\SysvoteWebsite\EnvLoader;
use Sethrey\SysvoteWebsite\StripeClient;

if (class_exists(EnvLoader::class)) {
    EnvLoader::load(__DIR__ . '/../.env');
}

// --- Product catalog ---------------------------------------------------
// Maps a public "plan" key (sent from the pricing form) to a Stripe Price ID
// created in the Stripe Dashboard (Product catalog). The amount/currency
// live in Stripe, never hardcoded here, so pricing can change without a
// code deploy.
$catalog = [
    'starter-license' => getenv('STRIPE_PRICE_STARTER_LICENSE') ?: '',
];

$plan = $_POST['plan'] ?? '';

function fail(int $status, string $message): void
{
    http_response_code($status);
    header('Content-Type: text/html; charset=utf-8');
    echo '<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8">'
        . '<title>Checkout unavailable</title></head><body style="font-family:sans-serif;max-width:520px;margin:80px auto;text-align:center;">'
        . '<p>' . htmlspecialchars($message, ENT_QUOTES) . '</p>'
        . '<p><a href="index.php#tarifs">&larr; Back to pricing</a></p>'
        . '</body></html>';
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    fail(405, 'This endpoint only accepts form submissions.');
}

if (!isset($catalog[$plan]) || $catalog[$plan] === '') {
    fail(400, 'This plan is not available for online purchase right now. Please use the contact form below instead.');
}

$secretKey = getenv('STRIPE_SECRET_KEY') ?: '';
$appUrl = rtrim(getenv('APP_URL') ?: '', '/');

if ($secretKey === '' || $appUrl === '') {
    error_log('[create-checkout-session] Missing STRIPE_SECRET_KEY or APP_URL in .env');
    fail(500, 'Online payment is not configured yet. Please use the contact form below.');
}

$stripe = new StripeClient($secretKey);

try {
    $session = $stripe->createCheckoutSession([
        'mode' => 'payment',
        'line_items' => [
            [
                'price' => $catalog[$plan],
                'quantity' => 1,
            ],
        ],
        'success_url' => $appUrl . '/success.php?session_id={CHECKOUT_SESSION_ID}',
        'cancel_url' => $appUrl . '/index.php#tarifs',
        'automatic_tax' => ['enabled' => false],
        'metadata' => [
            'plan' => $plan,
        ],
    ]);

    if (empty($session['url'])) {
        throw new \RuntimeException('Stripe did not return a Checkout URL.');
    }

    header('Location: ' . $session['url'], true, 303);
    exit;
} catch (\Throwable $e) {
    error_log('[create-checkout-session] ' . $e->getMessage());
    fail(502, 'We could not start the checkout process. Please try again in a moment, or use the contact form below.');
}
