<?php

namespace App\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Core\Session;
use App\Models\User;

class AuthController extends Controller
{
    private User $userModel;

    public function __construct()
    {
        $this->userModel = new User();
    }

    public function showLogin(Request $request): Response
    {
        return $this->render('auth.login');
    }

    public function login(Request $request): Response
    {
        $email = $request->post('email', '');
        $password = $request->post('password', '');

        $user = $this->userModel->findByEmail($email);

        if (!$user || !password_verify($password, $user['password'])) {
            Session::flash('error', \App\Helpers\Lang::t('invalid_credentials'));
            return Response::redirect('/login');
        }

        if ($user['role_id'] == 0) {
            Session::flash('error', \App\Helpers\Lang::t('account_banned'));
            return Response::redirect('/login');
        }

        Session::set('user_id', $user['id']);
        Session::set('username', $user['username']);
        Session::set('role', $user['role_id']);

        return Response::redirect('/');
    }

    public function showRegister(Request $request): Response
    {
        return $this->render('auth.register');
    }

    public function register(Request $request): Response
    {
        $username = trim($request->post('username', ''));
        $email = trim($request->post('email', ''));
        $password = $request->post('password', '');
        $confirm = $request->post('password_confirm', '');

        if (empty($username) || empty($email) || empty($password)) {
            Session::flash('error', \App\Helpers\Lang::t('fill_all_fields'));
            return Response::redirect('/register');
        }

        if ($password !== $confirm) {
            Session::flash('error', \App\Helpers\Lang::t('passwords_dont_match'));
            return Response::redirect('/register');
        }

        if (strlen($password) < 6) {
            Session::flash('error', \App\Helpers\Lang::t('password_too_short'));
            return Response::redirect('/register');
        }

        if ($this->userModel->findByEmail($email) || $this->userModel->findByUsername($username)) {
            Session::flash('error', \App\Helpers\Lang::t('user_already_exists'));
            return Response::redirect('/register');
        }

        $userId = $this->userModel->create([
            'username' => $username,
            'email' => $email,
            'password' => password_hash($password, PASSWORD_DEFAULT),
        ]);

        Session::set('user_id', $userId);
        Session::set('username', $username);
        Session::set('role', 1);

        return Response::redirect('/');
    }

    public function logout(Request $request): Response
    {
        \App\Core\CSRF::reset();
        Session::destroy();
        return Response::redirect('/');
    }
}
