<?php
declare(strict_types=1);

namespace Celena\Module\Users;

use Celena\Core\Database\Connection;
use Celena\Core\Http\Request;
use Celena\Core\Http\Response;
use Celena\Core\Security\Auth;
use Celena\Core\Security\Csrf;
use Celena\Core\Security\Filter;
use Celena\Core\Security\Password;
use Celena\Core\Template\Engine;
use Celena\Module\AdminBase\AdminController;
use Celena\Module\Settings\Options;

/**
 * Профиль текущего пользователя (любая роль). Изменение имени, email, пароля и локали.
 */
final class ProfileController extends AdminController
{
    public function __construct(
        Engine $engine,
        Auth $auth,
        Options $options,
        private readonly Connection $conn,
    ) {
        parent::__construct($engine, $auth, $options);
    }

    public function index(Request $request): Response
    {
        $user = $this->auth->user();
        if ($user === null) {
            return Response::redirect('/admin/login');
        }
        return $this->view('admin/profile/index', [
            'profile' => $user,
        ], 'profile', 'Мой профиль');
    }

    public function save(Request $request): Response
    {
        $user = $this->auth->user();
        if ($user === null) {
            return Response::redirect('/admin/login');
        }
        if (!Csrf::validate((string) $request->input('_csrf'))) {
            return $this->redirect('/admin/profile', 'CSRF.', 'error');
        }
        $id = (int) $user['id'];
        $name = Filter::string($request->input('name'), 191);
        $email = Filter::email($request->input('email'));
        $locale = Filter::in($request->input('locale'), ['ru', 'en'], (string) $user['locale']);
        $currentPass = (string) $request->input('current_password', '');
        $newPass = (string) $request->input('new_password', '');

        if ($name === '' || $email === null) {
            return $this->redirect('/admin/profile', 'Проверьте имя и email.', 'error');
        }
        // Email занят другим пользователем?
        $other = $this->conn->builder('celena_users')
            ->where('email', '=', $email)
            ->where('id', '!=', $id)
            ->first();
        if ($other !== null) {
            return $this->redirect('/admin/profile', 'Этот email уже занят.', 'error');
        }

        $data = [
            'name' => $name,
            'email' => $email,
            'locale' => $locale,
            'updated_at' => date('Y-m-d H:i:s'),
        ];

        if ($newPass !== '') {
            if (!Password::verify($currentPass, (string) $user['password_hash'])) {
                return $this->redirect('/admin/profile', 'Неверный текущий пароль.', 'error');
            }
            if (strlen($newPass) < 8) {
                return $this->redirect('/admin/profile', 'Новый пароль от 8 символов.', 'error');
            }
            $data['password_hash'] = Password::hash($newPass);
        }
        $this->conn->builder('celena_users')->where('id', '=', $id)->update($data);
        return $this->redirect('/admin/profile', 'Сохранено.');
    }
}
