<?php

namespace App\Http\Controllers;

use App\Models\Order;
use App\Models\ManualPaymentGateway;
use App\Models\ProductVariant;
use App\Services\AnalyticsTracker;
use App\Services\CheckoutService;
use Illuminate\Http\Request;
use RuntimeException;

class OrderController extends Controller
{
    public function store(Request $request, ProductVariant $productVariant, CheckoutService $checkoutService, AnalyticsTracker $analytics)
    {
        $payload = $request->validate([
            'customer_name' => ['required', 'string', 'max:120'],
            'customer_email' => ['nullable', 'email', 'max:190'],
            'player_id' => ['nullable', 'string', 'max:80'],
            'server' => ['nullable', 'string', 'max:80'],
            'notes' => ['nullable', 'string', 'max:500'],
            'payment_method' => ['required', 'in:manual,wallet,mock_gateway,online_gateway'],
            'coupon_code' => ['nullable', 'string', 'max:40'],
        ]);

        try {
            $order = $checkoutService->createOrder($productVariant, $payload, $request->user());
        } catch (RuntimeException $exception) {
            return back()->withErrors(['checkout' => $exception->getMessage()])->withInput();
        }

        $analytics->track($request, 'order_created', 'order', $order->id, [
            'order_number' => $order->order_number,
            'total_minor' => $order->total_minor,
            'payment_method' => $order->payment_method,
            'product_variant_id' => $productVariant->id,
        ]);

        if ($order->payment_method === 'mock_gateway') {
            return redirect()->route('payments.mock.show', $order);
        }

        if ($order->payment_method === 'online_gateway') {
            return redirect()->route('payments.online.show', $order);
        }

        return redirect()->route('orders.show', $order)->with('status', 'تم إنشاء الطلب بنجاح.');
    }

    public function show(Request $request, Order $order)
    {
        abort_unless(! $order->user_id || $request->user()?->id === $order->user_id || $request->user()?->isAdmin(), 403);

        $canRevealCodes = $order->canRevealDigitalCodes()
            && $request->user()
            && ($request->user()->id === $order->user_id || $request->user()->isAdmin());

        return view('orders.show', [
            'order' => $order->load([
                'items' => fn ($items) => $items->with($canRevealCodes ? ['stockCodes'] : []),
                'latestPaymentAttempt',
                'manualPaymentSubmissions.gateway',
            ]),
            'canRevealCodes' => $canRevealCodes,
            'manualPaymentGateways' => ManualPaymentGateway::where('is_active', true)->orderBy('sort_order')->get(),
        ]);
    }
}
