<?php

declare(strict_types=1); // Enforce strict typing

// Error reporting for development - REMOVE OR CHANGE IN PRODUCTION
error_reporting(E_ALL);
ini_set('display_errors', '1');

// Assuming this is needed for other application logic
require_once "../models/Operations.php";

// Include the Stripe PHP library
require_once '../vendor/autoload.php';

use Dotenv\Dotenv;
use Stripe\Stripe;
use Stripe\Checkout\Session;
use Stripe\Exception\ApiErrorException;

// --- Environment Variable Loading ---
try {
    // Determine the base directory for Dotenv correctly
    $baseDir = dirname(__DIR__);
    $dotenv = Dotenv::createImmutable($baseDir);
    $dotenv->safeLoad(); // Use safeLoad to avoid throwing if .env is missing (though it should be present)
} catch (\Exception $e) {
    // Log the error and show a generic message instead of crashing with internal path info
    error_log("Failed to load environment variables: " . $e->getMessage());
    die("Configuration error. Please contact support.");
}


// --- Configuration and API Key Setup ---
$stripeSecretKey = $_ENV['STRIPE_SECRET_KEY'] ?? null;

if (!$stripeSecretKey) {
    error_log("Stripe secret key is not set in environment variables.");
    die("Payment configuration error. Please contact support.");
}

Stripe::setApiKey($stripeSecretKey);

// --- Input Validation and Sanitization ---
// Retrieve the session ID from the query string and sanitize it
$sessionId = $_GET['session_id'] ?? null;

if (empty($sessionId) || !is_string($sessionId)) {
    // Log an attempt with an invalid or missing session ID
    error_log("Invalid or missing session_id received: " . ($sessionId ?? 'NULL'));
    // Redirect or show a generic error page instead of a failure message
    // header("Location: /stripe/error.php?session_id={$sessionId}");
    renderErrorPage('Invalid Request', 'The payment session is invalid or has expired.');
    exit();
}

// --- Stripe Session Retrieval and Error Handling ---
try {
    // Retrieve the checkout session
    $session = Session::retrieve($sessionId);

    // var_dump($session);
    // exit();

    // Example: Get the customer, subscription, and metadata
    $sessionId = $session->id;
    $sessionMode = $session->mode;
    $customerEmail = $session->customer_details->email ?? 'N/A';
    $paymentStatus = $session->payment_status;
    $amountTotal = $session->amount_total ? ($session->amount_total / 100) : 0;
    $currency = strtoupper($session->currency ?? 'USD');

    $clientAlert = "";
    $message = "";

    // --- 1. Check for Successful One-Time Payment (mode: payment) ---
    if ($sessionMode === 'payment' && $paymentStatus === 'paid') {
        // 🎉 Success: One-time payment received.
        $clientAlert = "<h1>Payment Successful!</h1>";
        $clientAlert .= "<p>Your payment has been processed successfully.</p>";
    }
    // --- 2. Check for Successful Subscription Activation (mode: subscription) ---
    elseif ($sessionMode === 'subscription' && ($paymentStatus === 'paid' || $paymentStatus === 'no_payment_required')) {

        // 🎉 Success: Subscription activated.
        if ($paymentStatus === 'no_payment_required') {
            $clientAlert = "<h1>Subscription Activated!</h1>";
            $clientAlert .= "<p>Your free trial has started. No payment was required today.</p>";
        } else {
            $clientAlert = "<h1>Subscription Activated!</h1>";
            $clientAlert .= "<p>Your payment for the first period was successful.</p>";
        }
    }
    // --- 3. Check for Successful Card Setup (mode: setup) ---
    elseif ($sessionMode === 'setup' && $paymentStatus === 'no_payment_required') {

        // 💳 Success: Payment method saved for future billing.
        $clientAlert = "<h1>Payment Method Saved!</h1>";
        $clientAlert .= "<p>Your card has been securely saved for future payments.</p>";
    }
    // --- 4. Handle General Failures (Any mode resulting in unpaid status) ---
    elseif ($paymentStatus === 'unpaid') {

        // ⚠️ Failure: Payment required but failed.
        $clientAlert = "<h1>Payment Incomplete!</h1>";
        $clientAlert .= "<p>It looks like the payment was not completed. Please check your card details and try again.</p>";
        // (e.g., log failure, prompt user to retry checkout)
    }

    // --- 5. Handle Other/Unexpected Statuses ---
    else {
        // ❓ Unknown: Catch any combination not explicitly handled.
        $clientAlert = "<h1>Order Status: " . htmlspecialchars(ucfirst($paymentStatus)) . "</h1>";
        $clientAlert .= "<p>We are still processing your order. Please check back later or contact support.</p>";
    }

    // Render response
    renderSuccessPage($paymentStatus, $customerEmail, $amountTotal, $currency, $sessionId, $clientAlert);
} catch (ApiErrorException $e) {
    // Handle Stripe API errors (e.g., session ID not found, invalid API key, network error)
    http_response_code(500);
    renderErrorPage('Payment Verification Failed', 'Unable to verify your session ' . htmlspecialchars($sessionId) . ' Please contact support.');
    error_log("Stripe API Error retrieving session $sessionId: " . $e->getMessage());
} catch (\Exception $e) {
    // Catch any other unexpected errors
    http_response_code(500);
    renderErrorPage('An Error Occurred', 'Something went wrong. Please contact support if the problem persists.');
    error_log("Unexpected error on payment check for session $sessionId: " . $e->getMessage());
    $htmlTitle = 'System Error';
    $message = '<p>A system error occurred. Please try again later or contact support.</p>';
    $cssClass = 'error';
}
/**
 * Render success/failure page
 */
function renderSuccessPage(string $paymentStatus, string $email, float $amount, string $currency, string $sessionId, string $clientAlert): void
{
    if ($paymentStatus === 'paid') {
        // Payment was successful
        $title = 'Payment Successful!';
        $statusClass = 'success';
        $icon = '✓';
    } elseif ($paymentStatus === 'unpaid') {
        // Payment was not successful
        $title = 'Payment Incomplete';
        $statusClass = 'warning';
        $icon = '⚠';
    } elseif ($paymentStatus === 'no_payment_required') {
        // Trial started
        $title = 'Trial Started';
        $statusClass = 'info';
        $icon = '🆕';
    } else {
        // Other statuses
        $title = 'Payment Status: ' . ucfirst($paymentStatus);
        $statusClass = 'info';
        $icon = 'ℹ';
    }

?>
    <!DOCTYPE html>
    <html lang="en">

    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title><?= htmlspecialchars($title); ?></title>
        <style>
            * {
                margin: 0;
                padding: 0;
                box-sizing: border-box;
            }

            body {
                font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif;
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                min-height: 100vh;
                display: flex;
                align-items: center;
                justify-content: center;
                padding: 20px;
            }

            .container {
                background: white;
                border-radius: 12px;
                box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
                max-width: 500px;
                width: 100%;
                padding: 40px;
                text-align: center;
            }

            .icon {
                width: 80px;
                height: 80px;
                margin: 0 auto 20px;
                border-radius: 50%;
                display: flex;
                align-items: center;
                justify-content: center;
                font-size: 40px;
            }

            .success .icon {
                background: #d4edda;
                color: #28a745;
            }

            .warning .icon {
                background: #fff3cd;
                color: #ffc107;
            }

            h1 {
                color: #333;
                margin-bottom: 15px;
                font-size: 28px;
            }

            p {
                color: #666;
                margin-bottom: 15px;
                line-height: 1.6;
            }

            .details {
                background: #f8f9fa;
                border-radius: 8px;
                padding: 20px;
                margin: 25px 0;
                text-align: left;
            }

            .detail-row {
                display: flex;
                justify-content: space-between;
                padding: 10px 0;
                border-bottom: 1px solid #e9ecef;
            }

            .detail-row:last-child {
                border-bottom: none;
            }

            .detail-label {
                font-weight: 600;
                color: #495057;
            }

            .detail-value {
                color: #6c757d;
            }

            .btn {
                display: inline-block;
                padding: 12px 30px;
                background: #667eea;
                color: white;
                text-decoration: none;
                border-radius: 6px;
                font-weight: 600;
                margin-top: 20px;
                transition: background 0.3s;
            }

            .btn:hover {
                background: #5568d3;
            }

            .reference {
                font-size: 12px;
                color: #adb5bd;
                margin-top: 20px;
            }
        </style>
    </head>

    <body>
        <div class="container <?= $statusClass; ?>">
            <div class="icon">
                <?= $icon; ?>
            </div>

            <?= $clientAlert; ?>

            <?php if ($paymentStatus === 'paid'): ?>

                <div class="details">
                    <div class="detail-row">
                        <span class="detail-label">Amount:</span>
                        <span class="detail-value"><?= htmlspecialchars($currency . ' ' . number_format($amount, 2)); ?></span>
                    </div>
                    <div class="detail-row">
                        <span class="detail-label">Email:</span>
                        <span class="detail-value"><?= htmlspecialchars($email); ?></span>
                    </div>
                    <div class="detail-row">
                        <span class="detail-label">Status:</span>
                        <span class="detail-value">Paid</span>
                    </div>
                </div>

                <p>A confirmation email has been sent to <?= htmlspecialchars($email); ?></p>

                <a href="/" class="btn">Return to Home</a>

            <?php elseif ($paymentStatus === 'unpaid'): ?>

                <div class="details">
                    <div class="detail-row">
                        <span class="detail-label">Status:</span>
                        <span class="detail-value"><?= htmlspecialchars(ucfirst($paymentStatus)); ?></span>
                    </div>
                </div>

                <p>If you believe this is an error, please contact our support team.</p>

                <a href="/checkout" class="btn">Try Again</a>
            <?php elseif ($paymentStatus === 'no_payment_required'): ?>
                <p>No payment was required for this order.</p>
            <?php else: ?>
                <p>Your payment was not successful. Please try again.</p>
                <p>Payment status: <?= htmlspecialchars(ucfirst($paymentStatus)); ?></p>
            <?php endif; ?>

            <!-- <p class="reference">Reference: <?= htmlspecialchars(substr($sessionId, 0, 20)) . '...'; ?></p> -->
        </div>
    </body>

    </html>
<?php
}

/**
 * Render error page
 */
function renderErrorPage(string $title, string $message): void
{
?>
    <!DOCTYPE html>
    <html lang="en">

    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title><?= htmlspecialchars($title); ?></title>
        <style>
            * {
                margin: 0;
                padding: 0;
                box-sizing: border-box;
            }

            body {
                font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif;
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                min-height: 100vh;
                display: flex;
                align-items: center;
                justify-content: center;
                padding: 20px;
            }

            .container {
                background: white;
                border-radius: 12px;
                box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
                max-width: 500px;
                width: 100%;
                padding: 40px;
                text-align: center;
            }

            .icon {
                width: 80px;
                height: 80px;
                margin: 0 auto 20px;
                border-radius: 50%;
                background: #f8d7da;
                color: #dc3545;
                display: flex;
                align-items: center;
                justify-content: center;
                font-size: 40px;
            }

            h1 {
                color: #333;
                margin-bottom: 15px;
                font-size: 28px;
            }

            p {
                color: #666;
                margin-bottom: 20px;
                line-height: 1.6;
            }

            .btn {
                display: inline-block;
                padding: 12px 30px;
                background: #667eea;
                color: white;
                text-decoration: none;
                border-radius: 6px;
                font-weight: 600;
                transition: background 0.3s;
            }

            .btn:hover {
                background: #5568d3;
            }
        </style>
    </head>

    <body>
        <div class="container">
            <div class="icon">✕</div>
            <h1><?= htmlspecialchars($title); ?></h1>
            <p><?= htmlspecialchars($message); ?></p>
            <a href="/" class="btn">Return to Home</a>
        </div>
    </body>

    </html>
<?php
}
