<?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\SensitiveDataLog as SensitiveDataLogModel;
use Webman\Http\Request;
use support\Response;

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

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

    protected function initController(Request $request): ?Response
    {
        $this->model = new SensitiveDataLogModel();
        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) {
            $item->id_value = $item['primary_key'] . '=' . $item->id_value;
        }

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

    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('security_sensitive_data_log.id', $id)
            ->find();
        if (!$row) {
            return $this->error(__('Record not found'));
        }
        return $this->success('', ['row' => $row]);
    }

    public function rollback(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) {
                $conn = Db::connect(TableManager::getConnection($row->connection));
                if ($conn->name($row->data_table)->where($row->primary_key, $row->id_value)->update([$row->data_field => $row->before])) {
                    $count++;
                }
            }
            $this->model->commit();
        } catch (\Throwable $e) {
            $this->model->rollback();
            return $this->error($e->getMessage());
        }
        return $count ? $this->success(__('Rollback successful')) : $this->error(__('No rows were rolled back'));
    }
}
