<?php

namespace App\Http\Controllers\Web;

use App\Http\Controllers\Controller;
use App\Models\Order;
use App\Services\EasyKashService;
use App\Services\PaymentTransactionLogger;
use App\Support\PaymentFailure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class EasyKashReturnController extends Controller
{
    /**
     * Browser redirect after EasyKash hosted payment.
     * Finalizes the order here when EasyKash confirms success (webhook may arrive later).
     */
    public function handle(Request $request, PaymentController $paymentController, EasyKashService $easyKashService)
    {
        $user = auth()->user();
        $order = $this->resolveOrder($request, $user ? $user->id : null);

        if (!$order) {
            return redirect('/cart');
        }

        $queryPayload = $request->query();

        if ($easyKashService->isFailedPaymentPayload($queryPayload)
            && in_array($order->status, [Order::$pending, Order::$paying], true)) {
            $reason = $this->buildReturnFailureReason($request);
            PaymentFailure::markOrderFailed($order, $reason);

            PaymentTransactionLogger::logForOrder($order, 'easykash_return', 'failed', $reason, [
                'response_body' => json_encode($queryPayload, JSON_UNESCAPED_UNICODE),
            ]);
        } elseif ($easyKashService->canTrustSuccessfulReturn($queryPayload)
            && in_array($order->status, [Order::$pending, Order::$paying], true)) {
            $finalized = $paymentController->finalizeSuccessfulGatewayPayment($order);
            $order->refresh();

            PaymentTransactionLogger::logForOrder($order, 'easykash_return', $finalized ? 'success' : 'skipped', null, [
                'response_body' => json_encode($queryPayload, JSON_UNESCAPED_UNICODE),
            ]);

            if (!$finalized) {
                Log::notice('easykash.return.success_not_finalized', [
                    'order_id' => $order->id,
                    'status' => $order->status,
                ]);
            }
        }

        if ($order->status === Order::$fail) {
            PaymentFailure::flash(PaymentFailure::resolveReason($order) ?? '');
        }

        $redirectStatus = strtolower((string) $request->get('status', ''));

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

    private function resolveOrder(Request $request, ?int $userId): ?Order
    {
        $orderId = $request->get('order_id');

        if (empty($orderId) && $request->filled('customerReference')) {
            $orderId = EasyKashService::resolveOrderIdFromCustomerReference((int) $request->get('customerReference'));
        }

        if (empty($orderId)) {
            return null;
        }

        $query = Order::where('id', $orderId);

        if ($userId) {
            $query->where('user_id', $userId);
        }

        return $query->first();
    }

    private function resolvePurchasedCourseUrl(Order $order): ?string
    {
        if ($order->status !== Order::$paid) {
            return null;
        }

        $order->loadMissing('orderItems.webinar');

        foreach ($order->orderItems as $item) {
            if (!empty($item->webinar) && !empty($item->webinar->slug)) {
                return $item->webinar->getLearningPageUrl();
            }
        }

        return null;
    }

    private function buildReturnFailureReason(Request $request): string
    {
        foreach (['message', 'error', 'reason', 'statusMessage', 'failure_reason'] as $key) {
            $value = $request->get($key);
            if (is_string($value) && trim($value) !== '') {
                return 'رفض الدفع من EasyKash: ' . trim($value);
            }
        }

        $status = $request->get('status');
        $extra = array_filter($request->query(), static function ($value) {
            return $value !== null && $value !== '';
        });

        $suffix = $status ? ' (حالة: ' . $status . ')' : '';
        if (count($extra) > 0) {
            $suffix .= ' — ' . json_encode($extra, JSON_UNESCAPED_UNICODE);
        }

        return 'تم إلغاء أو رفض الدفع من صفحة EasyKash' . $suffix;
    }
}
