<?php

namespace App\Http\Controllers;

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

class OrderTrackingController extends Controller
{
    public function index(Request $request, $order_number = null)
    {
        $order = null;
        $searchedNumber = $order_number ?: $request->query('order_number');

        if ($searchedNumber) {
            $searchedNumber = strtoupper(trim($searchedNumber));
            // Support numbers passed with or without DIV- prefix
            if (!str_starts_with($searchedNumber, 'DIV-')) {
                $queryNumber = 'DIV-' . ltrim($searchedNumber, '#');
            } else {
                $queryNumber = $searchedNumber;
            }

            $order = Order::with('items')->where('order_number', $queryNumber)->orWhere('order_number', $searchedNumber)->first();
        }

        return view('pages.track-order', [
            'order' => $order,
            'searchedNumber' => $searchedNumber,
        ]);
    }

    public function search(Request $request)
    {
        $request->validate([
            'order_number' => 'required|string',
        ]);

        $orderNumber = strtoupper(trim($request->order_number));

        return redirect()->route('order.track', ['order_number' => $orderNumber]);
    }
}
