<?php

namespace App\Models\Mobile\Ujian;

use CodeIgniter\Model;

class Jadwal extends Model
{
    protected $DBGroup              = 'default';
    protected $table                = 'jadwal_ujian';
    protected $primaryKey           = 'id';
    protected $useAutoIncrement     = true;
    protected $insertID             = 0;
    protected $returnType           = 'array';
    protected $useSoftDeletes       = false;
    protected $protectFields        = true;
    protected $allowedFields        = [
        'nama', 'tahun_id', 'locked', 'draft_id', 'ruang_id', 'jenis_id', "pengawas_id",
        "multi_login", 'status', 'startDateTime', 'endDateTime', 'token', 'use_token',
        'strict', 'afktimeout', 'maxCheatCount', 'show_point', 'cache_soal',
    ];

    // Dates
    protected $useTimestamps        = false;
    protected $dateFormat           = 'datetime';
    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          = [];
    protected $select               = [
        "TO_BASE64(us.id) ujian_id",
        "TO_BASE64(us.jadwal_id) jadwal_id,us.status,us.start_at,us.end_at,ju.startDateTime,ju.endDateTime",
        "mm.nama nama_mapel,ju.use_token,ju.show_point"
    ];

    public function overview($opt = [])
    {
        if (isset($opt['jwt'])) {
            $this->select[] = "(CASE WHEN ju.multi_login = '0' AND us.jwt != '$opt[jwt]' THEN 1 ELSE 0 END) locked";
        }
        $this->select[] = "ju.nama as nama_jadwal";
        $builder = $this->db->table('ujian_siswa us');
        $builder->select(implode(',', $this->select), false);
        $builder->join("jadwal_ujian ju", "ju.id=us.jadwal_id");
        $builder->join("draft_ujian du", "du.id=ju.draft_id");
        $builder->join("m_mapel mm", "mm.id=du.mapel_id");
        $builder->join("tahun_pelajaran tp", "tp.id=ju.tahun_id", "left");
        if (isset($opt['siswa_id'])) {
            $builder->where("us.siswa_id", $opt['siswa_id']);
        }
        if (isset($opt['status_ujian'])) {
            $builder->where("us.status", $opt['status_ujian']);
        }
        if (isset($opt['tahun_id'])) {
            $builder->where("tp.id", $opt['tahun_id']);
        } elseif (isset($opt['tahun_pelajaran'])) {
            $builder->where("tp.id", $opt['tahun_pelajaran']);
        }
        if (isset($opt['startDateTime']) && isset($opt['endDateTime'])) {
            $builder->where("(ju.endDateTime >= $opt[endDateTime] AND ju.startDateTime <= $opt[startDateTime]) =", true, false);
        }
        if (isset($opt['nowDateTime'])) {
            $tdy[] = strtotime(date("Y-m-d 00:00"), $opt['nowDateTime']);
            $tdy[] = strtotime(date("Y-m-d 23:59"), $opt['nowDateTime']);
            $today[] = "$opt[nowDateTime] BETWEEN ju.startDateTime AND ju.endDateTime";
            $today[] = "ju.startDateTime BETWEEN $tdy[0] AND $tdy[1]";
            $today[] = "ju.endDateTime BETWEEN $tdy[0] AND $tdy[1]";
            $builder->where("(CASE WHEN $today[0] THEN 1 WHEN $today[1] THEN 1 WHEN $today[2] THEN 1 ELSE 0 END) = ", 1, false);
        }
        if (isset($opt['tahun_active'])) $builder->where("tp.is_active", $opt['tahun_active']);
        $builder->where("ju.status", $opt['status_jadwal'] ?? '1');
        $builder->orderBy('ju.startDateTime', 'DESC');
        return $builder->get()->getResultArray();
    }
    public function findId($id, $opt = [])
    {
        $select = [
            "TO_BASE64(us.id) ujian_id,ju.multi_login,ju.show_point",
            "TO_BASE64(us.jadwal_id) jadwal_id,us.status,ju.status status_jadwal,us.start_at",
            "us.end_at,ju.startDateTime,ju.endDateTime,du.minFinishTime",
            "mm.nama nama_mapel,ju.use_token,us.siswa_id,du.timeout"
        ];
        if (($opt['withToken'] ?? false)) {
            $select[] = "ju.token,us.jwt";
        }
        $builder = $this->db->table('ujian_siswa us');
        $builder->select(implode(',', $select), false);
        $builder->join("jadwal_ujian ju", "ju.id=us.jadwal_id");
        $builder->join("draft_ujian du", "du.id=ju.draft_id");
        $builder->join("m_mapel mm", "mm.id=du.mapel_id");
        if (isset($opt['status'])) $builder->where("ju.status",  $opt['status']);
        $builder->where("us.id",  $id);
        return $builder->get()->getRowArray();
    }
}
