<?php

namespace App\Http\Controllers;

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

class AdminOrderController extends Controller
{
    public function index()
    {
        $query = trim((string) request('q', ''));
        $payment = (string) request('payment_status', '');
        $fulfillment = (string) request('fulfillment_status', '');
        $ordersQuery = Order::query()
            ->with(['items', 'user'])
            ->when($query !== '', function ($builder) use ($query) {
                $builder->where(function ($nested) use ($query) {
                    $nested
                        ->where('order_number', 'like', "%{$query}%")
                        ->orWhere('customer_name', 'like', "%{$query}%")
                        ->orWhere('customer_email', 'like', "%{$query}%");
                });
            })
            ->when($payment, fn ($builder) => $builder->where('payment_status', $payment))
            ->when($fulfillment, fn ($builder) => $builder->where('fulfillment_status', $fulfillment));

        return view('admin.orders.index', [
            'orders' => (clone $ordersQuery)->latest()->paginate(20)->withQueryString(),
            'summary' => [
                'total' => Order::count(),
                'paid' => Order::where('payment_status', 'paid')->count(),
                'pending' => Order::where('payment_status', 'pending')->count(),
                'needsFulfillment' => Order::whereIn('fulfillment_status', ['pending', 'processing'])->count(),
                'failed' => Order::where('fulfillment_status', 'failed')->count(),
                'revenue' => Order::where('payment_status', 'paid')->sum('total_minor'),
            ],
            'query' => $query,
            'payment' => $payment,
            'fulfillment' => $fulfillment,
        ]);
    }

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

    public function markPaid(Request $request, Order $order, FulfillmentService $fulfillment)
    {
        $fulfillment->markPaid($order, $request->user());

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

    public function complete(Request $request, Order $order, FulfillmentService $fulfillment)
    {
        $fulfillment->complete($order, $request->user());

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