<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Driver;
use App\Models\Truck;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use App\Services\ActionNotificationService;
use App\Services\DriverAccountService;
use App\Mail\DriverInvitationMail;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Str;

class DriverController extends Controller
{
    /**
     * Resolve maximum drivers allowed for a user.
     */
    private function resolveDriverLimit($user): ?int
    {
        $packageLimit = (int) $user->getDriverLimit();
        if ($packageLimit > 0) {
            return $packageLimit;
        }

        $companyLimit = (int) ($user->company?->num_drivers ?? 0);
        return $companyLimit > 0 ? $companyLimit : null;
    }

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

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

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

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

    /**
     * Get available trucks for driver assignment (dropdown).
     */
    public function availableTrucks(Request $request): JsonResponse
    {
        $user = $request->user();
        $trucks = Truck::where('company_id', $user->company_id)
                       ->whereDoesntHave('driver')
                       ->get(['id', 'number', 'name']);

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

    /**
     * Store a newly created driver.
     */
    public function store(Request $request, ActionNotificationService $notifications, DriverAccountService $driverAccountService): JsonResponse
    {
        $user = $request->user();
        $driverLimit = $this->resolveDriverLimit($user);
        $driverCount = Driver::where('company_id', $user->company_id)->count();

        if ($driverLimit !== null && $driverCount >= $driverLimit) {
            return response()->json([
                'success' => false,
                'message' => 'Driver limit reached for your current package.',
            ], 422);
        }

        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|email|unique:drivers,email',
            'phone' => 'required|string|max:20',
            'truck_id' => 'nullable|exists:trucks,id',
            'salary_per_mile' => 'nullable|numeric|min:0',
            'salary_percent' => 'nullable|numeric|min:0|max:100',
        ]);

        $validated['company_id'] = $user->company_id;

        $driver = Driver::create($validated);

        // Create or update User account for driver
        $temporaryPassword = Str::random(12);
        $driverUser = $driverAccountService->createOrUpdateDriverAccount($driver);
        
        // Force set the temporary password
        $driverUser->update([
            'password' => \Illuminate\Support\Facades\Hash::make($temporaryPassword),
        ]);

        // Send invitation email
        Mail::to($driver->email)->queue(new DriverInvitationMail($driver, $temporaryPassword));

        $notifications->notifyAction(
            'Driver Created',
            $user,
            [
                'channel' => 'mobile',
                'company_id' => $user->company_id,
                'driver_name' => $driver->name,
            ],
            [$driver->email]
        );

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

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

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

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

        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|email|unique:drivers,email,' . $driver->id,
            'phone' => 'required|string|max:20',
            'truck_id' => 'nullable|exists:trucks,id',
            'salary_per_mile' => 'nullable|numeric|min:0',
            'salary_percent' => 'nullable|numeric|min:0|max:100',
        ]);

        $driver->update($validated);

        $notifications->notifyAction(
            'Driver Updated',
            $request->user(),
            [
                'channel' => 'mobile',
                'company_id' => $driver->company_id,
                'driver_name' => $driver->name,
            ],
            [$driver->email]
        );

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

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

        $driverEmail = $driver->email;
        $driverName = $driver->name;
        $companyId = $driver->company_id;

        $driver->delete();

        $notifications->notifyAction(
            'Driver Deleted',
            $request->user(),
            [
                'channel' => 'mobile',
                'company_id' => $companyId,
                'driver_name' => $driverName,
            ],
            [$driverEmail]
        );

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

