<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Core\Auth;
use App\Core\Controller;
use App\Core\Csrf;
use App\Core\Session;
use App\Services\UtilisateurService;
use App\Services\ParametreSocieteService;
use Throwable;

final class AuthController extends Controller
{
    public function __construct(
        private readonly UtilisateurService $users =
            new UtilisateurService()
    ) {
    }

    public function login(): void
    {
        if (Auth::check()) {
            $this->redirect('dashboard');
        }

		
		$settings = (new ParametreSocieteService())->get();

		$this->view('auth/login', [
			'title' => 'Connexion — DARLINK-ERP',
			'layout' => 'auth',
			'error' => Session::flash('error'),
			'oldLogin' => Session::flash('old_login'),
			'expired' => isset($_GET['expired']),
			'settings' => $settings,
		]);
    }

    public function authenticate(): void
    {
        $login = trim(
            (string)($_POST['login'] ?? '')
        );

        $password = (string)(
            $_POST['password'] ?? ''
        );

        try {
            $this->users->authenticate(
                $login,
                $password
            );
            Csrf::rotate();

            Session::flash(
                'success',
                'Connexion réussie.'
            );

            $this->redirect('dashboard');
        } catch (Throwable $exception) {
            Session::flash(
                'error',
                $exception->getMessage()
            );

            Session::flash(
                'old_login',
                $login
            );

            $this->redirect('login');
        }
    }

    public function logout(): void
    {
        $this->users->logout();
        Csrf::rotate();

        Session::flash(
            'success',
            'Déconnexion effectuée.'
        );

        $this->redirect('login');
    }
}