<?php

class EmisKemenagClient extends BackgroundBaseClient
{
    private $token;
    public $jenjang = [];

    public function filterResponse($body, $result)
    {
        parent::filterResponse($body, $result);
        if($this->logger != null) {
            if(!empty($result)) {
                if(array_key_exists('message', $result)) {
                    if($result['message'] == 'error') {
                        if(array_key_exists('errors', $result)) {
                            if (array_key_exists('code', $result['errors'])) $this->logger->addItem("api_result_code", $result['errors']['code']);
                            if (array_key_exists('message', $result['errors'])) $this->logger->addItem("api_result_message", $result['errors']['message']);
                        }
                    }
                }
            }
        }
    }

    //region Connect to API
    public function partnerLogin()
    {
        $method = "POST";
        $path = "/v1/accounts/partners-login";
        $params = [
            "headers" => [
                "Content-Type" => "application/json"
            ],
            "json" => [
                "public_key" => AppConfig::getValueByKode('EMIS_KEMENAG_PUBLIC_KEY'),
                "private_key" => AppConfig::getValueByKode('EMIS_KEMENAG_PRIVATE_KEY')
            ]
        ];

        //region LOG Definition
        $this->setApiName("emis_kemenag-partenrs_login");
        $this->setLogParams([
            'public_key-pt' => AppConfig::getValueByKode('EMIS_KEMENAG_PUBLIC_KEY'),
            'private_key-semester' => AppConfig::getValueByKode('EMIS_KEMENAG_PRIVATE_KEY'),
        ]);
        //endregion

        $res = $this->execute($method, $path, $params);
        $this->token = $res['results']['token'];
    }

    public function refreshToken()
    {
        $method = "POST";
        $path = "/v1/accounts/refresh";
        $params = [
            "headers" => [
                "Authorization" => "Bearer " . $this->token,
            ]
        ];

        //region LOG Definition
        $this->setApiName("emis_kemenag-refresh");
        $this->setLogParams([
            'token' => $this->token
        ]);
        //endregion

        $res = $this->execute($method, $path, $params);
        $this->token = $res['results']['access_token'];
    }

    public function institutionInfoByProvinceCode($provinceCode, $page)
    {
        $method = "GET";
        $path = "/v1/institutions/info";
        $params = [
            "headers" => [
                "Authorization" => 'Bearer ' . $this->token
            ],
            "query" => [
                'province_code' => $provinceCode,
                'page' => $page
            ]
        ];

        //region LOG Definition
        $this->setApiName("emis_kemenag-institution_info_by_province_code");
        $this->setLogParams([
            'province_code' => $provinceCode,
            'page' => $page
        ]);
        //endregion

        $exec = $this->execute($method, $path, $params);
        return $exec;
    }

    public function institutionInfoByStatisticNum($statisticNum)
    {
        $method = "GET";
        $path = "/v1/institutions/info";
        $params = [
            "headers" => [
                "Authorization" => 'Bearer ' . $this->token
            ],
            "query" => [
                'statistic_num' => $statisticNum
            ],
            "connect_timeout" => 15,
            "timeout" => 15
        ];

        //region LOG Definition
        $this->setApiName("emis_kemenag-institution_info_by_statistic_num");
        $this->setLogParams([
            'statistic_num' => $statisticNum
        ]);
        //endregion

        $exec = $this->execute($method, $path, $params);
        return $exec['results'][0];
    }

    public function rombelSiswa($idEmis)
    {
        $method = "GET";
        $path = "/v1/partners/cari/rombel";
        $params = [
            "headers" => [
                "Authorization" => 'Bearer ' . $this->token
            ],
            "query" => [
                'institution_id' => $idEmis
            ]
        ];

        //region LOG Definition
        $this->setApiName("emis_kemenag-rombel_siswa");
        $this->setLogParams([
            'institution_id' => $idEmis
        ]);
        //endregion

        $exec = $this->execute($method, $path, $params);
        return $exec['results']['rombels'];
    }
    //endregion

    //region Other Function, not connected to API
    //return Data Jenjang
    public function saveDataMadrasah($item, $jenjang = []) {
        $madrasah = Madrasah::findFirst([
            'conditions' => 'id_emis = ?0',
            'bind' => [
                $item['id']
            ]
        ]);
        if(!$madrasah) {
            $madrasah = new Madrasah();
            $madrasah->created_at = date('Y-m-d H:i:s');
        }
        $madrasah->id_emis = $item['id'];
        $madrasah->statistic_num = $item['statistic_num'];
        $madrasah->npsn = $item['npsn'];
        $madrasah->name = $item['name'];
        $madrasah->status = $item['status'];
        $madrasah->phone = $item['phone'];
        $madrasah->accreditation_status = $item['accreditation_status'];
        $madrasah->category = $item['category'];
        $madrasah->student_count = $item['student_count'];
        $madrasah->jumlah_siswa = $item['jumlah_siswa'];
        $madrasah->rombel_count = $item['rombel_count'];
        $madrasah->jumlah_rombel = $item['jumlah_rombel'];
        $madrasah->personnel_count = $item['personnel_count'];
        $madrasah->waktu_pembelajaran_sesuai_kn = $item['waktu_pembelajaran_sesuai_kn'];
        $madrasah->mapel_wajib_sesuai_kn = $item['mapel_wajib_sesuai_kn'];
        $madrasah->jumlah_lulusan_terakhir = $item['jumlah_lulusan_terakhir'];
        $madrasah->has_graduate = $item['has_graduate'];
        $madrasah->institution_id = $item['location']['institution_id'];
        $madrasah->address = $item['location']['address'];
        $madrasah->city_id = $item['location']['city_id'];
        $madrasah->province_id = $item['location']['province_id'];
        $madrasah->longitude = $item['location']['longitude'];
        $madrasah->latitude = $item['location']['latitude'];
        $madrasah->formatted_address = $item['location']['formatted_address'];
        $madrasah->sub_district = $item['location']['sub_district']['sub_district'];
        $madrasah->district = $item['location']['district']['district'];
        $madrasah->city = $item['location']['city']['city'];
        $madrasah->province = $item['location']['province']['province'];
        $madrasah->student_male = $item['institution_student_count']['student_male'];
        $madrasah->student_female = $item['institution_student_count']['student_female'];
        $madrasah->student_normal = $item['institution_student_count']['student_normal'];
        $madrasah->student_special_need = $item['institution_student_count']['student_special_need'];
        $madrasah->student_with_study_group = $item['institution_student_count']['student_with_study_group'];
        $madrasah->student_non_study_group = $item['institution_student_count']['student_non_study_group'];
        $madrasah->student_stop_learning = $item['institution_student_count']['student_stop_learning'];
        $madrasah->student_dropout = $item['institution_student_count']['student_dropout'];
        $madrasah->student_ipa = $item['institution_student_count']['student_ipa'];
        $madrasah->student_ips = $item['institution_student_count']['student_ips'];
        $madrasah->student_bahasa = $item['institution_student_count']['student_bahasa'];
        $madrasah->student_agama = $item['institution_student_count']['student_agama'];
        $madrasah->study_group_num = $item['institution_student_count']['study_group_num'];
        $madrasah->personnel_teacher = $item['institution_personnel_count']['personnel_teacher'];
        $madrasah->personnel_education_staff = $item['institution_personnel_count']['personnel_education_staff'];
        $madrasah->teacher_male = $item['institution_personnel_count']['teacher_male'];
        $madrasah->teacher_female = $item['institution_personnel_count']['teacher_female'];
        $madrasah->teacher_pns = $item['institution_personnel_count']['teacher_pns'];
        $madrasah->teacher_non_pns = $item['institution_personnel_count']['teacher_non_pns'];
        $madrasah->teacher_permanent = $item['institution_personnel_count']['teacher_permanent'];
        $madrasah->teacher_temporary = $item['institution_personnel_count']['teacher_temporary'];
        $madrasah->teacher_other = $item['institution_personnel_count']['teacher_other'];
        $madrasah->education_staff_male = $item['institution_personnel_count']['education_staff_male'];
        $madrasah->education_staff_female = $item['institution_personnel_count']['education_staff_female'];
        $madrasah->education_staff_pns = $item['institution_personnel_count']['education_staff_pns'];
        $madrasah->education_staff_non_pns = $item['institution_personnel_count']['education_staff_non_pns'];
        $madrasah->education_staff_permanent = $item['institution_personnel_count']['education_staff_permanent'];
        $madrasah->updated_at = date('Y-m-d H:i:s');

        if(!in_array($item['category'], $jenjang))
            $jenjang[] = $item['category'];

        $madrasah->save();
        return $jenjang;
    }
    //endregion
}
