<?php

namespace App\Http\Controllers;

use App\Models\Driver;
use App\Models\Truck;
use Illuminate\Http\Request;
use Illuminate\Http\RedirectResponse;
use Illuminate\View\View;
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
{
    // Middleware applied in routes

    /**
     * Resolve the maximum number of drivers allowed for the authenticated 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 drivers.
     */
    public function index(): View
    {
        $user = auth()->user();
        $drivers = Driver::where('company_id', $user->company_id)->with('truck')->get();
        $driverCount = $drivers->count();
        $driverLimit = $this->resolveDriverLimit($user);
        $canAddDriver = $driverLimit === null || $driverCount < $driverLimit;

        return view('drivers.index', compact('drivers', 'driverCount', 'driverLimit', 'canAddDriver'));
    }

    /**
     * Show create form.
     */
    public function create(): View|RedirectResponse
    {
        $user = auth()->user();
        $driverLimit = $this->resolveDriverLimit($user);
        $driverCount = Driver::where('company_id', $user->company_id)->count();
        $remainingDriverSlots = $driverLimit !== null ? max($driverLimit - $driverCount, 0) : null;

        if ($driverLimit !== null && $driverCount >= $driverLimit) {
            return redirect()->route('owner.drivers.index')
                ->withErrors(['driver_limit' => 'Driver limit reached for your current package.']);
        }

        $trucks = Truck::where('company_id', $user->company_id)->get();
        return view('drivers.create', compact('trucks', 'driverCount', 'driverLimit', 'remainingDriverSlots'));
    }

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

        if ($driverLimit !== null && $driverCount >= $driverLimit) {
            return redirect()->route('owner.drivers.index')
                ->withErrors(['driver_limit' => 'Driver limit reached for your current package.'])
                ->withInput();
        }

        $userEmail = auth()->user()->email;
        $emailRule = 'required|email';
        if ($request->email !== $userEmail) {
            $emailRule .= '|unique:drivers,email';
        }
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'email' => $emailRule,
            '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 = Driver::create(array_merge($validated, [
            'company_id' => $user->company_id,
        ]));

        // 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' => 'web',
                'company_id' => $user->company_id,
                'driver_name' => $driver->name,
            ],
            [$driver->email]
        );

        return redirect()->route('owner.drivers.index')->with('success', 'Driver added successfully!');
    }

    /**
     * Show edit form.
     */
    public function edit(Driver $driver): View
    {
        $user = auth()->user();

        if ($driver->company_id !== $user->company_id) {
            abort(403);
        }

        $driverCount = Driver::where('company_id', $user->company_id)->count();
        $driverLimit = $this->resolveDriverLimit($user);
        $remainingDriverSlots = $driverLimit !== null ? max($driverLimit - $driverCount, 0) : null;

        $trucks = Truck::where('company_id', $user->company_id)->get();
        return view('drivers.edit', compact('driver', 'trucks', 'driverCount', 'driverLimit', 'remainingDriverSlots'));
    }

    /**
     * Update driver.
     */
    public function update(Request $request, Driver $driver, ActionNotificationService $notifications): RedirectResponse
    {
        if ($driver->company_id !== auth()->user()->company_id) {
            abort(403);
        }

        $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',
            auth()->user(),
            [
                'channel' => 'web',
                'company_id' => $driver->company_id,
                'driver_name' => $driver->name,
            ],
            [$driver->email]
        );

        return redirect()->route('owner.drivers.index')->with('success', 'Driver updated successfully!');
    }

    /**
     * Delete driver.
     */
    public function destroy(Driver $driver, ActionNotificationService $notifications): RedirectResponse
    {
        if ($driver->company_id !== auth()->user()->company_id) {
            abort(403);
        }

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

        $driver->delete();

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

        return redirect()->route('owner.drivers.index')->with('success', 'Driver deleted successfully!');
    }
}

