<?php

namespace App\Http\Controllers;

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

class AuthController extends Controller
{
    public function showRegister()
    {
        return view('register');
    }

    public function register(Request $request)
    {
        $request->validate([
            'name' => 'required',
            'email' => 'required|email|unique:users',
            'password' => 'required|confirmed',
            'role' => 'required|in:vendedor,administrador',
        ]);

        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'role' => $request->role,
            'password' => Hash::make($request->password),
        ]);

        Auth::login($user);

        return redirect()->route('productos.index');
    }

    public function showLogin()
    {
        // Pasa todos los usuarios a la vista para la lista desplegable
        $usuarios = User::all();
        return view('login', compact('usuarios'));
    }

    public function login(Request $request)
    {
        // Validar que se seleccione usuario y contraseña
        $request->validate([
            'user_id' => 'required|exists:users,id',
            'password' => 'required',
        ]);

        // Buscar el usuario por id
        $user = User::find($request->user_id);

        if ($user && Hash::check($request->password, $user->password)) {
            Auth::login($user);
            return redirect()->route('productos.index');
        }

        return back()->withErrors([
            'user_id' => 'Usuario o contraseña incorrectos.',
        ]);
    }

    public function logout()
    {
        Auth::logout();
        return redirect('/login');
    }
}