<?php

namespace App\Controllers\Panel\App\Settings;

use App\Controllers\Panel\BC;
use CodeIgniter\API\ResponseTrait;

class SecretKey extends BC
{
    use ResponseTrait;
    public function index()
    {
        $data['page_title'] = "Pengaturan - Secret Key";
        return view('Panel/App/Settings/SecretKey/index', $data);
    }
    public function data()
    {
        if (!$this->request->isAJAX() && ENVIRONMENT != 'development') {
            exit('No direct script access allowed');
        }

        $data = [];
        foreach (options(['tinymcekey', 'onesignal_config', 'licensekey', 'sck']) as $key => $value) {
            if ($value['option_name'] == 'onesignal_config') {
                foreach (json_decode($value['option_value'], true) as $k => $v) {
                    $data["osc_$k"] = ['value' => $v, 'on' => false];
                }
                continue;
            }
            $data[$value['option_name']] = ['value' => $value['option_value'], 'on' => false];
        }
        return $this->respond(['csrf' => csrf_hash(), 'data' => $data]);
    }
    public function license()
    {
        if (!$this->request->isAJAX() && ENVIRONMENT != 'development') {
            exit('No direct script access allowed');
        }

        $data = [];
        foreach (options(['nama_sekolah', 'eat', 'licensekey', 'npsn']) as $key => $value) {
            $data[$value['option_name']] = $value['option_value'];
        }
        return $this->respond(['data' => $data]);
    }
    public function save_data()
    {
        if (!$this->request->isAJAX() && ENVIRONMENT != 'development') {
            exit('No direct script access allowed');
        }

        $rules['licensekey'] = [
            "alias" => "Kode Lisensi",
            'rules' => "required",
            'errors' => [
                'required' => "{value} Tidak Valid"
            ]
        ];
        $rules['sck'] = [
            "alias" => "Secret Key",
            'rules' => "required",
            'errors' => [
                'required' => "{value} Tidak Valid"
            ]
        ];
        if (!$this->validate($rules)) {
            $errors = $this->validator->getErrors();
            $err = '';
            foreach ($errors as $key => $error) {
                $err = $err . $rules[$key]['alias'] . " : " . $error . '<br>';
            }
            return $this->fail(["csrf" => csrf_hash(), 'message' => $err]);
        }
        $license = $this->request->getVar('licensekey');
        $nd = [
            ['option_name' => 'sck', 'option_value' => $this->request->getVar('sck')],
            ['option_name' => 'tinymcekey', 'option_value' => $this->request->getVar('tinymcekey')],
            ['option_name' => 'onesignal_config', 'option_value' => json_encode([
                'app_id' => $this->request->getVar('osc_app_id'),
                'key' => $this->request->getVar('osc_key'),
                'safari_web_id' => $this->request->getVar('osc_safari_web_id'),
            ])],
        ];
        $npsn = $this->request->getVar('npsn');
        $namasekolah = $this->request->getVar('namasekolah');
        if ($license != options('licensekey') || options('eat') < time()) {
            if ($npsn) $opt['npsn'] = $npsn;
            if ($namasekolah) $opt['namasekolah'] = $namasekolah;
            $valid = checkLicense($license, $opt ?? []);
            if ($valid['state'] == 0) {
                return $this->fail(["csrf" => csrf_hash(), 'message' => $valid['msg'], 'requiredFields' => $valid['requiredFields'] ?? []]);
            }
            if ($valid['state'] == 1) {
                $nd[] = ['option_name' => 'licensekey', 'option_value' => $license];
                $nd[] = ['option_name' => 'eat', 'option_value' => $valid['expired_at']];
                $nd[] = ['option_name' => 'npsn', 'option_value' => $valid['NPSN']];
                $nd[] = ['option_name' => 'nama_sekolah', 'option_value' => $valid['NamaSekolah']];
            }
        }
        if (!save_options($nd)) return $this->fail(['message' => "Gagal Menyimpan Data"]);
        setLog("Mengubah Secret Key");
        return $this->respond(['message' => "Berhasil Disimpan"]);
    }
}
