<?php

class SPILogDownloadController 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['instansi'] = array_key_exists('instansi', $getParams) ? $getParams['instansi'] : 'all';

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

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


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

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

    public function detail($id)
    {

        $kp = SPILogDownload::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']],
                'instansi' => ['validators' => ['required']],
            ]
        );

        $instansi_id = $params['instansi'];
        $instansi = Instansi::findFirst([
            'conditions' => 'id = :id:',
            'bind' => [
                'id' => $instansi_id
            ]
        ]);

        if ($instansi == null) {
            throw new CustomErrorException(BaseResponse::INVALID_REQUEST, "Instansi $instansi_id tidak ditemukan");
        }

        $kp = new SPILogDownload();
        $kp->id = null;
        $kp->username = $this->shared->user->um_user_name;
        $kp->email = $this->shared->user->email;

        $kp->tahun = $params['tahun'];
        $kp->instansi = $instansi_id;
        $kp->instansi_name = $instansi->nama;
        $kp->tanggal = date('Y-m-d');

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