<?php

class SPIPeriodeController 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'] : '';

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

        $kp = SPIPeriode::find([
            'conditions' => 'tahun ilike :keyword: and is_active = true',
            'bind' => [
                'keyword' => '%' . $params['keyword'] . '%'
            ],
            'limit' => $params['limit'],
            'offset' => $params['offset']
        ]);


        $total_record = SPIPeriode::find([
            'conditions' => 'tahun ilike :keyword: and is_active = true',
            'bind' => [
                'keyword' => '%' . $params['keyword'] . '%'
            ],
        ])->count();

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

    public function detail($id)
    {

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

        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']],
                'keterangan' => ['validators' => ['required']]
            ]
        );

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

        if ($total_record > 0) {
            throw new CustomErrorException(BaseResponse::INVALID_REQUEST, 'Tahun ' . $tahun . ' Sudah digunakan');
        }

        $kp = new SPIPeriode();
        $kp->id = null;
        $kp->tahun = $params['tahun'];
        $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 = SPIPeriode::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']],
                'keterangan' => ['validators' => ['required']]
            ]
        );

        $tahun = $params['tahun'];
        $total_record = SPIPeriode::find([
            'conditions' => "is_active = true and tahun = '$tahun' and id != '$id'"
        ])->count();
        if ($total_record > 0) {
            throw new CustomErrorException(BaseResponse::INVALID_REQUEST, 'Tahun ' . $tahun . ' Sudah digunakan');
        }
        
        $kp->tahun = $params['tahun'];
        $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 = SPIPeriode::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]);
        }
    }
}
