<?php

class PancekKonsepSistemPencegahanController extends BaseController
{
    public function list()
    {
        $getParams = $this->request->get();
        $getParams['keyword'] = array_key_exists('keyword', $getParams) ? $getParams['keyword'] : '';
        $getParams['limit'] = $this->getDefaultLimit($getParams);
        $getParams['offset'] = array_key_exists('offset', $getParams) ? $getParams['offset'] : 0;

        $params = $this->validate(
            $getParams,
            [
                'limit' => ['validators' => ['digit']],
                'offset' => ['validators' => ['digit']],
                'keyword' => ['validators' => []]
            ]
        );

        $conditions = "label ilike :keyword: AND deleted_at IS NULL";
        $bind = [
            'keyword' => '%' . $params['keyword'] . '%'
        ];
        $records = PancekKonsepSistemPencegahan::find([
            'conditions' => $conditions,
            'bind' => $bind,
            'limit' => $params['limit'],
            'offset' => $params['offset'],
            'order' => 'view_order, formulir_type ASC'
        ]);

        $total = PancekKonsepSistemPencegahan::count([
            'conditions' => $conditions,
            'bind' => $bind
        ]);

        return new PaginatedResponse($records, $total, $params['limit'], $params['offset']);
    }

    public function detail($id)
    {
        /** @var $record PancekKonsepSistemPencegahan */
        $record = PancekKonsepSistemPencegahan::findFirst($id);
        if (!$record) {
            throw new CustomErrorException(BaseResponse::INVALID_REQUEST, 'Konsep Sistem Pencegahan [#' . $id . '] tidak ditemukan');
        }

        return new SimpleResponse($record->toDetail());
    }

    public function update($id)
    {
        $this->checkOneOfScopes(['admin.view','pancek.admin']);
        /** @var $data PancekKonsepSistemPencegahan */
        $data = PancekKonsepSistemPencegahan::findFirst(['conditions' => 'id = :id:', 'bind' => ['id' => $id]]);
        if (!$data) throw new CustomErrorException(BaseResponse::DATA_NOT_FOUND, "Konsep Sistem Pencegahan tidak ditemukan");

        $params = $this->validatePost();
        $data->code = $params['code'];
        $data->label = $params['label'];
        $data->label_en = $params['label_en'];
        $data->view_order = $params['view_order'];
        $data->formulir_type = $params['formulir_type'];
        $data->updated_at = DateHelper::getNowTimezoned();
        if (!$data->save()) {
            $errors = $data->getMessages();
            $error_messages = [];

            foreach ($errors as $key => $error) {
                $error_messages[] = ["field" => $error->getField(), "message" => $error->getMessage()];
            }

            throw new ValidationException($error_messages);
        }

        return new SimpleResponse($data);
    }

    private function validatePost()
    {
        $rawBody = $this->request->getJsonRawBody(true);
        return $this->validate($rawBody, [
            'code' => ['validators' => [
                'required',
                [
                    'name' => 'max_string',
                    'params' => 30
                ]
            ]],
            'label' => ['validators' => [
                'required',
                [
                    'name' => 'max_string',
                    'params' => 255
                ]
            ]],
            'label_en' => ['validators' => [
                'required',
                [
                    'name' => 'max_string',
                    'params' => 255
                ]
            ]],
            'view_order' => ['validators' => [
                'required',
                'digit'
            ]],
            "formulir_type" => ['validators' => ['required', [
                'name' => 'inclusion_in',
                'params' => PancekJenisInstansi::TIPE_FORMULIR
            ]]]
        ]);
    }
}
