<?php

declare(strict_types=1);

namespace app\admin\controller\routine;

use app\common\controller\Backend;
use app\common\model\Attachment as AttachmentModel;
use Webman\Http\Request;
use support\Response;

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

    protected array|string $quickSearchField = 'name';
    protected array $withJoinTable = ['admin'];
    protected array|string $defaultSortField = ['last_upload_time' => 'desc'];

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

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

        $where = [];
        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds) {
            $where[] = [$this->dataLimitField, 'in', $dataLimitAdminIds];
        }

        $ids = $request->post('ids', $request->get('ids', []));
        $ids = is_array($ids) ? $ids : [];
        $where[] = [$this->model->getPk(), 'in', $ids];
        $data = $this->model->where($where)->select();

        $count = 0;
        try {
            foreach ($data as $v) {
                $count += $v->delete();
            }
        } catch (\Throwable $e) {
            return $this->error(__('%d records and files have been deleted', [$count]) . $e->getMessage());
        }
        return $count ? $this->success(__('%d records and files have been deleted', [$count])) : $this->error(__('No rows were deleted'));
    }
}
