<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Auth\Events\PasswordReset;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Password;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Str;
use App\Mail\PasswordResetMail;

class AuthController extends Controller
{
    // Affiche le formulaire de login
    public function showLoginForm()
    {
        return view('auth.login');
    }

    // Traite le login
    public function login(Request $r)
    {
        $credentials = $r->validate([
            'email'    => 'required|email',
            'password' => 'required|string',
        ]);

        if (Auth::attempt($credentials, $r->filled('remember'))) {
            $r->session()->regenerate();
            if (Auth::user()->force_password_change) {
                return redirect()->route('account.password.edit');
            }
            return redirect()->intended(route('admin.dashboard'));
        }

        return back()
            ->withErrors(['email' => 'Identifiants invalides.'])
            ->onlyInput('email');
    }

    // Affiche le formulaire d’inscription
    public function showRegisterForm()
    {
        return view('auth.register');
    }

    // Traite l’inscription
    public function register(Request $r)
    {
        $data = $r->validate([
            'name'     => 'required|string|max:255',
            'email'    => 'required|email|unique:users',
            'password' => 'required|string|min:8|confirmed',
        ]);

        $user = User::create([
            'name'     => $data['name'],
            'email'    => $data['email'],
            'password' => Hash::make($data['password']),
            // 'is_admin' restera false par défaut
        ]);

        Auth::login($user);
        return redirect()->route('admin.dashboard');
    }

    // Déconnexion
    public function logout(Request $r)
    {
        Auth::logout();
        $r->session()->invalidate();
        $r->session()->regenerateToken();
        return redirect()->route('login');
    }

    // Affiche le formulaire "mot de passe oublié"
    public function showForgotPasswordForm()
    {
        return view('auth.forgot-password');
    }

    // Envoie un mot de passe temporaire au lieu d'un lien
    public function sendResetLinkEmail(Request $request)
    {
        $request->validate(['email' => 'required|email']);

        $user = User::where('email', $request->input('email'))->first();

        if (! $user) {
            return back()->withErrors(['email' => 'Adresse inconnue.']);
        }

        $password = str()->random(8);

        $user->password = Hash::make($password);
        $user->force_password_change = true;
        $user->save();

        Mail::to($user->email)->send(new PasswordResetMail($user, $password));

        return back()->with('status', 'Un nouveau mot de passe vous a été envoyé.');
    }

    // Affiche le formulaire de réinitialisation
    public function showResetForm(string $token)
    {
        return view('auth.reset-password', [
            'token' => $token,
            'email' => request('email'),
        ]);
    }

    // Traite la réinitialisation
    public function resetPassword(Request $request)
    {
        $request->validate([
            'token' => 'required',
            'email' => 'required|email',
            'password' => 'required|string|confirmed|min:8',
        ]);

        $status = Password::reset(
            $request->only('email', 'password', 'password_confirmation', 'token'),
            function ($user) use ($request) {
                $user->force_password_change = false;
                $user->password = $request->password;
                $user->setRememberToken(Str::random(60));
                $user->save();

                event(new PasswordReset($user));
            }
        );

        return $status === Password::PASSWORD_RESET
            ? redirect()->route('login')->with('success', __($status))
            : back()->withErrors(['email' => __($status)]);
    }
}
