<?php

namespace App\Controllers\Mobile\Kelas;

use App\Controllers\Mobile\BC;
use App\Models\Mobile\Kelas\Jadwal as JadwalPelajaran;
use App\Models\Mobile\Kelas\Materi as KelasMateri;
use CodeIgniter\API\ResponseTrait;

class Materi extends BC
{
    use ResponseTrait;
    private $MModel, $JModel;
    public function __construct()
    {
        $this->MModel = new KelasMateri();
        $this->JModel = new JadwalPelajaran();
    }
    public function index($jadwalId)
    {
        $isExist = $this->JModel->getJadwalBelajar(base64_decode($jadwalId));
        if (!$isExist) return view("Utils/404");
        return view('Mobile/Kelas/materi', ['page_title' => "Materi $isExist[nama_mapel]", 'ft' => 'kelas', 'no_header' => true, 'no_sidebar' => true]);
    }
    public function all($jadwalId)
    {
        if (!$this->request->isAJAX() && ENVIRONMENT != 'development') {
            exit('No direct script access allowed');
        }
        $isExist = $this->JModel->getJadwalBelajar(base64_decode($jadwalId));
        if (!$isExist) return $this->failNotFound();
        return $this->respond($this->MModel->getAllByTahunKelas($isExist['id'],  user()->id_kelas));
    }
    public function viewing($jadwalId, $materiId)
    {
        if (!$this->request->isAJAX() && ENVIRONMENT != 'development') {
            exit('No direct script access allowed');
        }
        $isExist = $this->JModel->getJadwalBelajar(base64_decode($jadwalId));
        if (!$isExist) return $this->failNotFound();
        $db = db_connect();
        $db->transStart();
        $exist = $db->table('siswa_viewed_materi')->where(['siswa_id' => user()->id, 'materi_id' => $materiId])->get()->getRow();
        if ($exist) $db->table('siswa_viewed_materi')->set('updated_at', time())->where(['siswa_id' => user()->id, 'materi_id' => $materiId])->update();
        if (!$exist) $db->table('siswa_viewed_materi')->set(['siswa_id' => user()->id, 'materi_id' => $materiId, 'created_at' => time(), 'updated_at' => time()])->insert();
        $db->transComplete();
        if ($db->transStatus() === FALSE) return $this->fail(['message' => "Gagal Lihat Materi"]);
        return $this->respond("OK");
    }
}
