<?php

declare(strict_types=1);

namespace app\admin\controller\security;

use app\common\controller\Backend;
use app\admin\model\SensitiveData as SensitiveDataModel;
use Webman\Http\Request;
use support\Response;

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

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

    protected function initController(Request $request): ?Response
    {
        $this->model = new SensitiveDataModel();
        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)
            ->alias($alias)
            ->where($where)
            ->order($order)
            ->paginate($limit);

        $items = $res->items();
        foreach ($items as $item) {
            if ($item->data_fields) {
                $fields = [];
                foreach ($item->data_fields as $key => $field) {
                    $fields[] = $field ?: $key;
                }
                $item->data_fields = $fields;
            }
        }

        return $this->success('', [
            'list' => $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->success('', ['controllers' => $this->getControllerList()]);
        }

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

        if (is_array($data['fields'] ?? null)) {
            $data['data_fields'] = [];
            foreach ($data['fields'] as $field) {
                $data['data_fields'][$field['name']] = $field['value'];
            }
        }

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

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

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

        if ($request->method() !== 'POST') {
            return $this->success('', [
                'row' => $row,
                'controllers' => $this->getControllerList(),
            ]);
        }

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

        if (is_array($data['fields'] ?? null)) {
            $data['data_fields'] = [];
            foreach ($data['fields'] as $field) {
                $data['data_fields'][$field['name']] = $field['value'];
            }
        }

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

    private function getControllerList(): array
    {
        $outExcludeController = [
            'Addon.php',
            'Ajax.php',
            'Dashboard.php',
            'Index.php',
            'Module.php',
            'Terminal.php',
            'auth/AdminLog.php',
            'routine/AdminInfo.php',
            'routine/Config.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;
    }
}
