<?php

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

class SPIConfigController extends BaseController
{

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

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

        $params = $this->validate(
          $getParams,
          [
            'limit' => ['validators' => ['digit']],
            'offset' => ['validators' => ['digit']]
          ]
        );
        
        $kp = SPIConfig::find([
            'conditions' => "",
            'bind' => [],
            'limit' => $params['limit'],
            'offset' => $params['offset']
        ]);


        $total_record = SPIConfig::find([
            'conditions' => "",
            'bind' => [],
        ])->count();

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

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

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

            $kp = SPIConfig::findFirst();
            if (empty($kp)) {
                $kp = new SPIConfig();
                $kp->id = null;
            }
            
            $kp->notif_public = $params['notifPublic'];
            $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);
            }
            
            $this->db->commit();
        } catch (\Exception $ex) {
            $this->db->rollback();
            throw $ex;
        }
        
        return new CollectionPaginatedResponse([$kp]);
    }
    
}
