<?php
declare(strict_types=1);

/**
 * 用户自己改资料：只能改邮箱/手机号/密码，其它字段（用户名/姓名/部门/允许状态）不允许自己改，
 * 那些只能在后台用户管理（admin/action/users.php 的 grid）里由管理员改
 */
class profileAction extends Action
{
    private function gridModel(): Users
    {
        return new Users();
    }

    /**
     * 系统内置超级管理员（不入库）没有资料可改
     */
    private function isSuperAdmin(): bool
    {
        return Auth::id() === 0;
    }

    public function index(): void
    {
        $admin = $this->isSuperAdmin() ? null : $this->gridModel()->findByUsername(Auth::user()['admin_username']);

        View::set([
            'pageTitle'      => lg('修改资料'),
            'isSuperAdmin'   => $this->isSuperAdmin(),
            'admin'          => $admin,
            'passwordExpired' => !empty($this->request['passwordExpired']),
        ]);
        View::put();
    }

    /**
     * 提交资料修改，请求体: { email, mobile, password?, passwordConfirm? }
     * password 不填就只改 email/mobile，不动密码
     */
    public function update(): void
    {
        if ($this->isSuperAdmin()) {
            $this->error(1, lg('系统内置账号不支持修改资料'));
        }

        $email = trim((string) ($this->request['email'] ?? ''));
        $mobile = trim((string) ($this->request['mobile'] ?? ''));
        $password = (string) ($this->request['password'] ?? '');
        $passwordConfirm = (string) ($this->request['passwordConfirm'] ?? '');

        if ($email !== '' && !filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $this->error(2, lg('邮箱格式不正确'));
        }

        $adminId = Auth::id();
        $model = $this->gridModel();
        $model->updateProfile($adminId, $email, $mobile);

        if ($password !== '') {
            if ($password !== $passwordConfirm) {
                $this->error(3, lg('两次输入的密码不一致'));
            }
            if (!PasswordPolicy::isValid($password)) {
                $this->error(4, lg('密码必须大于8位，且包含大写字母、小写字母、数字、特殊符号'));
            }
            $model->updatePasswordById($adminId, $password);
        }

        $this->success();
    }
}
