<?php

namespace App\Http\Controllers\Web;

use App\Http\Controllers\Controller;
use App\Models\Order;
use App\Support\PaymentFailure;

class PaymentStatusController extends Controller
{
    public function show($orderId)
    {
        $user = auth()->user();

        $order = Order::where('id', $orderId)
            ->where('user_id', $user->id)
            ->first();

        if (!$order) {
            if (request()->expectsJson() || request()->query('json')) {
                return response()->json(['paid' => false], 404);
            }

            return redirect('/cart');
        }

        if (request()->query('json')) {
            return response()->json([
                'paid' => $order->status === Order::$paid,
                'status' => $order->status,
            ]);
        }

        $purchasedCourseUrl = null;
        if ($order->status === Order::$paid) {
            $order->loadMissing('orderItems.webinar');
            foreach ($order->orderItems as $item) {
                if (!empty($item->webinar) && !empty($item->webinar->slug)) {
                    $purchasedCourseUrl = $item->webinar->getLearningPageUrl();
                    break;
                }
            }
        }

        return view('web.default.cart.status_pay', [
            'pageTitle' => trans('public.cart_page_title'),
            'order' => $order,
            'paymentFailureReason' => PaymentFailure::resolveReason($order),
            'paymentPending' => in_array($order->status, [Order::$pending, Order::$paying], true),
            'purchasedCourseUrl' => $purchasedCourseUrl,
        ]);
    }
}
