<?php

namespace App\Http\Controllers;

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

class TrackingController extends Controller
{
    /**
     * Show the tracking form
     * 
     * @return \Illuminate\View\View
     */
    public function show()
    {
        return view('tracking.form');
    }

    /**
     * Track a shipment by tracking number
     * 
     * @param  \Illuminate\Http\Request  $request
     * @param  string|null  $tracking_number
     * @return \Illuminate\View\View|\Illuminate\Http\RedirectResponse
     */
    public function track(Request $request, $tracking_number = null)
    {
        // Use the route parameter if provided, otherwise use the form input
        $trackingNumber = $tracking_number ?? $request->input('tracking_number');
        
        if (empty($trackingNumber)) {
            return redirect()->route('track')
                ->with('error', 'Please provide a tracking number');
        }
        
        // Clean up tracking number (remove spaces, etc.)
        $trackingNumber = trim($trackingNumber);
        
        // If multiple tracking numbers are provided (comma-separated), take the first one
        if (strpos($trackingNumber, ',') !== false) {
            $trackingNumbers = explode(',', $trackingNumber);
            $trackingNumber = trim($trackingNumbers[0]);
            
            // If there are multiple tracking numbers, we may want to inform the user
            if (count($trackingNumbers) > 1) {
                session()->flash('info', 'Multiple tracking numbers detected. Showing results for the first number.');
            }
        }

        // Find the shipment with eager loading of tracking updates
        $shipment = Shipment::with(['trackingUpdates' => function($query) {
            $query->orderBy('created_at', 'asc');
        }])->where('tracking_number', $trackingNumber)->first();

        if (!$shipment) {
            return redirect()->route('track')
                ->with('error', "Tracking number '$trackingNumber' not found. Please check and try again.");
        }

        $progress = $shipment->travel_progress;

        return view('tracking.show', compact('shipment', 'progress'));
    }
    
}
