<?php

class StranasSubaksiController extends BaseController
{
    public function index()
    {
        $this->checkIsAuthenticated();

        $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' => []]
            ]
        );

        $subaksi_list = StranasSubaksi::find([
            'conditions' => 'nama ilike :keyword: OR keterangan ilike :keyword:',
            'bind' => [
                'keyword' => '%' . $params['keyword'] . '%'
            ],
            'limit' => $params['limit'],
            'offset' => $params['offset'],
            'order' => 'id'
        ]);

        $total_record = StranasSubaksi::count();

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

    public function detail($id)
    {
        $this->checkIsAuthenticated();

        $subaksi = StranasSubaksi::findFirst($id);

        if (empty($subaksi)) {
            throw new CustomErrorException(BaseResponse::INVALID_REQUEST, 'Subaksi tidak ditemukan');
        }

        $result = $subaksi->toDetail();

        return new CollectionPaginatedResponse([$result]);
    }

    public function create()
    {
        $this->checkScopes(['stranas.admin']);

        $rawBody = $this->request->getJsonRawBody(true);

        $params = $this->validate(
            $rawBody,
            [
                'id_aksi' => ['validators' => ['required']],
                'nama' => ['validators' => ['required']],
                'keterangan' => ['validators' => []],
                'presentase_bobot' => ['validators' => ['numeric']]
            ]
        );

        $aksi = StranasAksi::findFirst($params['id_aksi']);

        if (empty($aksi)) {
            throw new CustomErrorException(BaseResponse::INVALID_REQUEST, 'Aksi tidak ditemukan');
        }

        if (!empty($aksi->deleted_at)) {
            throw new CustomErrorException(BaseResponse::INVALID_REQUEST, 'Aksi tidak aktif');
        }

        $subaksi = new StranasSubaksi();
        $subaksi->nama = $params['nama'];
        $subaksi->id_aksi = $params['id_aksi'];
        $subaksi->keterangan = $params['keterangan'];
        if(!empty($params['presentase_bobot'])) {
            $subaksi->presentase_bobot = $params['presentase_bobot'];
        }
        $subaksi->created_by = $this->shared->user->um_id;
        $status = $subaksi->save();

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

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

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

    public function update($id)
    {
        $this->checkScopes(['stranas.admin']);

        $subaksi = StranasSubaksi::findFirst($id);

        if (empty($subaksi)) {
            throw new CustomErrorException(BaseResponse::INVALID_REQUEST, 'Subaksi tidak ditemukan');
        }

        if (!empty($subaksi->deleted_at)) {
            throw new CustomErrorException(BaseResponse::INVALID_REQUEST, 'Subaksi sudah terhapus');
        }

        $rawBody = $this->request->getJsonRawBody(true);

        $params = $this->validate(
            $rawBody,
            [
                'id_aksi' => ['validators' => ['required']],
                'nama' => ['validators' => ['required']],
                'keterangan' => ['validators' => []],
                'presentase_bobot' => ['validators' => ['numeric']]
            ]
        );

        $aksi = StranasAksi::findFirst($params['id_aksi']);

        if (empty($aksi)) {
            throw new CustomErrorException(BaseResponse::INVALID_REQUEST, 'Aksi tidak ditemukan');
        }

        if (!empty($aksi->deleted_at)) {
            throw new CustomErrorException(BaseResponse::INVALID_REQUEST, 'Aksi tidak aktif');
        }

        $subaksi->id_aksi = $params['id_aksi'];
        $subaksi->nama = $params['nama'];
        $subaksi->keterangan = $params['keterangan'];
        if(!empty($params['presentase_bobot'])) {
            $subaksi->presentase_bobot = $params['presentase_bobot'];
        }
        $subaksi->updated_at = date('Y-m-d H:i:s');
        $subaksi->updated_by = $this->shared->user->um_id;
        $status = $subaksi->save();

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

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

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

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

        $subaksi = StranasSubaksi::findFirst($id);

        if (empty($subaksi)) {
            throw new CustomErrorException(BaseResponse::INVALID_REQUEST, 'Subaksi tidak ditemukan');
        }

        if (!empty($subaksi->deleted_at)) {
            throw new CustomErrorException(BaseResponse::INVALID_REQUEST, 'Subaksi sudah terhapus');
        }

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

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

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

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

    public function restore($id)
    {
        $this->checkScopes(['stranas.admin']);

        $subaksi = StranasSubaksi::findFirst($id);

        if (empty($subaksi)) {
            throw new CustomErrorException(BaseResponse::INVALID_REQUEST, 'Subaksi tidak ditemukan');
        }

        if (empty($subaksi->deleted_at)) {
            throw new CustomErrorException(BaseResponse::INVALID_REQUEST, 'Subaksi sudah aktif');
        }

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

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

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

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