<?php
/**
 * Stripe Checkout integration helpers.
 * Uses direct Stripe REST calls so the project does not require Composer.
 */

function stripe_api_request(string $secretKey, string $method, string $endpoint, array $payload = []): array
{
    $secretKey = trim($secretKey);

    if ($secretKey === '') {
        throw new RuntimeException('Stripe secret key is missing.');
    }

    if (!function_exists('curl_init')) {
        throw new RuntimeException('PHP cURL extension is required for Stripe payments.');
    }

    $url = 'https://api.stripe.com/v1/' . ltrim($endpoint, '/');
    $curl = curl_init();

    $headers = [
        'Authorization: Bearer ' . $secretKey,
        'Content-Type: application/x-www-form-urlencoded',
    ];

    $options = [
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => $headers,
        CURLOPT_CUSTOMREQUEST => strtoupper($method),
        CURLOPT_TIMEOUT => 30,
    ];

    if (!empty($payload)) {
        $options[CURLOPT_POSTFIELDS] = http_build_query($payload);
    }

    curl_setopt_array($curl, $options);

    $responseBody = curl_exec($curl);
    $curlError = curl_error($curl);
    $statusCode = (int)curl_getinfo($curl, CURLINFO_HTTP_CODE);
    curl_close($curl);

    if ($responseBody === false) {
        throw new RuntimeException('Stripe connection failed: ' . $curlError);
    }

    $decodedResponse = json_decode($responseBody, true);

    if (!is_array($decodedResponse)) {
        throw new RuntimeException('Stripe returned an invalid response.');
    }

    if ($statusCode < 200 || $statusCode >= 300) {
        $message = $decodedResponse['error']['message'] ?? 'Stripe API request failed.';
        throw new RuntimeException($message);
    }

    return $decodedResponse;
}

function stripe_create_checkout_session(
    string $secretKey,
    array $order,
    string $currency,
    string $successUrl,
    string $cancelUrl
): array {
    $payableAmount = !empty($order['total_amount']) ? (float)$order['total_amount'] : (float)$order['price'];
    $amountInCents = (int)round($payableAmount * 100);

    if ($amountInCents <= 0) {
        throw new RuntimeException('Stripe payable amount must be greater than zero.');
    }

    $payload = [
        'mode' => 'payment',
        'success_url' => $successUrl,
        'cancel_url' => $cancelUrl,
        'client_reference_id' => (string)$order['id'],
        'customer_email' => (string)($order['customer_email'] ?? ''),
        'metadata' => [
            'order_id' => (string)$order['id'],
            'user_id' => (string)$order['user_id'],
        ],
        'line_items' => [
            [
                'quantity' => 1,
                'price_data' => [
                    'currency' => strtolower($currency),
                    'unit_amount' => $amountInCents,
                    'product_data' => [
                        'name' => (string)$order['item_name'],
                        'metadata' => [
                            'item_id' => (string)$order['item_id'],
                        ],
                    ],
                ],
            ],
        ],
    ];

    return stripe_api_request($secretKey, 'POST', 'checkout/sessions', $payload);
}

function stripe_retrieve_checkout_session(string $secretKey, string $sessionId): array
{
    $sessionId = trim($sessionId);

    if ($sessionId === '') {
        throw new RuntimeException('Stripe session id is missing.');
    }

    return stripe_api_request($secretKey, 'GET', 'checkout/sessions/' . rawurlencode($sessionId));
}
