<?php
declare(strict_types=1);

namespace App\Modules\Users;

use App\Core\Http\Request;
use App\Core\Http\Response;
use App\Core\I18n\Translator;
use App\Core\Security\Csrf;
use App\Core\Support\Flash;
use App\Core\View\Template;
use App\Modules\Auth\AuthService;

final class UsersController
{
    public function __construct(
        private readonly Template $template,
        private readonly Translator $translator,
        private readonly AuthService $auth,
        private readonly UserRepository $users
    ) {
    }

    public function index(Request $request): Response
    {
        $filters = [
            'search' => trim((string) $request->input('search', '')),
            'sort' => (string) $request->input('sort', 'id'),
            'sort_dir' => (string) $request->input('sort_dir', 'DESC'),
            'page' => max(1, (int) $request->input('page', 1)),
            'per_page' => max(1, min(100, (int) $request->input('per_page', 20))),
        ];
        $result = $this->users->paginate($filters);
        $totalPages = max(1, (int) ceil(((int) $result['total']) / max(1, (int) $result['per_page'])));

        $html = $this->template->render('users/index', [
            'title' => $this->translator->get('users.title'),
            'activeMenu' => 'settings',
            'activeSettings' => 'users',
            'user' => $this->auth->user(),
            'csrfToken' => Csrf::token(),
            'tableList' => [
                'list_key' => 'users',
                'base_path' => '/settings/users',
                'query' => $filters,
                'filters' => [
                    [
                        'key' => 'search',
                        'label' => $this->translator->get('users.filters.search'),
                        'type' => 'text',
                        'value' => $filters['search'],
                    ],
                ],
                'columns' => [
                    ['key' => 'id', 'label' => 'ID', 'sortable' => true, 'sort_key' => 'id'],
                    ['key' => 'name', 'label' => $this->translator->get('users.fields.name'), 'sortable' => true, 'sort_key' => 'name'],
                    ['key' => 'email', 'label' => $this->translator->get('users.fields.email'), 'sortable' => true, 'sort_key' => 'email'],
                    ['key' => 'created_at', 'label' => $this->translator->get('users.fields.created_at'), 'sortable' => true, 'sort_key' => 'created_at'],
                ],
                'rows' => (array) ($result['items'] ?? []),
                'pagination' => [
                    'page' => (int) ($result['page'] ?? 1),
                    'total_pages' => $totalPages,
                    'total' => (int) ($result['total'] ?? 0),
                    'per_page' => (int) ($result['per_page'] ?? 20),
                ],
                'per_page_options' => [10, 20, 50, 100],
                'empty_message' => $this->translator->get('users.empty'),
                'show_actions' => false,
            ],
            'errorMessage' => (string) Flash::get('users_error', ''),
            'successMessage' => (string) Flash::get('users_success', ''),
            'oldName' => (string) Flash::get('users_old_name', ''),
            'oldEmail' => (string) Flash::get('users_old_email', ''),
        ], 'layouts/app');

        return Response::html($html);
    }

    public function store(Request $request): Response
    {
        $csrfToken = (string) $request->input('_token', '');
        if (!Csrf::validate($csrfToken)) {
            Flash::set('users_error', $this->translator->get('auth.errors.csrf_expired'));
            return Response::redirect('/settings/users');
        }

        $name = trim((string) $request->input('name', ''));
        $email = strtolower(trim((string) $request->input('email', '')));
        $password = (string) $request->input('password', '');

        Flash::set('users_old_name', $name);
        Flash::set('users_old_email', $email);

        if (mb_strlen($name) < 2) {
            Flash::set('users_error', $this->translator->get('users.validation.name_min'));
            return Response::redirect('/settings/users');
        }

        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            Flash::set('users_error', $this->translator->get('users.validation.email_invalid'));
            return Response::redirect('/settings/users');
        }

        if (strlen($password) < 8) {
            Flash::set('users_error', $this->translator->get('users.validation.password_min'));
            return Response::redirect('/settings/users');
        }

        if ($this->users->findByEmail($email) !== null) {
            Flash::set('users_error', $this->translator->get('users.validation.email_taken'));
            return Response::redirect('/settings/users');
        }

        $passwordHash = password_hash($password, PASSWORD_DEFAULT);
        $this->users->create($name, $email, $passwordHash);

        Flash::set('users_success', $this->translator->get('users.flash.created'));
        Flash::set('users_old_name', '');
        Flash::set('users_old_email', '');

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