<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use App\Models\User;

class AuthController extends Controller
{
    public function showLoginForm()
    {
        return view('auth.login');
    }

    public function login(Request $request)
    {
        $validated = $request->validate([
            'login' => ['required', 'string'],
            'password' => ['required', 'string'],
        ]);

        $loginValue = $validated['login'];
        $password = $validated['password'];

        $field = filter_var($loginValue, FILTER_VALIDATE_EMAIL) ? 'email' : 'name';

        if (Auth::attempt([$field => $loginValue, 'password' => $password])) {
            $request->session()->regenerate();
            return redirect()->intended(route('dashboard'));
        }

        return back()->withErrors([
            'login' => 'بيانات الدخول غير صحيحة.',
        ])->onlyInput('login');
    }

    public function showForgotPassword()
    {
        return view('auth.forgot');
    }

    public function processForgotPassword(Request $request)
    {
        $validated = $request->validate([
            'login' => ['required', 'string'],
        ]);

        $loginValue = $validated['login'];
        $field = filter_var($loginValue, FILTER_VALIDATE_EMAIL) ? 'email' : 'name';
        $user = User::where($field, $loginValue)->first();

        if (!$user) {
            return back()->withErrors(['login' => 'المستخدم غير موجود']).onlyInput('login');
        }

        $temporaryPassword = Str::random(10);
        $user->password = Hash::make($temporaryPassword);
        $user->save();

        return back()->with('reset_success', true)->with('temporary_password', $temporaryPassword);
    }

    public function logout(Request $request)
    {
        Auth::logout();
        $request->session()->invalidate();
        $request->session()->regenerateToken();
        return redirect()->route('login');
    }
}