<?php

namespace App\Http\Controllers;

use App\Models\Order;
use App\Services\FulfillmentService;
use Illuminate\Http\Request;
use RuntimeException;

class AdminFulfillmentController extends Controller
{
    public function index(Request $request)
    {
        $status = $request->query('status', 'active');

        return view('admin.fulfillment.index', [
            'status' => $status,
            'orders' => Order::with(['items', 'assignee'])
                ->when($status === 'active', fn ($query) => $query->whereIn('fulfillment_status', ['pending', 'claimed', 'info_requested']))
                ->when($status !== 'active', fn ($query) => $query->where('fulfillment_status', $status))
                ->latest()
                ->paginate(20)
                ->withQueryString(),
        ]);
    }

    public function show(Order $order)
    {
        return view('admin.fulfillment.show', [
            'order' => $order->load(['items.stockCodes', 'items.latestProviderAttempt', 'latestPaymentAttempt', 'notificationDeliveries', 'assignee', 'timelines.actor']),
        ]);
    }

    public function claim(Request $request, Order $order, FulfillmentService $fulfillment)
    {
        try {
            $fulfillment->claim($order, $request->user());
        } catch (RuntimeException $exception) {
            return back()->withErrors(['fulfillment' => $exception->getMessage()]);
        }

        return back()->with('status', 'تم استلام الطلب.');
    }

    public function complete(Request $request, Order $order, FulfillmentService $fulfillment)
    {
        $data = $request->validate([
            'note' => ['nullable', 'string', 'max:1000'],
        ]);

        try {
            $fulfillment->complete($order, $request->user(), $data['note'] ?? null);
        } catch (RuntimeException $exception) {
            return back()->withErrors(['fulfillment' => $exception->getMessage()]);
        }

        return back()->with('status', 'تم تنفيذ الطلب.');
    }

    public function fail(Request $request, Order $order, FulfillmentService $fulfillment)
    {
        $data = $request->validate([
            'reason' => ['required', 'string', 'max:1000'],
        ]);

        $fulfillment->fail($order, $request->user(), $data['reason']);

        return back()->with('status', 'تم تسجيل فشل الطلب.');
    }

    public function requestInfo(Request $request, Order $order, FulfillmentService $fulfillment)
    {
        $data = $request->validate([
            'note' => ['required', 'string', 'max:1000'],
        ]);

        $fulfillment->requestInfo($order, $request->user(), $data['note']);

        return back()->with('status', 'تم طلب معلومات من العميل.');
    }
}
