<?php

namespace App\Controllers\Panel\App\Settings;

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

class General extends BC
{
    use ResponseTrait;
    private $allowed_timezones = ['Asia/Jakarta', 'Asia/Makassar', 'Asia/Jayapura'];
    public function index()
    {
        $data['page_title'] = "Pengaturan - Umum";
        return view('Panel/App/Settings/General/index', $data);
    }
    public function data()
    {
        if (!$this->request->isAJAX() && ENVIRONMENT != 'development') {
            exit('No direct script access allowed');
        }
        $required_options = [
            'appname', 'el_mode', 'npsn', 'website', 'nama_sekolah',
            'alamat', 'email', 'telp', 'ttd_image', 'browserCheck',
            'maintenance', 'chat', 'kecamatan', 'kota', 'strict_browser',
            'nama_kepala_sekolah', 'nip_kepala_sekolah', 'exambro_version',
            'display_video', 'display_news', 'kementrian_image',
            'panel_session_unit', 'panel_session_timeout',
            'mobile_session_unit', 'mobile_session_timeout',

        ];
        $opt = options($required_options);
        $data = [];
        foreach ($opt as $k => $v) {
            $data[$v['option_name']] = $v['option_value'];
        }
        $data['el_mode'] = $data['el_mode'] == '1';
        $data['browserCheck'] = $data['browserCheck'] == '1';
        $data['strict_browser'] = $data['strict_browser'] == '1';
        $data['maintenance'] = $data['maintenance'] == '1' || $data['maintenance'] == null;
        $data['chat'] = $data['chat'] == '1';
        $data['dev_mode'] = ENVIRONMENT != 'production';
        $manifest = json_decode(file_get_contents(FCPATH . "manifest.json"), true);
        $data['background_color'] = $manifest['background_color'] ?? "#0d5afd";
        $data['theme_color'] = $manifest['theme_color'] ?? "#0d5afd";
        $data['logo'] = logo();
        $data['kementrian_image'] = base_url(config('app')->imgPath . "/$data[kementrian_image]");
        $data['ttd_image'] = base_url(config('app')->imgPath . "/$data[ttd_image]");
        $data['timezones'] = [
            'state' => date_default_timezone_get(),
            'options' => $this->allowed_timezones
        ];
        return $this->respond(['csrf' => csrf_hash(), 'data' => $data]);
    }
    public function save()
    {
        if (!$this->request->isAJAX() && ENVIRONMENT != 'development') {
            exit('No direct script access allowed');
        }
        $rules['appname'] = [
            "alias" => "Nama Aplikasi",
            'rules' => "required",
            'errors' => [
                'required' => "{value} Tidak Valid"
            ]
        ];
        $rules['panel_session_timeout'] = [
            "alias" => "Masa Aktif Sesi Akun Panel",
            'rules' => "integer|greater_than[0]",
            'errors' => [
                'integer' => "{value} Harus Angka",
                'greater_than' => "Harus Lebih Besar Dari 0"
            ]
        ];
        $rules['mobile_session_timeout'] = [
            "alias" => "Masa Aktif Sesi Akun Mobile",
            'rules' => "integer|greater_than[0]",
            'errors' => [
                'integer' => "{value} Harus Angka",
                'greater_than' => "Harus Lebih Besar Dari 0"
            ]
        ];
        $rules['panel_session_unit'] = [
            "alias" => "Satuan Sesi Akun Panel",
            'rules' => "in_list[minutes,hours,days]required",
            'errors' => [
                'in_list' => "{value} Tidak Valid",
                'required' => "Dibutuhkan"
            ]
        ];
        $rules['mobile_session_unit'] = [
            "alias" => "Satuan Sesi Akun Mobile",
            'rules' => "in_list[minutes,hours,days]required",
            'errors' => [
                'in_list' => "{value} Tidak Valid",
                'required' => "Dibutuhkan"
            ]
        ];
        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]);
        }
        if (!in_array($this->request->getVar('timezone'), $this->allowed_timezones)) {
            return $this->fail(["csrf" => csrf_hash(), 'message' => "Timezone tidak valid"]);
        }
        $env = ROOTPATH . '.env';
        if (!file_exists($env)) return $this->fail(['message' => "File env Tidak Ditemukan"]);
        $newEnv = '';
        $handle = fopen($env, "r");

        while (($line = fgets($handle)) !== false) {
            if (strpos($line, 'CI_ENVIRONMENT') !== false) {
                $line = $this->request->getVar('dev_mode') == 'on' ? 'development' : 'production';
                if (strpos($newEnv, 'CI_ENVIRONMENT') !== false) continue;
                $line = "CI_ENVIRONMENT = $line\n";
            }
            $newEnv .= $line;
        }
        fclose($handle);
        file_put_contents(ROOTPATH . '.env', $newEnv);
        $manifest = json_decode(file_get_contents(FCPATH . "manifest.json"), true);

        $nd = [
            ['option_name' => 'appname', 'option_value' => $this->request->getVar('appname')],
            ['option_name' => 'alamat', 'option_value' => $this->request->getVar('alamat')],
            ['option_name' => 'email', 'option_value' => $this->request->getVar('email')],
            ['option_name' => 'telp', 'option_value' => $this->request->getVar('telp')],
            ['option_name' => 'kecamatan', 'option_value' => $this->request->getVar('kecamatan')],
            ['option_name' => 'kota', 'option_value' => $this->request->getVar('kota')],
            ['option_name' => 'website', 'option_value' => $this->request->getVar('website')],
            ['option_name' => 'display_video', 'option_value' => $this->request->getVar('display_video')],
            ['option_name' => 'display_news', 'option_value' => $this->request->getVar('display_news')],
            ['option_name' => 'strict_browser', 'option_value' => $this->request->getVar('strict_browser') == 'on' ? 1 : 0],
            ['option_name' => 'exambro_version', 'option_value' => $this->request->getVar('exambro_version')],
            ['option_name' => 'mobile_session_timeout', 'option_value' => $this->request->getVar('mobile_session_timeout')],
            ['option_name' => 'panel_session_timeout', 'option_value' => $this->request->getVar('panel_session_timeout')],
            ['option_name' => 'mobile_session_unit', 'option_value' => $this->request->getVar('mobile_session_unit')],
            ['option_name' => 'panel_session_unit', 'option_value' => $this->request->getVar('panel_session_unit')],
            ['option_name' => 'nama_kepala_sekolah', 'option_value' => $this->request->getVar('nama_kepala_sekolah')],
            ['option_name' => 'nip_kepala_sekolah', 'option_value' => $this->request->getVar('nip_kepala_sekolah')],
            ['option_name' => 'maintenance', 'option_value' => $this->request->getVar('maintenance') == 'on' ? 1 : 0],
            ['option_name' => 'chat', 'option_value' => $this->request->getVar('chat') == 'on' ? 1 : 0],
            ['option_name' => 'el_mode', 'option_value' => $this->request->getVar('el_mode') == 'on' ? 1 : 0],
            ['option_name' => 'browserCheck', 'option_value' => $this->request->getVar('browserCheck') == 'on' ? 1 : 0],
        ];
        $app = config('app');

        $logoFile = $this->request->getFile('logo');
        if ($logoFile) {
            if ($logoFile->isValid()) {
                $allowed_mime = ['image/png', 'image/jpg', 'image/jpeg'];
                if (!in_array($logoFile->getClientMimeType(), $allowed_mime)) return $this->fail(['message' => "Gambar Logo Tidak Valid!"]);
                if (!$logoFile->hasMoved()) {
                    $imgName = $logoFile->getRandomName();
                    $path = $app->imgPath;
                    $fixpath = FCPATH . "$path";
                    $imgExt = $logoFile->getExtension();
                    $imgMime = $logoFile->getMimeType();
                    if (strpos($imgName, '.php') !== false) return $this->fail(['message' => "Gambar Logo Tidak Valid!"]);
                    $logoFile->move($fixpath, $imgName);
                    rmbfe('php', $fixpath);

                    $nd[] = [
                        'option_name' => 'logo',
                        'option_value' => $imgName
                    ];
                    // image resize for pwa
                    $pwaSize = [72, 96, 128, 144, 152, 192, 384, 512];
                    $pwaIcons = [];
                    foreach ($pwaSize as $v) {
                        $icon = [
                            "src" => "$app->imgPath/app/icon-$v" . "x" . $v . "." . $imgExt,
                            "sizes" => $v . "x" . $v,
                            "type" => $imgMime
                        ];
                        resize_image($fixpath . "/" . $imgName, FCPATH . "$icon[src]", ['width' => $v, 'height' => $v]);
                        $pwaIcons[] = $icon;
                    }
                    $manifest['icons'] = $pwaIcons;
                }
            }
        }
        $kementrian_image = $this->request->getFile('kementrian_image');
        if ($kementrian_image) {
            if ($kementrian_image->isValid()) {
                $allowed_mime = ['image/png', 'image/jpg', 'image/jpeg'];
                if (!in_array($kementrian_image->getClientMimeType(), $allowed_mime)) return $this->fail(['message' => "Gambar Kementrian Tidak Valid!"]);
                $path = $app->imgPath;
                $fixpath = FCPATH . "$path";
                $kemName = $kementrian_image->getRandomName();
                if (strpos($kemName, '.php') !== false) return $this->fail(['message' => "Gambar Kementrian Tidak Valid!"]);

                $kementrian_image->move($fixpath, $kemName, true);
                rmbfe('php', $fixpath);
                $nd[] = [
                    'option_name' => 'kementrian_image',
                    'option_value' => $kemName
                ];
            }
        }
        $ttd_image = $this->request->getFile('ttd_image');
        if ($ttd_image) {
            if ($ttd_image->isValid()) {
                $allowed_mime = ['image/png', 'image/jpg', 'image/jpeg'];
                if (!in_array($ttd_image->getClientMimeType(), $allowed_mime)) return $this->fail(['message' => "Gambar Tanda Tangan Tidak Valid!"]);
                $path = $app->imgPath;
                $fixpath = FCPATH . "$path";
                $ttdName = $ttd_image->getRandomName();
                if (strpos($ttdName, '.php') !== false) return $this->fail(['message' => "Gambar Tanda Tangan Tidak Valid!"]);
                $ttd_image->move($fixpath, $ttdName, true);
                rmbfe('php', $fixpath);
                $nd[] = [
                    'option_name' => 'ttd_image',
                    'option_value' => $ttdName
                ];
            }
        }
        if (!save_options($nd)) return $this->fail(['message' => "Gagal Menyimpan Data"]);
        $appfile = APPPATH . '/Config/App.php';
        $rawAppConfig = file_get_contents($appfile);
        file_put_contents($appfile, str_replace($app->appTimezone, $this->request->getVar('timezone'), $rawAppConfig));

        $manifest['name'] = $this->request->getVar('appname');
        $manifest['start_url'] = trim(base_url(), '/');
        $manifest['background_color'] = $this->request->getVar('background_color') ?? "#0d5afd";
        $manifest['theme_color'] = $this->request->getVar('theme_color') ?? "#0d5afd";
        $manifest['short_name'] = $this->request->getVar('appname');
        $manifest['description'] = $this->request->getVar('appname') . (options('nama_sekolah') ? ' - ' . options('nama_sekolah') : '');
        file_put_contents(FCPATH . "manifest.json", json_encode($manifest, JSON_UNESCAPED_SLASHES));
        setLog("Menyimpan pengaturan umum");
        return $this->respond(['message' => "Berhasil Disimpan"]);
    }
}
