<?php

declare(strict_types=1);

namespace app\admin\controller\security;

use ba\TableManager;
use support\think\Db;
use app\common\controller\Backend;
use app\admin\model\DataRecycleLog as DataRecycleLogModel;
use Webman\Http\Request;
use support\Response;

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

    protected array|string $preExcludeFields = [];
    protected array|string $quickSearchField = 'recycle.name';
    protected array $withJoinTable = ['recycle', 'admin'];

    protected function initController(Request $request): ?Response
    {
        $this->model = new DataRecycleLogModel();
        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);

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

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

        $ids = $request->post('ids', $request->get('ids', []));
        $ids = is_array($ids) ? $ids : [];
        $data = $this->model->where('id', 'in', $ids)->select();
        if (!$data) {
            return $this->error(__('Record not found'));
        }

        $count = 0;
        $this->model->startTrans();
        try {
            foreach ($data as $row) {
                $recycleData = json_decode($row['data'], true);
                if (is_array($recycleData) && Db::connect(TableManager::getConnection($row->connection))->name($row->data_table)->insert($recycleData)) {
                    $row->delete();
                    $count++;
                }
            }
            $this->model->commit();
        } catch (\Throwable $e) {
            $this->model->rollback();
            return $this->error($e->getMessage());
        }

        return $count ? $this->success(__('Restore successful')) : $this->error(__('No rows were restore'));
    }

    public function info(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
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->where('data_recycle_log.id', $id)
            ->find();
        if (!$row) {
            return $this->error(__('Record not found'));
        }
        $data = $this->jsonToArray($row['data']);
        if (is_array($data)) {
            foreach ($data as $key => $item) {
                $data[$key] = $this->jsonToArray($item);
            }
        }
        $row['data'] = $data;

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

    protected function jsonToArray(mixed $value = ''): mixed
    {
        if (!is_string($value)) {
            return $value;
        }
        $data = json_decode($value, true);
        if (($data && is_object($data)) || (is_array($data) && !empty($data))) {
            return $data;
        }
        return $value;
    }
}
