<?php

use Jaga\Models\BaseModel;

class AppConfig extends BaseModel
{
    public $id;
    public $kode;
    public $nilai;
    public $keterangan;
    public $created_at;
    public $updated_at;
    public $deleted_at;
    public $is_public;

    public function initialize()
    {
        $this->setSchema("jaga");
        $this->setSource("app_config");
    }

    /**
     * @param $kode
     * @return AppConfig
     * @throws CustomErrorException
     */
    public static function findByKode($kode): AppConfig
    {
        $data = AppConfig::findFirst([
            'conditions' => 'kode = :kode:',
            'bind' => ['kode' => $kode]
        ]);

        if (!$data) {
            throw new CustomErrorException(BaseResponse::DATA_NOT_FOUND, "Data tidak ditemukan");
        }

        return $data;
    }

    public static function getValueByKode($kode)
    {
        $value = null;
        try {
            $appConfig = self::findByKode($kode);
            $value = $appConfig->nilai;
        } catch (CustomErrorException $e) {
            $value = null;
        }

        return $value;
    }

    public static function getIntValueByKode($kode): int
    {
        $value = self::getValueByKode($kode);
        if (is_numeric($value)) $value = intval($value);
        else $value = 0;

        return $value;
    }

    public static function getIntValueByKodeOrDefault($kode, int $default): int
    {
        $value = self::getValueByKode($kode);
        if (is_numeric($value)) $value = intval($value);
        else $value = $default;

        return $value;
    }

    public static function findByLikeKode($kode) {
        return AppConfig::find([
            'conditions' => 'kode ILIKE :kode:',
            'bind' => ['kode' => "%$kode%"]
        ]);
    }
}
