<?php

namespace portalpeople\stripe\controllers\api;

use portalpeople\stripe\models\Carts;
use portalpeople\stripe\models\HostedPage;
use RuntimeException;
use Yii;
use yii\web\Controller;
use yii\web\Response;

class HostedPageController extends Controller
{
    public $enableCsrfValidation = false;

    /**
     * Create a Stripe Checkout Session for a hosted payment page.
     *
     * POST /stripe/hostedpage/checkout
     *
     * Payload example:
     * {
     *   "items": [
     *     {
     *       "price_data": {
     *         "currency": "gbp",
     *         "unit_amount": 2000,
     *         "product_data": {"name": "T-Shirt"}
     *       },
     *       "quantity": 1
     *     }
     *   ],
     *   "successUrl": "https://example.com/success",
     *   "cancelUrl": "https://example.com/cancel",
     *   "customerEmail": "customer@example.com",
     *   "metadata": {"order_id": "123"}
     * }
     */
    public function actionCheckout(): array
    {
        Yii::$app->response->format = Response::FORMAT_JSON;

        if (!Yii::$app->request->isPost) {
            Yii::$app->response->statusCode = 405;
            return ['error' => 'POST required.'];
        }

        $params = Yii::$app->request->post();

        try {
            $session = HostedPage::createCheckoutSession($params);
            return [
                'success' => true,
                'session' => $session,
                'url' => $session['url'] ?? null,
            ];
        } catch (RuntimeException $e) {
            Yii::$app->response->statusCode = 400;
            return ['error' => $e->getMessage()];
        }
    }

    /**
     * Create a Stripe Payment Link for a reusable hosted checkout.
     *
     * POST /stripe/hostedpage/payment-link
     *
     * Payload example:
     * {
     *   "items": [
     *     {
     *       "price_data": {
     *         "currency": "gbp",
     *         "unit_amount": 2000,
     *         "product_data": {"name": "Digital Download"}
     *       },
     *       "quantity": 1
     *     }
     *   ],
     *   "redirectUrl": "https://example.com/thanks",
     *   "metadata": {"campaign": "summer_sale"}
     * }
     */
    public function actionPaymentLink(): array
    {
        Yii::$app->response->format = Response::FORMAT_JSON;

        if (!Yii::$app->request->isPost) {
            Yii::$app->response->statusCode = 405;
            return ['error' => 'POST required.'];
        }

        $params = Yii::$app->request->post();

        try {
            $link = HostedPage::createPaymentLink($params);
            return [
                'success' => true,
                'link' => $link,
                'url' => $link['url'] ?? null,
            ];
        } catch (RuntimeException $e) {
            Yii::$app->response->statusCode = 400;
            return ['error' => $e->getMessage()];
        }
    }

    /**
     * Create a Stripe Checkout Session from an existing Cart.
     *
     * POST /stripe/hostedpage/checkout-from-cart
     *
     * Payload example:
     * {
     *   "cartId": "abc-123",
     *   "successUrl": "https://example.com/success",
     *   "cancelUrl": "https://example.com/cancel",
     *   "metadata": {"source": "checkout"}
     * }
     */
    public function actionCheckoutFromCart(): array
    {
        Yii::$app->response->format = Response::FORMAT_JSON;

        if (!Yii::$app->request->isPost) {
            Yii::$app->response->statusCode = 405;
            return ['error' => 'POST required.'];
        }

        $params = Yii::$app->request->post();
        $cartId = trim((string) ($params['cartId'] ?? ''));

        if ($cartId === '') {
            Yii::$app->response->statusCode = 400;
            return ['error' => 'Parameter "cartId" is required.'];
        }

        /** @var Carts|null $cart */
        $cart = Carts::findOne($cartId);

        if ($cart === null) {
            Yii::$app->response->statusCode = 404;
            return ['error' => 'Cart not found.'];
        }

        try {
            $session = HostedPage::createCheckoutSessionFromCart($cart, $params);
            return [
                'success' => true,
                'session' => $session,
                'url' => $session['url'] ?? null,
            ];
        } catch (RuntimeException $e) {
            Yii::$app->response->statusCode = 400;
            return ['error' => $e->getMessage()];
        }
    }

    /**
     * Retrieve a checkout session or payment link details.
     *
     * GET /stripe/hostedpage/retrieve?id=<sessionId>&type=checkout_session
     */
    public function actionRetrieve(): array
    {
        Yii::$app->response->format = Response::FORMAT_JSON;

        $sessionId = trim((string) Yii::$app->request->get('id', ''));
        $type = trim((string) Yii::$app->request->get('type', 'checkout_session'));

        if ($sessionId === '') {
            Yii::$app->response->statusCode = 400;
            return ['error' => 'Query parameter "id" is required.'];
        }

        try {
            $session = HostedPage::retrieve($sessionId, $type);
            return [
                'success' => true,
                'session' => $session,
            ];
        } catch (RuntimeException $e) {
            Yii::$app->response->statusCode = 400;
            return ['error' => $e->getMessage()];
        }
    }
}
