<?php

declare(strict_types=1);

namespace app\admin\controller\user;

use Throwable;
use app\common\controller\Backend;
use app\admin\model\User as UserModel;
use Webman\Http\Request;
use support\Response;

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

    protected array $withJoinTable = ['userGroup'];
    protected array|string $preExcludeFields = ['last_login_time', 'login_failure', 'password', 'salt'];
    protected array|string $quickSearchField = ['username', 'nickname', 'id'];

    protected function initController(Request $request): ?Response
    {
        $this->model = new UserModel();
        return null;
    }

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

        if ($request->get('select') || $request->post('select')) {
            return $this->select($request);
        }

        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = $this->model
            ->withoutField('password,salt')
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($where)
            ->order($order)
            ->paginate($limit);

        return $this->success('', [
            'list' => $res->items(),
            'total' => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }

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

        if ($request->method() !== 'POST') {
            return $this->error(__('Parameter error'));
        }

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

        $passwd = $data['password'] ?? '';
        $data = $this->excludeFields($data);

        $result = false;
        $this->model->startTrans();
        try {
            if ($this->modelValidate) {
                $validateClass = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                if (class_exists($validateClass)) {
                    $validate = new $validateClass();
                    if ($this->modelSceneValidate) $validate->scene('add');
                    $validate->check($data);
                }
            }
            $result = $this->model->save($data);
            $this->model->commit();
            if ($passwd) {
                $this->model->resetPassword($this->model->id, $passwd);
            }
        } catch (Throwable $e) {
            $this->model->rollback();
            return $this->error($e->getMessage());
        }
        return $result !== false ? $this->success(__('Added successfully')) : $this->error(__('No rows were added'));
    }

    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'));
        }

        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds && !in_array($row[$this->dataLimitField], $dataLimitAdminIds)) {
            return $this->error(__('You have no permission'));
        }

        if ($request->method() === 'POST') {
            $data = $request->post();
            if (!$data) {
                return $this->error(__('Parameter %s can not be empty', ['']));
            }
            if (!empty($data['password'])) {
                $this->model->resetPassword($row->id, $data['password']);
            }
            $data = $this->excludeFields($data);
            $result = false;
            $this->model->startTrans();
            try {
                if ($this->modelValidate) {
                    $validateClass = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validateClass)) {
                        $validate = new $validateClass();
                        $validate->scene('edit')->check(array_merge($data, [$pk => $row[$pk]]));
                    }
                }
                $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'));
        }

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

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

        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = $this->model
            ->withoutField('password,salt')
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($where)
            ->order($order)
            ->paginate($limit);

        return $this->success('', [
            'list' => $res->items(),
            'total' => $res->total(),
        ]);
    }
}
