<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

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

    public function login(Request $request)
    {
        $credentials = $request->validate([
            'username' => ['required', 'string', 'max:255'],
            'password' => ['required', 'string'],
        ]);

        $username = trim((string) $credentials['username']);
        $password = (string) $credentials['password'];

        $user = DB::table('dm_user')
            ->where('is_active', 1)
            ->whereRaw('LOWER(username) = ?', [mb_strtolower($username)])
            ->first();

        $role = $this->normalizeRole((string) ($user->roll ?? ''));
        $allowedRoles = ['admin', 'superadmin', 'coordinadores', 'secretarias', 'docentes'];

        if (
            ! $user
            || ! $this->verifyLegacyPassword($password, (string) ($user->password ?? ''), (string) ($user->salt ?? ''), (string) ($user->algorithm ?? 'sha1'))
            || ! in_array($role, $allowedRoles, true)
        ) {
            return back()->withErrors([
                'username' => 'Credenciales incorrectas.',
            ])->onlyInput('username');
        }

        $request->session()->regenerate();
        $request->session()->put('admin_auth', true);
        $request->session()->put('admin_user_id', (int) $user->id);
        $request->session()->put('admin_username', (string) $user->username);
        $request->session()->put('admin_email', (string) ($user->email ?: $user->username));
        $request->session()->put('admin_role', $role);

        $displayName = trim((string) (($user->nombres ?? '') . ' ' . ($user->apellido1 ?? '') . ' ' . ($user->apellido2 ?? '')));
        if ($displayName !== '') {
            $request->session()->put('admin_display_name', $displayName);
        }

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

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

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

    private function verifyLegacyPassword(string $plain, string $storedHash, string $salt = '', string $algorithm = 'sha1'): bool
    {
        if ($storedHash === '') {
            return false;
        }

        $stored = mb_strtolower(trim($storedHash));
        $algo = mb_strtolower(trim($algorithm));

        if ($algo === 'bcrypt' || str_starts_with($storedHash, '$2y$') || str_starts_with($storedHash, '$2a$') || str_starts_with($storedHash, '$2b$')) {
            return password_verify($plain, $storedHash);
        }

        $candidates = [
            $plain,
            sha1($plain),
            md5($plain),
            sha1(md5($plain)),
            md5(sha1($plain)),
        ];

        if ($salt !== '') {
            $candidates[] = sha1($salt . $plain);
            $candidates[] = sha1($plain . $salt);
            $candidates[] = sha1($salt . sha1($plain));
            $candidates[] = sha1(sha1($plain) . $salt);
            $candidates[] = md5($salt . $plain);
            $candidates[] = md5($plain . $salt);
        }

        foreach ($candidates as $candidate) {
            if (mb_strtolower((string) $candidate) === $stored) {
                return true;
            }
        }

        return false;
    }

    private function normalizeRole(string $value): string
    {
        return Str::lower(trim(str_replace(["\r", "\n"], '', $value)));
    }
}
