<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Models\Order;
use App\Services\UserOrderService;
use Illuminate\Contracts\View\View;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use RuntimeException;

class OrderController extends Controller
{
    public function index(Request $request): View
    {
        $status = trim((string) $request->query('status', ''));
        $search = trim((string) $request->query('q', ''));

        $query = Order::query()
            ->where('user_id', auth()->id())
            ->with('items')
            ->latest('id');

        if ($status !== '') {
            $query->where('status', $status);
        }

        if ($search !== '') {
            $query->where(function ($builder) use ($search): void {
                $builder->where('order_number', 'like', "%{$search}%")
                    ->orWhere('payment_method', 'like', "%{$search}%");
            });
        }

        return view('user.orders', [
            'orders' => $query->paginate(12)->withQueryString(),
            'status' => $status,
            'search' => $search,
            'summary' => [
                'total' => Order::query()->where('user_id', auth()->id())->count(),
                'pending' => Order::query()->where('user_id', auth()->id())->where('status', 'pending_payment')->count(),
                'approved' => Order::query()->where('user_id', auth()->id())->where('status', 'approved')->count(),
                'delivered' => Order::query()->where('user_id', auth()->id())->where('status', 'delivered')->count(),
                'total_amount' => (float) Order::query()->where('user_id', auth()->id())->sum('total'),
            ],
        ]);
    }

    public function cancel(Order $order, UserOrderService $orderService): RedirectResponse
    {
        try {
            $orderService->cancelOrder(auth()->user(), $order);
        } catch (RuntimeException $exception) {
            return back()->withErrors(['order' => $exception->getMessage()]);
        }

        return back()->with('status', 'Order cancelled successfully.');
    }

    public function invoice(Order $order)
    {
        abort_unless((int) $order->user_id === (int) auth()->id(), 403);
        $order->load('items', 'user');

        return response()->view('user.order-invoice', compact('order'));
    }
}

