<?php

class PancekIndikatorController extends BaseController
{
    public function list()
    {
        $getParams = $this->request->get();

        $getParams['konsep_sistem_pencegahan_id'] = array_key_exists('konsep_sistem_pencegahan_id', $getParams) ? $getParams['konsep_sistem_pencegahan_id'] : null;
        $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,
            [
                'konsep_sistem_pencegahan_id' => ['validators' => ['digit']],
                'limit' => ['validators' => ['digit']],
                'offset' => ['validators' => ['digit']],
                'keyword' => ['validators' => []]
            ]
        );

        $conditions = "PancekIndikator.label ilike :keyword: AND PancekIndikator.deleted_at IS NULL";
        $countConditions = "i.label ilike :keyword AND i.deleted_at IS NULL";
        $bind = [
            'keyword' => '%' . $params['keyword'] . '%'
        ];

        if (!is_null($params['konsep_sistem_pencegahan_id'])) {
            $conditions .= " AND PancekIndikator.konsep_sistem_pencegahan_id = :konsep_sistem_pencegahan_id:";
            $countConditions .= " AND i.konsep_sistem_pencegahan_id = :konsep_sistem_pencegahan_id";
            $bind['konsep_sistem_pencegahan_id'] = $params['konsep_sistem_pencegahan_id'];
        }

        $records = PancekIndikator::query()
            ->columns("
                PancekIndikator.id, PancekIndikator.konsep_sistem_pencegahan_id, PancekIndikator.code, PancekIndikator.label, PancekIndikator.label_en, PancekIndikator.formulir_type, PancekIndikator.view_order
            ")
            ->where($conditions)
            ->bind($bind)
            ->orderBy("PancekIndikator.view_order")
            ->limit($params['limit'], $params['offset'])
            ->execute()
            ->toArray();

        $total = $this->rawQuery("SELECT COUNT(*) as total FROM jaga.pancek_indikator i WHERE $countConditions", $bind)[0]['total'];

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

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

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

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

        $params = $this->validatePost();
        $data->konsep_sistem_pencegahan_id = $params['konsep_sistem_pencegahan_id'];
        $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);
        $params = $this->validate($rawBody, [
            'konsep_sistem_pencegahan_id' => ['validators' => [
                'required',
                'digit'
            ]],
            'code' => ['validators' => [
                'required',
                [
                    'name' => 'max_string',
                    'params' => 30
                ]
            ]],
            'label' => ['validators' => [
                'required'
            ]],
            'label_en' => ['validators' => [
                'required'
            ]],
            'view_order' => ['validators' => [
                'required',
                'digit'
            ]],
            "formulir_type" => ['validators' => ['required', [
                'name' => 'inclusion_in',
                'params' => PancekJenisInstansi::TIPE_FORMULIR
            ]]]
        ]);

        $konsepSistemPencegahan = PancekKonsepSistemPencegahan::findFirst(['conditions' => 'id = :id:', 'bind' => ['id' => $params['konsep_sistem_pencegahan_id']]]);
        if (!$konsepSistemPencegahan) throw new CustomErrorException(BaseResponse::DATA_NOT_FOUND, "Konsep Sistem Pencegahan tidak ditemukan");

        return $params;
    }
}
