<?php

declare(strict_types=1);

namespace app\admin\controller\routine;

use app\admin\model\Admin;
use app\common\controller\Backend;
use Webman\Http\Request;
use support\Response;

class AdminInfo extends Backend
{
    protected ?object $model = null;

    protected array|string $preExcludeFields = ['username', 'last_login_time', 'password', 'salt', 'status', 'channel_id', 'totp_secret', 'totp_bind_time'];
    protected array $authAllowFields = ['id', 'username', 'nickname', 'avatar', 'email', 'mobile', 'motto', 'last_login_time', 'totp_bound'];

    protected function initController(Request $request): ?Response
    {
        $this->auth->setAllowFields($this->authAllowFields);
        $this->model = $this->auth->getAdmin();
        return null;
    }

    public function index(Request $request): Response
    {
        $response = $this->initializeBackend($request);
        if ($response !== null) return $response;

        $info = $this->auth->getInfo();
        return $this->success('', ['info' => $info]);
    }

    public function edit(Request $request): Response
    {
        $response = $this->initializeBackend($request);
        if ($response !== null) return $response;

        $pk = $this->model->getPk();
        $id = $request->post($pk) ?? $request->get($pk);
        $row = $this->model->find($id);
        if (!$row) {
            return $this->error(__('Record not found'));
        }

        if ($request->method() === 'POST') {
            $data = $request->post();
            if (!$data) {
                return $this->error(__('Parameter %s can not be empty', ['']));
            }

            if (!empty($data['avatar'])) {
                $row->avatar = $data['avatar'];
                if ($row->save()) {
                    return $this->success(__('Avatar modified successfully!'));
                }
            }

            if ($this->modelValidate) {
                $validateClass = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                if (class_exists($validateClass)) {
                    try {
                        $validate = new $validateClass();
                        $validate->scene('info')->check($data);
                    } catch (\Throwable $e) {
                        return $this->error($e->getMessage());
                    }
                }
            }

            if (!empty($data['password'])) {
                $this->model->resetPassword($this->auth->id, $data['password']);
            }

            $data = $this->excludeFields($data);
            $result = false;
            $this->model->startTrans();
            try {
                $result = $row->save($data);
                $this->model->commit();
            } catch (\Throwable $e) {
                $this->model->rollback();
                return $this->error($e->getMessage());
            }
            return $result !== false ? $this->success(__('Update successful')) : $this->error(__('No rows updated'));
        }

        return $this->success('', ['row' => $row]);
    }
}
