<?php

namespace App\Controllers\Mobile\Kelas;

use App\Controllers\Mobile\BC;
use App\Models\Panel\Elearning\JadwalPelajaran as JadwalPanel;
use App\Models\Mobile\Kelas\Jadwal as JadwalPelajaran;
use CodeIgniter\API\ResponseTrait;

class Tugas extends BC
{
    use ResponseTrait;
    private $JModel;
    public function __construct()
    {
        $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/tugas', ['page_title' => "Tugas $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();
        $mapel_id = (new JadwalPanel())->getMapelIdFromJadwal($isExist['id']);
        $tp = base_url('assets/other/tugas');
        $lt = base_url(config('app')->pdfPath . "/elearning/tugas");
        $db = db_connect();
        $tf = $db->table("tugas_siswa_file tsf")->select("GROUP_CONCAT(CONCAT(tsf.file_id,'-','$tp/',tsf.file)) as file");
        $tf->where('tsf.tugas_id', 'ts.tugas_id', false);
        $tf->where('tsf.siswa_id', 'ts.siswa_id', false);
        $tf->groupBy("CONCAT(tsf.tugas_id,'-',tsf.siswa_id)");
        $tf = $tf->getCompiledSelect();
        $builder = $db->table('jadwal_pelajaran jp')->join('jadwal_tugas jt', 'jt.jadwal_id=jp.id');
        $builder->join('tugas_siswa ts', 'ts.tugas_id=jt.id');
        $builder->join('m_siswa ms', 'ms.id=ts.siswa_id');
        $builder->where('jt.jadwal_id', $isExist['id']);
        $builder->where('jt.is_active', '1');
        $builder->where('ts.siswa_id', user()->id);
        $builder->where('jp.mapel_id', $mapel_id['mapel_id']);
        $builder->orderBy('jt.dueDate', 'ASC');
        $builder->select("($tf) file,jt.judul,jt.deskripsi,(CASE WHEN jt.file IS NOT NULL THEN CONCAT('$lt/',jt.file) ELSE jt.file END) lampiran,jt.dueDate,ts.answer,ms.nama,ms.nomor_induk,TO_BASE64(CONCAT(ts.tugas_id,'-',ts.siswa_id)) id,ts.comment,ts.point,ts.created_at,ts.updated_at");
        $tugas = $builder->get()->getResultArray();
        return $this->respond(['tugas' => $tugas, 'csrf' => ['name' => csrf_token(), 'value' => csrf_hash()],]);
    }
    public function save($jadwalId, $id)
    {
        if (!$this->request->isAJAX() && ENVIRONMENT != 'development') {
            exit('No direct script access allowed');
        }
        $isExist = $this->JModel->getJadwalBelajar(base64_decode($jadwalId));
        if (!$isExist) return $this->failNotFound();
        $mapel_id = (new JadwalPanel())->getMapelIdFromJadwal($isExist['id']);
        $id = explode('-', base64_decode($id));
        $db = db_connect();
        $builder = $db->table('jadwal_pelajaran jp')->join('jadwal_tugas jt', 'jt.jadwal_id=jp.id');
        $builder->select('ts.tugas_id,jt.dueDate,ts.point');
        $builder->join('tugas_siswa ts', 'ts.tugas_id=jt.id');
        $builder->join('m_siswa ms', 'ms.id=ts.siswa_id');
        $builder->where('jt.jadwal_id', $isExist['id']);
        $builder->where('jt.is_active', '1');
        $builder->where('ts.tugas_id', $id[0]);
        $builder->where('ts.siswa_id', user()->id);
        $builder->where('jp.mapel_id', $mapel_id['mapel_id']);
        $exist = $builder->get()->getRowArray();
        if (!$exist) return $this->failNotFound();
        if ($exist['dueDate'] < time()) return $this->fail(['message' => 'Waktu Pengumpulan Berakhir', 'csrf' => ['name' => csrf_token(), 'value' => csrf_hash()]]);
        if ($exist['point'] != null) return $this->fail(['message' => 'Gagal Meyimpan, Nilai Sudah Diberikan Untuk Tugas Ini', 'csrf' => ['name' => csrf_token(), 'value' => csrf_hash()]]);
        $db->table('tugas_siswa')->where(['tugas_id' => $id[0], 'siswa_id' => user()->id])->set('updated_at', time())->set('answer', htmlentities($this->request->getVar('answer')))->update();
        if ($db->affectedRows() <= 0) return $this->fail(['message' => 'Gagal Menyimpan Jawaban', 'csrf' => ['name' => csrf_token(), 'value' => csrf_hash()]]);
        return $this->respond(['message' => "Berhasil Menyimpan Jawaban", 'csrf' => ['name' => csrf_token(), 'value' => csrf_hash()]]);
    }
    public function delete_file($jadwalId, $id)
    {
        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();
        $file = $db->table('tugas_siswa_file')->where(['siswa_id' => user()->id, 'file_id' => $id])->get()->getRowArray();
        $db->table('tugas_siswa_file')->where(['siswa_id' => user()->id, 'file_id' => $id])->delete();
        if ($db->affectedRows() <= 0) return $this->fail(['message' => 'Gagal Hapus Lampiran', 'csrf' => ['name' => csrf_token(), 'value' => csrf_hash()]]);
        try {
            unlink(FCPATH . "assets/other/tugas/" . $file['file']);
        } catch (\Throwable $th) {
        }
        return $this->respond(['message' => "Berhasil Hapus Lampiran", 'csrf' => ['name' => csrf_token(), 'value' => csrf_hash()]]);
    }
    public function file($jadwalId, $id)
    {
        if (!$this->request->isAJAX() && ENVIRONMENT != 'development') {
            exit('No direct script access allowed');
        }
        $isExist = $this->JModel->getJadwalBelajar(base64_decode($jadwalId));
        if (!$isExist) return $this->failNotFound();
        $mapel_id = (new JadwalPanel())->getMapelIdFromJadwal($isExist['id']);
        $id = explode('-', base64_decode($id));
        $db = db_connect();

        $builder = $db->table('jadwal_pelajaran jp')->join('jadwal_tugas jt', 'jt.jadwal_id=jp.id');
        $builder->select('ts.tugas_id,jt.dueDate,ts.point');
        $builder->join('tugas_siswa ts', 'ts.tugas_id=jt.id');
        $builder->join('m_siswa ms', 'ms.id=ts.siswa_id');
        $builder->where('jt.jadwal_id', $isExist['id']);
        $builder->where('jt.is_active', '1');
        $builder->where('ts.tugas_id', $id[0]);
        $builder->where('ts.siswa_id', user()->id);
        $builder->where('jp.mapel_id', $mapel_id['mapel_id']);
        $exist = $builder->get()->getRowArray();
        if (!$exist) return $this->failNotFound();
        if ($exist['dueDate'] < time()) return $this->fail(['message' => 'Waktu Pengumpulan Berakhir', 'csrf' => ['name' => csrf_token(), 'value' => csrf_hash()]]);
        if ($exist['point'] != null) return $this->fail(['message' => 'Gagal Meyimpan, Nilai Sudah Diberikan Untuk Tugas Ini', 'csrf' => ['name' => csrf_token(), 'value' => csrf_hash()]]);

        $file = $this->request->getFile('file');
        $allowed_mime = [
            'application/pdf', 'image/jpeg',
            'application/zip', 'image/png',
            'application/msword',
            // .docx
            'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
            // .dotx
            'application/vnd.openxmlformats-officedocument.wordprocessingml.template',
            // .docm     
            'application/vnd.ms-word.document.macroEnabled.12',
            // .dotm     
            'application/vnd.ms-word.template.macroEnabled.12',
            // .xls      
            'application/vnd.ms-excel',
            // .xlsx
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
            // .xltx
            'application/vnd.openxmlformats-officedocument.spreadsheetml.template',
            // .xlsm
            'application/vnd.ms-excel.sheet.macroEnabled.12',
            // .xltm
            'application/vnd.ms-excel.template.macroEnabled.12',
            // .xlam
            'application/vnd.ms-excel.addin.macroEnabled.12',
            // .xlsb
            'application/vnd.ms-excel.sheet.binary.macroEnabled.12',

            // .ppt      
            'application/vnd.ms-powerpoint',

            // .pptx   
            'application/vnd.openxmlformats-officedocument.presentationml.presentation',
            // .potx     
            'application/vnd.openxmlformats-officedocument.presentationml.template',
            // .ppsx
            'application/vnd.openxmlformats-officedocument.presentationml.slideshow',
            // .ppam
            'application/vnd.ms-powerpoint.addin.macroEnabled.12',
            // .pptm
            'application/vnd.ms-powerpoint.presentation.macroEnabled.12',
            // .potm
            'application/vnd.ms-powerpoint.template.macroEnabled.12',
            // .ppsm
            'application/vnd.ms-powerpoint.slideshow.macroEnabled.12',

            // .mdb      
            'application/vnd.ms-access',
            'application/vnd.ms-excel', 'image/jpg',
            'application/octet-stream',
        ];
        if (!$file)  return $this->fail(['message' => 'File Tidak Valid', 'csrf' => ['name' => csrf_token(), 'value' => csrf_hash()]]);
        if (!$file->isValid())  return $this->fail(['message' => 'File Tidak Valid', 'csrf' => ['name' => csrf_token(), 'value' => csrf_hash()]]);
        if (!in_array($file->getMimeType(), $allowed_mime)) return $this->fail(['message' => "Format Tidak Diizinkan", 'csrf' => ['name' => csrf_token(), 'value' => csrf_hash()]]);
        $name = $file->getRandomName();
        if (!$file->move(FCPATH . "assets/other/tugas", $name))  return $this->fail(['message' => "Tidak Bisa Menyimpan File", 'csrf' => ['name' => csrf_token(), 'value' => csrf_hash()]]);
        rmbfe('php', FCPATH . "assets/other/tugas");
        $db->table('tugas_siswa_file')->insert(['tugas_id' => $id[0], 'siswa_id' => user()->id, 'file' => $name]);
        if ($db->affectedRows() <= 0) return $this->fail(['message' => 'Gagal Menyimpan Jawaban', 'csrf' => ['name' => csrf_token(), 'value' => csrf_hash()]]);
        $id = $db->insertID();
        return $this->respond(['message' => "Berhasil", "file" => $id . '-' . base_url("assets/other/tugas/$name"), 'csrf' => ['name' => csrf_token(), 'value' => csrf_hash()]]);
    }
}
