<?php

declare(strict_types=1);

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

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

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

$sessionId = $_GET['session_id'] ?? '';
$secretKey = getenv('STRIPE_SECRET_KEY') ?: '';
$downloadSecret = getenv('DOWNLOAD_SECRET') ?: '';

$downloadUrl = null;
$errorMessage = null;

if ($sessionId === '') {
    $errorMessage = 'Missing checkout session reference.';
} elseif ($secretKey === '' || $downloadSecret === '') {
    error_log('[success.php] Missing STRIPE_SECRET_KEY or DOWNLOAD_SECRET in .env');
    $errorMessage = 'We could not finalize your order right now. Please contact us with your payment receipt.';
} else {
    try {
        $stripe = new StripeClient($secretKey);
        $session = $stripe->retrieveCheckoutSession($sessionId);

        if (($session['payment_status'] ?? '') === 'paid') {
            $token = DownloadToken::issue($sessionId, $downloadSecret, 86400);
            $downloadUrl = 'download.php?token=' . urlencode($token);
        } else {
            $errorMessage = 'Payment has not been confirmed yet. If you were just charged, please refresh this page in a few seconds.';
        }
    } catch (\Throwable $e) {
        error_log('[success.php] ' . $e->getMessage());
        $errorMessage = 'We could not verify your payment right now. Please contact us with your payment receipt.';
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>SysVote — Order Confirmation</title>
<script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-slate-50 min-h-screen flex items-center justify-center px-4">
  <div class="max-w-lg w-full bg-white border border-gray-200 rounded-xl shadow-sm p-8 text-center">
    <?php if ($downloadUrl !== null): ?>
      <div class="w-14 h-14 mx-auto rounded-full bg-green-50 flex items-center justify-center text-green-600 text-2xl mb-4">&#10003;</div>
      <h1 class="text-2xl font-bold text-slate-800 mb-2">Payment confirmed</h1>
      <p class="text-slate-600 mb-6">Thank you for your purchase. Your download is ready below. This link stays valid for 24 hours.</p>
      <a href="<?= htmlspecialchars($downloadUrl, ENT_QUOTES) ?>" class="inline-block bg-blue-600 hover:bg-blue-700 text-white font-semibold px-6 py-3 rounded-lg transition">Download SysVote</a>
    <?php else: ?>
      <div class="w-14 h-14 mx-auto rounded-full bg-red-50 flex items-center justify-center text-red-600 text-2xl mb-4">!</div>
      <h1 class="text-2xl font-bold text-slate-800 mb-2">We couldn't confirm your payment</h1>
      <p class="text-slate-600 mb-6"><?= htmlspecialchars($errorMessage ?? 'Unknown error.', ENT_QUOTES) ?></p>
      <a href="index.php#tarifs" class="inline-block border border-slate-300 hover:border-slate-400 font-semibold px-6 py-3 rounded-lg transition">Back to pricing</a>
    <?php endif; ?>
  </div>
</body>
</html>
