<?php

namespace App\Http\Controllers\Pages;

use App\Http\Controllers\Controller;
use App\Models\Shipment;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class TrackingController extends Controller
{
    public function track(Request $request) {
        $validation = Validator::make($request->all(), [
            'tracking_code' => 'required|size:10'
        ]);

        if($validation->fails()) {
            return response()->json([
                'errors' => $validation->errors(),
            ], 422);
        }

        $shipment = Shipment::firstWhere('tracking_code', $request->tracking_code);
        
        if($shipment != null) {
            session()->put('shipment', $shipment->id);
            return response()->json([
                'success' => [
                    'redirect' => route('tracking.details'),
                ],
            ]);
        }
        return response()->json([
            'errors' => ['Invalid tracking code.']
        ], 422);
    }

    public function details() {
        if(session()->exists('shipment')) {
            $shipment = Shipment::find(session('shipment'));
            return view('pages.tracking.details', [
                'shipment' => $shipment,
                'tracking' => $shipment->tracking,
            ]);
        }

        abort(403);
    }
}
