<?php

namespace App\Models\Panel;

use CodeIgniter\Model;

class BankSoal extends Model
{
    protected $DBGroup              = 'default';
    protected $table                = 'm_banksoal';
    protected $primaryKey           = 'id';
    protected $useAutoIncrement     = true;
    protected $insertID             = 0;
    protected $returnType           = 'array';
    protected $useSoftDeletes       = false;
    protected $protectFields        = true;
    protected $allowedFields        = ['kode', 'deskripsi', 'user_id'];

    // Dates
    protected $useTimestamps        = true;
    protected $dateFormat           = 'int';
    protected $createdField         = 'created_at';
    protected $updatedField         = 'updated_at';
    protected $deletedField         = 'deleted_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          = [];

    static function jenis($jenis = null)
    {
        $jenisSoal = [
            "pg" => 1,
            "esai" => 2,
            "pgmulti" => 3,
            "pgcouple" => 4,
            "shortentry" => 5,
            "pgtf" => 6,
        ];
        if (!$jenis) return $jenisSoal;
        return $jenisSoal[$jenis];
    }
    public function getAll($opt = [])
    {
        $select = "$this->table.*,users.fullname created_by";
        $select .= ",(SELECT COUNT(*) FROM soal_data WHERE bank_id = $this->table.id AND jenis_soal = " . (new BankSoal)->jenis('pg') . ") count_soal_pg";
        $select .= ",(SELECT COUNT(*) FROM soal_data WHERE bank_id = $this->table.id AND jenis_soal = " . (new BankSoal)->jenis('esai') . ") count_soal_esai";
        $select .= ",(SELECT COUNT(*) FROM soal_data WHERE bank_id = $this->table.id AND jenis_soal = " . (new BankSoal)->jenis('pgmulti') . ") count_soal_pgmulti";
        $select .= ",(SELECT COUNT(*) FROM soal_data WHERE bank_id = $this->table.id AND jenis_soal = " . (new BankSoal)->jenis('pgtf') . ") count_soal_pgtf";
        $select .= ",(SELECT COUNT(*) FROM soal_data WHERE bank_id = $this->table.id AND jenis_soal = " . (new BankSoal)->jenis('pgcouple') . ") count_soal_pgcouple";
        $select .= ",(SELECT COUNT(*) FROM soal_data WHERE bank_id = $this->table.id AND jenis_soal = " . (new BankSoal)->jenis('shortentry') . ") count_soal_shortentry";
        $select .= ",(SELECT SUM(ssd.true_default_point) FROM soal_data ssd WHERE ssd.bank_id = $this->table.id AND ssd.jenis_soal IN (" . (new BankSoal)->jenis('pg') . "," . (new BankSoal)->jenis('pgmulti') . "," . (new BankSoal)->jenis('pgtf') . "," . (new BankSoal)->jenis('pgcouple') . "," . (new BankSoal)->jenis('shortentry') . ")) total_true_default_point";
        $select .= ",(SELECT SUM(ssd.false_default_point) FROM soal_data ssd WHERE ssd.bank_id = $this->table.id AND ssd.jenis_soal IN (" . (new BankSoal)->jenis('pg') . "," . (new BankSoal)->jenis('pgmulti') . "," . (new BankSoal)->jenis('pgtf') . "," . (new BankSoal)->jenis('pgcouple') . "," . (new BankSoal)->jenis('shortentry') . ")) total_false_default_point";
        $builder = $this->db->table($this->table);
        $builder->join('users', "users.id=$this->table.user_id");
        $builder->select($select);
        if (isset($opt['ORDER'])) {
            if (is_array($opt['ORDER'])) {
                $builder->orderBy($opt['ORDER'][0], $opt['ORDER'][1]);
            } else {
                $builder->orderBy("$this->table.created_at", $opt['ORDER']);
            }
        }
        if (isset($opt['user_id'])) {
            $builder->where("$this->table.user_id", $opt['user_id']);
        }
        if (isset($opt['id'])) {
            $builder->where("$this->table.id", $opt['id']);
            return $builder->get()->getRowArray();
        }
        return $builder->get()->getResultArray();
    }
    public function getBankSoalAllData($id)
    {
        $builder = $this->db->table("soal_data");
        $builder->select('soal_data.*');
        $builder->join("soal_opsi so", "so.soal_id=soal_data.id", "left");
        $builder->where(['soal_data.bank_id' => $id])->groupBy('soal_data.id');
        return $builder->get()->getResultArray();
    }
    public function getSoalsBankId($id, $opt = [])
    {
        $soals = [];
        $select = ["sd.*"];
        $terpakai = "(CASE ";
        $terpakai .= "WHEN sd.jenis_soal = " . $this->jenis('pg') . " THEN ((SELECT COUNT(*) FROM jawaban_pg_ujian_siswa WHERE jawaban_pg_ujian_siswa.soal_id=sd.id)+(SELECT COUNT(*) FROM jawaban_pg_temp_ujian_siswa WHERE jawaban_pg_temp_ujian_siswa.soal_id=sd.id)) ";
        $terpakai .= "WHEN sd.jenis_soal = " . $this->jenis('pgmulti') . " THEN ((SELECT COUNT(*) FROM jawaban_pgmulti_ujian_siswa WHERE jawaban_pgmulti_ujian_siswa.soal_id=sd.id)+(SELECT COUNT(*) FROM jawaban_pgmulti_temp_ujian_siswa WHERE jawaban_pgmulti_temp_ujian_siswa.soal_id=sd.id)) ";
        $terpakai .= "WHEN sd.jenis_soal = " . $this->jenis('esai') . " THEN ((SELECT COUNT(*) FROM jawaban_esai_ujian_siswa WHERE jawaban_esai_ujian_siswa.soal_id=sd.id)+(SELECT COUNT(*) FROM jawaban_esai_temp_ujian_siswa WHERE jawaban_esai_temp_ujian_siswa.soal_id=sd.id)) ";
        $terpakai .= "WHEN sd.jenis_soal = " . $this->jenis('pgtf') . " THEN ((SELECT COUNT(*) FROM jawaban_pgtf_ujian_siswa WHERE jawaban_pgtf_ujian_siswa.soal_id=sd.id)+(SELECT COUNT(*) FROM jawaban_pgtf_temp_ujian_siswa WHERE jawaban_pgtf_temp_ujian_siswa.soal_id=sd.id)) ";
        $terpakai .= "WHEN sd.jenis_soal = " . $this->jenis('pgcouple') . " THEN ((SELECT COUNT(*) FROM jawaban_pgcouple_ujian_siswa WHERE jawaban_pgcouple_ujian_siswa.soal_id=sd.id)+(SELECT COUNT(*) FROM jawaban_pgcouple_temp_ujian_siswa WHERE jawaban_pgcouple_temp_ujian_siswa.soal_id=sd.id)) ";
        $terpakai .= "WHEN sd.jenis_soal = " . $this->jenis('shortentry') . " THEN ((SELECT COUNT(*) FROM jawaban_shortentry_ujian_siswa WHERE jawaban_shortentry_ujian_siswa.soal_id=sd.id)+(SELECT COUNT(*) FROM jawaban_shortentry_temp_ujian_siswa WHERE jawaban_shortentry_temp_ujian_siswa.soal_id=sd.id)) ";
        $terpakai .= "ELSE 0 END) terpakai";
        $select[] = $terpakai;
        $opsi = $this->getOpsiBankId($id);
        $builder = $this->db->table("soal_data sd");
        $builder->select(implode(',', $select));
        $builder->join("soal_opsi so", "so.soal_id=sd.id", "left");
        $builder->where(['sd.bank_id' => $id])->groupBy('sd.id');
        if (isset($opt['limit'])) $builder->limit($opt['limit']);
        if (isset($opt['notIds'])) $builder->whereNotIn('sd.id', $opt['notIds']);
        foreach ($builder->get()->getResultArray() as $k => $v) {
            $v['options'] = [];
            $v['couples'] = [];
            if ($v['jenis_soal'] == $this->jenis('pgcouple')) $v['couples'] = $this->getCoupleSoalId($v['id']);
            foreach ($opsi as $ko => $vo) {
                if (count($v['options']) >= 5) break;
                if ($vo['soal_id'] == $v['id']) $v['options'][] = $vo;
            }
            $soals[] = $v;
        }
        return $soals;
    }
    public function getOpsiBankId($id)
    {
        $opsi = [];
        $builder = $this->db->table("soal_opsi so");
        $builder->select('so.*,sd.jenis_soal');
        $builder->join('soal_data sd', 'sd.id=so.soal_id');
        $builder->where('sd.bank_id', $id);
        foreach ($builder->get()->getResultArray() as $k => $v) {
            $opsi[] = $v;
        }
        return $opsi;
    }
    public function getCoupleSoalId($id)
    {
        $builder = $this->db->table("soal_data_couple");
        return $builder->getWhere(['soal_id' => $id])->getResultArray();
    }
    public function getBankSoalAllDataLight($id)
    {
        $builder = $this->db->table("soal_data sd");
        $builder->select('sd.id,sd.bank_id,sd.jenis_soal,sd.true_default_point,sd.false_default_point,sd.shortentry,sd.updated_at,sd.created_at');
        $builder->join("soal_opsi so", "so.soal_id=sd.id", "left");
        $builder->where(['sd.bank_id' => $id])->groupBy('sd.id');
        return $builder->get()->getResultArray();
    }
    public function getBankSoalDataSoal($id)
    {
        $builder = $this->db->table("soal_data");
        return $builder->where(['id' => $id])->get()->getRowArray();
    }
    public function getBankSoalDataSoalCouple($id)
    {
        $builder = $this->db->table("soal_data_couple");
        return $builder->where(['soal_id' => $id])->get()->getResultArray();
    }
    public function getBankSoalDataSoalWithOption($id)
    {
        $data['soal_data'] = $this->getBankSoalDataSoal($id);
        $data['soal_data_couple'] = $this->getBankSoalDataSoalCouple($id);
        $builder = $this->db->table("soal_opsi");
        $builder->where(['soal_id' => $id]);
        $data['soal_opsi'] = $builder->get()->getResultArray();
        return $data;
    }
    public function insertSoalDataOptionBatch($data)
    {
        return $this->db->table("soal_opsi")->insertBatch($data);
    }
    public function deleteSoal($id, $bid)
    {
        return $this->db->table("soal_data")->where(['bank_id' => $bid, 'id' => $id])->delete();
    }
}
