<?php

namespace App\Http\Controllers;

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

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

    public function login(Request $request)
    {
        $validated = $request->validate([
            'login_code' => ['required', 'string', 'max:30'],
            'pin' => ['required', 'string', 'min:4', 'max:12'],
        ]);

        $student = Student::query()->where('login_code', $validated['login_code'])->first();

        if (! $student || ! Hash::check($validated['pin'], $student->login_pin_hash)) {
            return back()->withErrors(['login_code' => 'Credenciales inválidas.'])->onlyInput('login_code');
        }

        $request->session()->regenerate();
        $request->session()->put('student_id', $student->id);

        return redirect()->route('voting.form');
    }

    public function logout(Request $request)
    {
        $request->session()->forget('student_id');
        $request->session()->invalidate();
        $request->session()->regenerateToken();

        return redirect()->route('login.form');
    }

    public function showAdminLogin()
    {
        if (! User::query()->where('role', 'admin')->exists()) {
            return redirect()->route('setup.initial.form');
        }

        return view('auth.admin-login');
    }

    public function showInitialSetup()
    {
        if (User::query()->where('role', 'admin')->exists()) {
            return redirect()->route('admin.login.form');
        }

        return view('auth.initial-setup');
    }

    public function initialSetup(Request $request)
    {
        if (User::query()->where('role', 'admin')->exists()) {
            return redirect()->route('admin.login.form');
        }

        $validated = $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'email', 'max:255', 'unique:users,email'],
            'password' => ['required', 'string', 'min:8', 'confirmed'],
        ]);

        $admin = User::query()->create([
            'name' => $validated['name'],
            'email' => $validated['email'],
            'password' => $validated['password'],
            'role' => 'admin',
            'is_active' => true,
        ]);

        $request->session()->regenerate();
        $request->session()->put('admin_user_id', $admin->id);

        return redirect()->route('admin.dashboard')->with('status', 'Administrador inicial creado correctamente.');
    }

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

        $admin = User::query()->where('email', $validated['email'])->where('role', 'admin')->where('is_active', true)->first();

        if (! $admin || ! Hash::check($validated['password'], $admin->password)) {
            return back()->withErrors(['email' => 'Credenciales de administrador inválidas.']);
        }

        $request->session()->regenerate();
        $request->session()->put('admin_user_id', $admin->id);

        return redirect()->route('admin.dashboard');
    }

    public function adminLogout(Request $request)
    {
        $request->session()->forget('admin_user_id');
        $request->session()->invalidate();
        $request->session()->regenerateToken();

        return redirect()->route('admin.login.form');
    }

    public function showJuryLogin()
    {
        return view('auth.jury-login');
    }

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

        $jury = User::query()->where('email', $validated['email'])->where('role', 'jury')->where('is_active', true)->first();

        if (! $jury || ! Hash::check($validated['password'], $jury->password)) {
            return back()->withErrors(['email' => 'Credenciales de jurado inválidas.']);
        }

        $request->session()->regenerate();
        $request->session()->put('jury_user_id', $jury->id);

        return redirect()->route('jury.dashboard');
    }

    public function juryLogout(Request $request)
    {
        $request->session()->forget('jury_user_id');
        $request->session()->invalidate();
        $request->session()->regenerateToken();

        return redirect()->route('jury.login.form');
    }
}
