<?php

class SPIProfilRespondenInternalController extends BaseController
{

    public function getAll()
    {
        $getParams = $this->request->get();

        $getParams['limit'] = $this->getDefaultLimit($getParams);
        $getParams['offset'] = array_key_exists('offset', $getParams) ? $getParams['offset'] : 0;
        $getParams['keyword'] = array_key_exists('keyword', $getParams) ? $getParams['keyword'] : '';
        $getParams['tahun'] = array_key_exists('tahun', $getParams) ? $getParams['tahun'] : '-9';

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

        $code = 'profil_responden_internal';
        $kp = SPIResponden::find([
            'conditions' => 'nama ilike :keyword: and is_active = true and code = :code: and (tahun = :tahun: or :tahun: = "-9")',
            'bind' => [
                'keyword' => '%' . $params['keyword'] . '%',
                'code' => $code,
                'tahun' => $getParams['tahun']
            ],
            'limit' => $params['limit'],
            'offset' => $params['offset']
        ]);


        $total_record = SPIResponden::find([
            'conditions' => 'nama ilike :keyword: and is_active = true and code = :code: and (tahun = :tahun: or :tahun: = "-9")',
            'bind' => [
                'keyword' => '%' . $params['keyword'] . '%',
                'code' => $code,
                'tahun' => $getParams['tahun']
            ],
        ])->count();

        return new PaginatedResponse($kp, $total_record, $params['limit'], $params['offset']);
    }

    public function detail($id)
    {

        $code = 'profil_responden_internal';
        $kp = SPIResponden::find([
            'conditions' => 'id = :id: and is_active = true and code = :code:',
            'bind' => [
                'id' => $id,
                'code' => $code
            ]
        ]);

        return new CollectionPaginatedResponse($kp);
    }

    public function store()
    {
         $this->checkScopes(['spi.manage_master_data']);

        $rawBody = $this->request->getJsonRawBody(true);
        $params = $this->validate(
            $rawBody,
            [
                'tahun' => ['validators' => ['required']],
                'nama' => ['validators' => ['required']],
                'keterangan' => ['validators' => ['required']]
            ]
        );

        $code = 'profil_responden_internal';
        $tahun = $params['tahun'];
        $total_record = SPIResponden::find([
            'conditions' => "is_active = true and code = '$code' and tahun = '$tahun'"
        ])->count();

        if ($total_record > 0) {
            throw new CustomErrorException(BaseResponse::INVALID_REQUEST, "Profil responed internal data pada $tahun Sudah digunakan");
        }

        $kp = new SPIResponden();
        $kp->id = null;
        $kp->tahun = $tahun;
        $kp->code = $code;
        $kp->nama = $params['nama'];
        $kp->keterangan = $params['keterangan'];
        $kp->is_active = true;
        $kp->created_at = date('Y-m-d H:i:s');
        $kp->created_by = $this->shared->user->um_id;
        $status = $kp->save();

        if (!$status) {
            $errors = $kp->getMessages();
            $error_messages = [];

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

            throw new ValidationException($error_messages);
        } else {
            return new CollectionPaginatedResponse([$kp]);
        }
    }

    public function update($id)
    {
         $this->checkScopes(['spi.manage_master_data']);
        $kp = SPIResponden::findFirst($id);

        if (empty($kp)) :
            throw new CustomErrorException(BaseResponse::INVALID_REQUEST, 'id' . $id . 'tidak ditemukan');
        endif;

        if (!empty($kp->deleted_at)) :
            throw new CustomErrorException(BaseResponse::INVALID_REQUEST, 'id ' . $id  . 'mungkin sudah terhapus');
        endif;

        $rawBody = $this->request->getJsonRawBody(true);
        $params = $this->validate(
            $rawBody,
            [
                'tahun' => ['validators' => ['required']],
                'nama' => ['validators' => ['required']],
                'keterangan' => ['validators' => ['required']]
            ]
        );

        $code = 'profil_responden_internal';
        $tahun = $params['tahun'];
        $total_record = SPIResponden::find([
            'conditions' => "is_active = true and code = '$code' and tahun = '$tahun' and id != '$id'"
        ])->count();

        if ($total_record > 0) {
            throw new CustomErrorException(BaseResponse::INVALID_REQUEST, "Profil responed internal data pada $tahun Sudah digunakan");
        }
        
        $kp->tahun = $params['tahun'];
        $kp->code = $code;
        $kp->nama = $params['nama'];
        $kp->keterangan = $params['keterangan'];
        $kp->is_active = true;
        $kp->updated_at = date('Y-m-d H:i:s');
        $kp->updated_by = $this->shared->user->um_id;
        $status = $kp->save();

        if (!$status) {
            $errors = $kp->getMessages();
            $error_messages = [];

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

            throw new ValidationException($error_messages);
        } else {
            return new CollectionPaginatedResponse([$kp]);
        }
    }

    public function delete($id)
    {
         $this->checkScopes(['spi.manage_master_data']);

        $kp = SPIResponden::findFirst($id);

        if (empty($kp)) :
            throw new CustomErrorException(BaseResponse::INVALID_REQUEST, 'id ' . $id . ' tidak diketemukan');
        endif;
        if (!empty($kp->deleted_at)) :
            throw new CustomErrorException(BaseResponse::INVALID_REQUEST, 'id ' . $id . ' mungkin sudah terhapus');
        endif;

        $date = date('Y-m-d H:i:s');
        $kp->is_active = false;
        $kp->updated_at = $date;
        $kp->deleted_at = $date;
        $kp->updated_by = $this->shared->user->um_id;
        $status = $kp->save();

        if (!$status) {
            $errors = $kp->getMessages();
            $error_messages = [];

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

            throw new ValidationException($error_messages);
        } else {
            return new CollectionPaginatedResponse([$kp]);
        }
    }
}
