<?php

namespace App\Core\Auth\Controllers;

use App\Controllers\BaseController;
use App\Core\Audit\Services\AuditService;
use App\Core\Auth\Services\AuthService;

class AuthController extends BaseController
{
    public function login()
    {
        if ((new AuthService())->check()) {
            return redirect()->to('/dashboard');
        }

        return view('core/auth/login', ['title' => 'Connexion']);
    }

    public function attempt()
    {
        $rules = [
            'email' => 'required|valid_email',
            'password' => 'required|min_length[8]',
        ];

        if (! $this->validate($rules)) {
            return redirect()->back()->withInput()->with('error', 'Identifiants invalides.');
        }

        if (! (new AuthService())->attempt((string) $this->request->getPost('email'), (string) $this->request->getPost('password'))) {
            return redirect()->back()->withInput()->with('error', 'Email ou mot de passe incorrect.');
        }

        (new AuditService())->log('auth.login', 'user', (string) session('core_user_id'), 'Connexion utilisateur');

        return redirect()->to('/dashboard');
    }

    public function logout()
    {
        (new AuditService())->log('auth.logout', 'user', (string) session('core_user_id'), 'Déconnexion utilisateur');
        (new AuthService())->logout();

        return redirect()->to('/login');
    }
}
