<?php

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

class SPIGenerateReportController 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['tahun'] = array_key_exists('tahun', $getParams) ? $getParams['tahun'] : '-9';

        $params = $this->validate(
          $getParams,
          [
            'limit' => ['validators' => ['digit']],
            'offset' => ['validators' => ['digit']],
            'keyword' => ['validators' => []]
          ]
        );
        
        $kp = SPIReportHeader::find([
          'conditions' => '(keterangan ilike :keyword: or tahun ilike :keyword:) and is_active = true and (tahun = :tahun: or :tahun: = "-9")',
          'bind' => [
              'keyword' => '%' . $params['keyword'] . '%',
              'tahun' => $getParams['tahun']
          ],
          'limit' => $params['limit'],
          'offset' => $params['offset']
        ]);


        $total_record = SPIReportHeader::find([
          'conditions' => '(keterangan ilike :keyword: or tahun ilike :keyword:) and is_active = true and (tahun = :tahun: or :tahun: = "-9")',
          'bind' => [
              'keyword' => '%' . $params['keyword'] . '%',
              'tahun' => $getParams['tahun']
          ],
        ])->count();

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

    public function detail($id)
    {
        $kp = SPIReportHeader::findFirst([
            'conditions' => 'id = :id: and is_active = true',
            'bind' => [
                'id' => $id
            ]
        ]);

        if (empty($kp)) :
            throw new CustomErrorException(BaseResponse::INVALID_REQUEST, 'Genrate report dengan id' . $id . 'tidak diketemukan');
        endif;

        $result = $kp->toDetail();

        return new CollectionPaginatedResponse($result);
    }

    public function updateLink() {
      $this->db->begin();

        try {
            $this->checkScopes(['spi.manage_master_data']);
            $rawBody = $this->request->getJsonRawBody(true);
            $params = $this->validate(
                $rawBody,
                [
                    'tahun' => ['validators' => ['required']],
                    'instansi' => ['validators' => ['required']]
                ]
            );

            $tahun = $params['tahun'];
            $instansi_id = $params['instansi'];

            $kp = SPIReportDetail::findFirst([
                'conditions' => 'instansi_id = :instansi_id: and tahun = :tahun: and is_active = true',
                'bind' => [
                    'instansi_id' => $instansi_id,
                    'tahun' => $tahun,
                ]
            ]);

            $kp->report_link = "/DownloadSPIPdf?year=$tahun&instansi=$instansi_id";
            $kp->status = 4;

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

    public function store()
    {
        $this->db->begin();

        try {
             $this->checkScopes(['spi.manage_master_data']);

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

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

            if ($total_record > 0) {
                throw new CustomErrorException(BaseResponse::INVALID_REQUEST, "Report pada $tahun Sudah digunakan");
            }

            $kp = new SPIReportHeader();
            $kp->id = null;
            $kp->tahun = $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);
            }

            // child
            foreach ($params['details'] as $key => $val) {
                $instansi = Instansi::findFirst([
                    'conditions' => 'id = :id:',
                    'bind' => [
                        'id' => $val["instansi_id"]
                    ]
                ]);

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

                $det = new SPIReportDetail();
                $det->spi_report_header = $kp->id;
                $det->tahun = $tahun;
                $det->instansi_id = $val["instansi_id"];
                $det->instansi_name = $instansi->nama;
                $det->report_link = "undefined";
                $det->status = 1;

                $det->is_active = true;
                $det->created_at = date('Y-m-d H:i:s');
                $det->created_by = $this->shared->user->um_id;

                $status = $det->save();

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

    public function update($id)
    {
        $this->db->begin();

        try {
             $this->checkScopes(['spi.manage_master_data']);
            $kp = SPIReportHeader::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']],
                    'details' => ['validators' => ['required']]
                ]
            );
    
            $tahun = $params['tahun'];
            $total_record = SPIReportHeader::find([
                'conditions' => "is_active = true and tahun = '$tahun' and id != '$id'"
            ])->count();
    
            if ($total_record > 0) {
                throw new CustomErrorException(BaseResponse::INVALID_REQUEST, "Report pada $tahun Sudah digunakan");
            }
            
            $kp->tahun = $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);
            }
            
            // delete all detail
            $this->db->delete("spi_report_detail", "spi_report_header = " . $id);

            // child
            foreach ($params['details'] as $spi_report_header => $val) {
                $instansi = Instansi::findFirst([
                    'conditions' => 'id = :id:',
                    'bind' => [
                        'id' => $val["instansi_id"]
                    ]
                ]);

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

                $det = new SPIReportDetail();
                $det->spi_report_header = $id;
                $det->tahun = $tahun;
                $det->instansi_id = $val["instansi_id"];
                $det->instansi_name = $instansi->nama;
                $det->report_link = "undefined";
                $det->status = 1;

                $det->is_active = true;
                $det->created_at = date('Y-m-d H:i:s');
                // $det->created_by = $this->shared->user->um_id;

                $status = $det->save();

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

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

        $kp = SPIReportHeader::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]);
        }
    }
}
