<?php

namespace App\Controllers;

use App\Models\UserModel;
use CodeIgniter\HTTP\RedirectResponse;

class AuthController extends BaseController
{
    public function index(): string|RedirectResponse
    {
        if ($this->session->has('auth_user')) {
            return redirect()->to(site_url('dashboard'));
        }

        return view('auth/login', [
            'title' => 'Iniciar sesión',
        ]);
    }

    public function login(): RedirectResponse
    {
        $rules = [
            'email'    => 'required|valid_email',
            'password' => 'required',
        ];

        if (! $this->validate($rules)) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

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

        // 1) Intentar autenticación contra la tabla de usuarios.
        $user = (new UserModel())
            ->where('email', $email)
            ->where('is_active', 1)
            ->first();

        if ($user !== null && password_verify($password, $user['password_hash'])) {
            return $this->authenticateAs(
                $user['id'],
                $user['full_name'],
                $user['email']
            );
        }

        // 2) Fallback: credenciales definidas en .env (útil antes de correr el
        //    seeder o en despliegues donde la tabla users está vacía).
        $envEmail    = (string) env('AUTH_ADMIN_EMAIL', '');
        $envPassword = (string) env('AUTH_ADMIN_PASSWORD', '');

        if ($envEmail !== '' && $envPassword !== ''
            && $email === $envEmail && $password === $envPassword
        ) {
            return $this->authenticateAs(0, 'Administrador', $envEmail);
        }

        return redirect()->back()->withInput()->with('error', 'Credenciales inválidas.');
    }

    private function authenticateAs(int|string $id, string $name, string $email): RedirectResponse
    {
        $this->session->regenerate();
        $this->session->set('auth_user', [
            'id'    => $id,
            'name'  => $name,
            'email' => $email,
        ]);

        return redirect()->to(site_url('dashboard'))->with('success', 'Bienvenido de nuevo.');
    }

    public function logout(): RedirectResponse
    {
        $this->session->destroy();

        return redirect()->to(site_url('login'))->with('success', 'Sesión cerrada correctamente.');
    }
}
