<?php

namespace App\Controllers\Panel\Elearning\JadwalMengajar;

use App\Controllers\Panel\BC;
use App\Models\Panel\Elearning\JadwalMengajar\Jadwal;
use CodeIgniter\API\ResponseTrait;

class Main extends BC
{
    use ResponseTrait;
    public function index()
    {
        return view('Panel/Elearning/JadwalMengajar/index', ['page_title' => "Jadwal Mengajar"]);
    }
    public function all()
    {
        if (!$this->request->isAJAX() && ENVIRONMENT != 'development') {
            exit('No direct script access allowed');
        }
        $jadwal = [];
        foreach ((new Jadwal())->getAll() as $j) {
            $j['startDateTime'] = get_time($j['startDay'], $j['startTime']);
            $j['endDateTime'] = get_time($j['startDay'], $j['endTime']);
            $j['startActivity'] = strtotime(date("Y-m-d 00:00:00", $j['startDateTime']));
            $j['endActivity'] = strtotime(date("Y-m-d 23:59:59", $j['startDateTime']));
            $jadwal[] = $j;
        }
        return $this->respond($jadwal);
    }


    public function praktek($jadwalID)
    {
        $db = db_connect();
        $isExist = (new Jadwal())->getJadwalMengajar(base64_decode($jadwalID));
        if (!$isExist) return view("Utils/404");
        if ($isExist['is_libur'] == 1) return view("Utils/404");
        $jadwalID = base64_decode($jadwalID);
        if (!$isExist['agenda_exist']) {
            $db->transStart();
            $db->table('agenda_kegiatan')->insert([
                'user_id' => user()->id,
                'jadwal_id' => $jadwalID,
                'created_at' => time(),
                'updated_at' => time()
            ]);
            $SQsiswa = $db->table('jadwal_absensi_siswa jas');
            $SQsiswa->select('jas.siswa_id')->where('jas.siswa_id', 'ms.id', false);
            $SQsiswa = $SQsiswa->where([
                'jadwal_id' => $jadwalID,
                "created_at >=" => strtotime(date('Y-m-d 00:00:00')),
                "created_at <=" => strtotime(date('Y-m-d 23:59:59'))
            ])->getCompiledSelect();
            $now = time();
            $Qsiswa = $db->table('m_siswa ms')->select("$isExist[id] jadwal_id,ms.id,$now created_at,$now updated_at");
            $Qsiswa->where(['kelas_id' => $isExist['kelas_id'], "(CASE WHEN NOT EXISTS ($SQsiswa) THEN 0 ELSE 1 END) =" => 0], null, false);
            $Qsiswa = $Qsiswa->getCompiledSelect();
            $sql = "INSERT INTO jadwal_absensi_siswa(jadwal_id,siswa_id,created_at,updated_at) $Qsiswa";
            $db->query($sql);
            $db->transComplete();
            if ($db->transStatus() === FALSE) return view("Utils/404");
        }
        return view('Panel/Elearning/JadwalMengajar/praktek', ['page_title' => "Mengajar - $isExist[nama_mapel] - $isExist[nama_kelas]"]);
    }
}
