<?php

namespace App\Models\Panel\Elearning;

use CodeIgniter\Model;

class KompetensiDasar extends Model
{
    protected $DBGroup          = 'default';
    protected $table            = 'kompetensi_dasar';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;
    protected $insertID         = 0;
    protected $returnType       = 'array';
    protected $useSoftDeletes   = false;
    protected $protectFields    = true;
    protected $allowedFields    = [
        'nomor',
        'nama',
        'kode',
        'mapel_id',
        'tingkat_id',
        'user_id',
    ];

    // Dates
    protected $useTimestamps = true;
    protected $dateFormat    = 'datetime';
    protected $createdField  = 'created_at';
    protected $updatedField  = 'updated_at';

    // Validation
    protected $validationRules      = [];
    protected $validationMessages   = [];
    protected $skipValidation       = false;
    protected $cleanValidationRules = true;

    // Callbacks
    protected $allowCallbacks = true;
    protected $beforeInsert   = [];
    protected $afterInsert    = [];
    protected $beforeUpdate   = [];
    protected $afterUpdate    = [];
    protected $beforeFind     = [];
    protected $afterFind      = [];
    protected $beforeDelete   = [];
    protected $afterDelete    = [];
    public function getAll($opt = [])
    {
        $select = "$this->table.*,(CASE WHEN $this->table.kode = 'KP' THEN CONCAT('3.',$this->table.nomor) ELSE CONCAT('4.',$this->table.nomor) END) nomor,u.fullname created_by,CONCAT($this->table.tingkat_id,'-',$this->table.mapel_id) tingmap,mm.nama nama_mapel,mm.kode kode_mapel,mt.kode kode_tingkat";
        $builder = $this->db->table($this->table);
        $builder->join('m_mapel mm', "mm.id=$this->table.mapel_id");
        $builder->join('m_tingkat mt', "mt.id=$this->table.tingkat_id");
        $builder->join('users u', "u.id=$this->table.user_id");
        $builder->select($select);
        if (isset($opt['user_id'])) {
            $builder->where("$this->table.user_id", $opt['user_id']);
        }
        if (isset($opt['tingkat_id'])) {
            if (is_array($opt['tingkat_id'])) {
                $builder->whereIn("$this->table.tingkat_id", $opt['tingkat_id']);
            } else {
                $builder->where("$this->table.tingkat_id", $opt['tingkat_id']);
            }
        }
        if (isset($opt['mapel_id'])) {
            if (is_array($opt['mapel_id'])) {
                $builder->whereIn("$this->table.mapel_id", $opt['mapel_id']);
            } else {
                $builder->where("$this->table.mapel_id", $opt['mapel_id']);
            }
        }
        if (isset($opt['tingmap'])) {
            if (is_array($opt['tingmap'])) {
                $builder->havingIn("tingmap", $opt['tingmap']);
            } else {
                $builder->having("tingmap", $opt['tingmap']);
            }
        }
        return $builder->get()->getResultArray();
    }
}
