<?php

namespace App\Http\Controllers\Api\Driver;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Services\ShiftService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Password;

class AuthController extends Controller
{
    /**
     * Company-scoped login for the driver app — mirrors the admin web
     * login's company_id+email+password shape (LoginRequest) so both
     * surfaces authenticate the same way, but only succeeds for a User
     * that actually has a linked Driver profile.
     */
    public function login(Request $request): JsonResponse
    {
        $data = $request->validate([
            'company_id' => ['required', 'exists:companies,id'],
            'email' => ['required', 'email'],
            'password' => ['required', 'string'],
        ]);

        $user = User::where('company_id', $data['company_id'])
            ->where('email', $data['email'])
            ->where('status', 'active')
            ->with('driver')
            ->first();

        if (! $user || ! Hash::check($data['password'], $user->password) || ! $user->driver) {
            return response()->json(['message' => __('api.driver_invalid_credentials')], 422);
        }

        $user->tokens()->delete();
        $token = $user->createToken('driver-app', ['driver'], now()->addDays(90))->plainTextToken;
        $user->forceFill(['last_login_at' => now()])->save();

        return response()->json([
            'token' => $token,
            'driver' => $user->driver,
            'user' => $user->only(['id', 'name', 'email', 'phone']),
        ]);
    }

    public function logout(Request $request, ShiftService $shifts): JsonResponse
    {
        $driver = $request->user()->driver;

        if ($driver) {
            $activeShift = $driver->shifts()->whereNull('ended_at')->first();
            if ($activeShift) {
                $shifts->end($activeShift, $request->user(), 'Logged out');
            }
        }

        $request->user()->currentAccessToken()->delete();

        return response()->json(['message' => __('api.logged_out')]);
    }

    /**
     * Emails a password reset link via Laravel's standard password broker
     * rather than the old project's OTP-less "email exists + active" reset
     * (which let anyone probe which emails were registered).
     */
    public function forgotPassword(Request $request): JsonResponse
    {
        $data = $request->validate(['email' => ['required', 'email']]);

        Password::sendResetLink($data);

        return response()->json(['message' => __('api.reset_link_sent')]);
    }
}
