<?php

namespace App\Http\Controllers;

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

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

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

        $user = User::where('email', $credentials['email'])->first();

        if ($user) {
            if ($user->is_blocked) {
                return back()->withErrors([
                    'email' => 'Votre compte a été bloqué. Veuillez contacter l\'administrateur.',
                ])->onlyInput('email');
            }

            // Check if password is MD5 (32 chars hex)
            if (strlen($user->password) === 32 && ctype_xdigit($user->password)) {
                // Verify MD5
                if (md5($credentials['password']) === $user->password) {
                    // Update to Bcrypt
                    $user->password = Hash::make($credentials['password']);
                    $user->save();
                    
                    Auth::login($user);
                    
                    $user->is_connected = true;
                    $user->save();
                    
                    if ($user->role === 'admin' || $user->role === 'staff') {
                        return redirect()->route('admin.dashboard');
                    }
                    return redirect()->intended('/');
                }
            }
            
            // Standard Laravel Auth check (Bcrypt)
            if (Auth::attempt($credentials)) {
                $request->session()->regenerate();
                $user->is_connected = true;
                $user->save();
                
                if (auth()->user()->role === 'admin' || auth()->user()->role === 'staff') {
                    return redirect()->route('admin.dashboard');
                }
                return redirect()->intended('/');
            }
        }

        return back()->withErrors([
            'email' => 'Les identifiants fournis ne correspondent pas à nos enregistrements.',
        ])->onlyInput('email');
    }

    public function showRegistrationForm()
    {
        return view('auth.register');
    }

    public function register(Request $request)
    {
        $request->validate([
            'nom' => ['required', 'string', 'max:255'],
            'prenom' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users', 'ends_with:@gmail.com'],
            'password' => ['required', 'string', 'min:8', 'confirmed'],
            'telephone' => ['nullable', 'string', 'digits:10'],
            'adresse' => ['nullable', 'string', 'max:500'],
        ]);

        $user = User::create([
            'nom' => $request->nom,
            'prenom' => $request->prenom,
            'email' => $request->email,
            'password' => Hash::make($request->password),
            'telephone' => $request->telephone,
            'adresse' => $request->adresse,
            'role' => 'client',
        ]);

        Auth::login($user);

        return redirect('/')->with('success', 'Votre compte a été créé avec succès !');
    }

    public function logout(Request $request)
    {
        $user = Auth::user();
        if ($user) {
            $user->is_connected = false;
            $user->save();
        }
        
        Auth::logout();
        $request->session()->invalidate();
        $request->session()->regenerateToken();
        return redirect('/');
    }
}
