<?php
namespace App\Controllers;

use CodeIgniter\HTTP\RedirectResponse;
use CodeIgniter\Controller;

class AuthController extends BaseController
{
    public function login()
    {
        // Redirect authenticated users away from login
        if (auth()->loggedIn()) {
            return redirect()->to('/dashboard');
        }

        $session = session();
        $locale = $this->request->getGet('lang');
        if ($locale) {
            $session->set('app_locale', $locale);
        }
        
        $currentLocale = $session->get('app_locale') ?? config('App')->defaultLocale;
        
        // Set the locale for the language helper
        service('language')->setLocale($currentLocale);
        
        return view('auth/login', [
            'title' => 'Login',
            'locale' => $currentLocale,
        ]);
    }

    public function attemptLogin(): RedirectResponse
    {
        // Prevent re-login when already authenticated
        if (auth()->loggedIn()) {
            return redirect()->back()->with('error', 'You are already logged in. Please logout before switching accounts.');
        }

        $login = $this->request->getPost('login');
        $password = $this->request->getPost('password');

        $validFields = config('Auth')->validFields ?? ['email'];

        $creds = ['password' => $password];
        // Prefer email if configured and input looks like an email
        if (in_array('email', $validFields, true) && filter_var($login, FILTER_VALIDATE_EMAIL)) {
            $creds['email'] = $login;
        } elseif (in_array('username', $validFields, true)) {
            $creds['username'] = $login;
        } else {
            // Fallback to first configured field
            $creds[$validFields[0]] = $login;
        }

        $result = auth()->attempt($creds);

        if (! $result->isOK()) {
            return redirect()->back()->with('error', $result->reason());
        }

        $user = auth()->user();
        // Role-based redirects
        if ($user && $user->inGroup('admin')) {
            return redirect()->to('/dashboard');
        }
        if ($user && $user->inGroup('student')) {
            return redirect()->to('/profile');
        }
        return redirect()->to('/dashboard');
    }

    public function logout(): RedirectResponse
    {
        auth()->logout();
        return redirect()->to('/login');
    }

    // Diagnostic: view valid login fields configured in Shield
    public function debugValidFields()
    {
        return $this->response->setJSON([
            'validFields' => config('Auth')->validFields ?? null,
        ]);
    }
}