<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Truck;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use App\Services\ActionNotificationService;

class TruckController extends Controller
{
    private function normalizeTruckPayload(Request $request, ?Truck $truck = null): void
    {
        $request->merge([
            'number' => $request->input('number', $request->input('truck_number', $request->input('truckNumber', $truck?->number))),
            'name' => $request->input('name', $request->input('type', $request->input('truck_type', $truck?->name))),
            'equipment_number' => $request->input('equipment_number', $request->input('equipment', $request->input('equipmentNumber', $truck?->equipment_number))),
            'fuel_cost_per_mile' => $request->input('fuel_cost_per_mile', $request->input('fuelCostPerMile', $truck?->fuel_cost_per_mile ?? 0)),
        ]);
    }

    /**
     * Display a listing of user's company trucks.
     */
    public function index(Request $request): JsonResponse
    {
        $user = $request->user();
        $query = Truck::where('company_id', $user->company_id);

        if ($request->filled('search')) {
            $query->where('number', 'like', '%' . $request->search . '%')
                  ->orWhere('name', 'like', '%' . $request->search . '%');
        }

        $trucks = $query->withCount('drivers')->paginate($request->input('per_page', 15));

        return response()->json([
            'success' => true,
            'data' => $trucks->items(),
            'pagination' => [
                'current_page' => $trucks->currentPage(),
                'per_page' => $trucks->perPage(),
                'total' => $trucks->total(),
                'last_page' => $trucks->lastPage(),
            ],
        ], 200);
    }

    /**
     * Store a newly created truck.
     */
    public function store(Request $request, ActionNotificationService $notifications): JsonResponse
    {
        $this->normalizeTruckPayload($request);

        $validated = $request->validate([
            'number' => 'required|string|max:50',
            'name' => 'required|string|max:100',
            'equipment_number' => 'required|string|max:50',
            'fuel_cost_per_mile' => 'required|numeric|min:0',
        ]);

        $truck = Truck::create(array_merge($validated, [
            'company_id' => $request->user()->company_id,
        ]));

        $notifications->notifyAction(
            'Truck Created',
            $request->user(),
            [
                'channel' => 'mobile',
                'company_id' => $truck->company_id,
                'truck_number' => $truck->number,
                'truck_name' => $truck->name,
            ]
        );

        return response()->json([
            'success' => true,
            'message' => 'Truck created successfully.',
            'data' => $truck->loadCount('drivers'),
        ], 201);
    }

    /**
     * Display the specified truck.
     */
    public function show(Truck $truck, Request $request): JsonResponse
    {
        if ($truck->company_id !== $request->user()->company_id) {
            return response()->json([
                'success' => false,
                'message' => 'Truck not found.',
            ], 404);
        }

        return response()->json([
            'success' => true,
            'data' => $truck->loadCount('drivers'),
        ], 200);
    }

    /**
     * Update the specified truck.
     */
    public function update(Request $request, Truck $truck, ActionNotificationService $notifications): JsonResponse
    {
        if ($truck->company_id !== $request->user()->company_id) {
            return response()->json([
                'success' => false,
                'message' => 'Truck not found.',
            ], 404);
        }

        $this->normalizeTruckPayload($request, $truck);

        $validated = $request->validate([
            'number' => 'required|string|max:50',
            'name' => 'required|string|max:100',
            'equipment_number' => 'required|string|max:50',
            'fuel_cost_per_mile' => 'required|numeric|min:0',
        ]);

        $truck->update($validated);

        $notifications->notifyAction(
            'Truck Updated',
            $request->user(),
            [
                'channel' => 'mobile',
                'company_id' => $truck->company_id,
                'truck_number' => $truck->number,
                'truck_name' => $truck->name,
            ]
        );

        return response()->json([
            'success' => true,
            'message' => 'Truck updated successfully.',
            'data' => $truck->fresh()->loadCount('drivers'),
        ], 200);
    }

    /**
     * Remove the specified truck.
     */
    public function destroy(Truck $truck, Request $request, ActionNotificationService $notifications): JsonResponse
    {
        if ($truck->company_id !== $request->user()->company_id) {
            return response()->json([
                'success' => false,
                'message' => 'Truck not found.',
            ], 404);
        }

        $truckNumber = $truck->number;
        $truckName = $truck->name;
        $companyId = $truck->company_id;

        $truck->delete();

        $notifications->notifyAction(
            'Truck Deleted',
            $request->user(),
            [
                'channel' => 'mobile',
                'company_id' => $companyId,
                'truck_number' => $truckNumber,
                'truck_name' => $truckName,
            ]
        );

        return response()->json([
            'success' => true,
            'message' => 'Truck deleted successfully.',
        ], 200);
    }
}

