<?php

declare(strict_types=1);

namespace app\admin\controller\security;

use app\common\controller\Backend;
use app\admin\model\DataRecycle as DataRecycleModel;
use Webman\Http\Request;
use support\Response;

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

    protected array|string $preExcludeFields = ['update_time', 'create_time'];
    protected array|string $quickSearchField = 'name';

    protected function initController(Request $request): ?Response
    {
        $this->model = new DataRecycleModel();
        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
            ->withJoin($this->withJoinTable ?? [], $this->withJoinType ?? 'LEFT')
            ->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') {
            $data = $request->post();
            if (!$data) {
                return $this->error(__('Parameter %s can not be empty', ['']));
            }
            $data = $this->excludeFields($data);
            $data['controller_as'] = str_ireplace('.php', '', $data['controller'] ?? '');
            $data['controller_as'] = strtolower(str_ireplace(['\\', '.'], '/', $data['controller_as']));

            $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('add')->check($data);
                    }
                }
                $result = $this->model->save($data);
                $this->model->commit();
            } catch (\Throwable $e) {
                $this->model->rollback();
                return $this->error($e->getMessage());
            }
            return $result !== false ? $this->success(__('Added successfully')) : $this->error(__('No rows were added'));
        }

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

    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', ['']));
            }
            $data = $this->excludeFields($data);
            $data['controller_as'] = str_ireplace('.php', '', $data['controller'] ?? '');
            $data['controller_as'] = strtolower(str_ireplace(['\\', '.'], '/', $data['controller_as']));

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

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

    private function getControllerList(): array
    {
        $outExcludeController = [
            'Addon.php',
            'Ajax.php',
            'Module.php',
            'Terminal.php',
            'Dashboard.php',
            'Index.php',
            'routine/AdminInfo.php',
            'user/MoneyLog.php',
            'user/ScoreLog.php',
        ];
        $outControllers = [];
        $controllers = get_controller_list();
        foreach ($controllers as $key => $controller) {
            if (!in_array($controller, $outExcludeController)) {
                $outControllers[$key] = $controller;
            }
        }
        return $outControllers;
    }
}
