<?php

use DusanKasan\Knapsack\Collection;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

class KorsupgahAreaFokusController extends BaseController
{
    public function list()
    {
        $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' => []]
            ]
        );

        $template_list = KorsupgahAreaFokus::find([
            'conditions' => 'title ilike :keyword:',
            'bind' => [
                'keyword' => '%' . $params['keyword'] . '%'
            ],
            'limit' => $params['limit'],
            'offset' => $params['offset']
        ]);

        $total_record = KorsupgahAreaFokus::count();

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

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

        $areaFokus = KorsupgahAreaFokus::findFirst($id);

        if (empty($areaFokus)) {
            throw new CustomErrorException(BaseResponse::INVALID_REQUEST, 'Fokus Area tidak ditemukan');
        }

        return new CollectionPaginatedResponse([$areaFokus]);
    }

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

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

        $params = $this->validate(
            $rawBody,
            [
                'title' => ['validators' => ['required']],
                'description' => ['validators' => []]
            ]
        );

        $areaFokus = new KorsupgahAreaFokus();
        $areaFokus->title = $params['title'];
        $areaFokus->description = $params['description'];
        $status = $areaFokus->save();

        if (!$status) {
            $errors = $areaFokus->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([$areaFokus]);
        }
    }

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

        $areaFokus = KorsupgahAreaFokus::findFirst($id);

        if (empty($areaFokus))
            throw new CustomErrorException(BaseResponse::INVALID_REQUEST, 'Area Fokus dengan ID #' . $id . 'tidak ditemukan');

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

        $params = $this->validate(
            $rawBody,
            [
                'title' => ['validators' => ['required']],
                'description' => ['validators' => []]
            ]
        );

        $areaFokus->title = $params['title'];
        $areaFokus->description = $params['description'];
        $status = $areaFokus->save();

        if (!$status) {
            $errors = $areaFokus->getMessage();

            $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([$areaFokus]);
        }
    }

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

        $areaFokus = KorsupgahAreaFokus::findFirst($id);

        if (empty($areaFokus))
            throw new CustomErrorException(BaseResponse::INVALID_REQUEST, 'Template dengan ID #' . $id . 'tidak ditemukan');

        $status = $areaFokus->delete();

        if (!$status) {
            $errors = $areaFokus->getMessages();

            $error_messages = [];

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

            throw new ValidationException($error_messages);
        } else {

            return new CollectionPaginatedResponse([$areaFokus]);
        }
    }
}
