<?php

namespace App\Http\Controllers;

use App\Models\Order;
use Illuminate\Http\Request;
use Illuminate\View\View;

class OrderTrackingController extends Controller
{
    public function __invoke(Request $request): View
    {
        $order = null;
        $hasSearch = $request->filled('order_number') || $request->filled('delivery_phone');

        if ($hasSearch) {
            $data = $request->validate([
                'order_number' => ['required', 'string', 'max:80'],
                'delivery_phone' => ['required', 'string', 'max:40'],
            ]);

            $order = Order::query()
                ->with('items')
                ->where('order_number', trim($data['order_number']))
                ->where('delivery_phone', trim($data['delivery_phone']))
                ->first();
        }

        return view('orders.track', [
            'order' => $order,
            'hasSearch' => $hasSearch,
            'orderNumber' => $request->string('order_number')->toString(),
            'deliveryPhone' => $request->string('delivery_phone')->toString(),
        ]);
    }
}
