<?php

namespace App\Controllers\Panel\Elearning;

use App\Controllers\Panel\BC;
use App\Models\Panel\Elearning\KompetensiDasar as ElearningKompetensiDasar;
use App\Models\Panel\MasterData\MataPelajaran;
use App\Models\Panel\MasterData\Tingkat;
use CodeIgniter\API\ResponseTrait;

class KompetensiDasar extends BC
{
    use ResponseTrait;
    private $KDModel;
    public function __construct()
    {
        parent::__construct();
        $this->KDModel = new ElearningKompetensiDasar();
    }
    public function index()
    {
        return view('Panel/Elearning/KompetensiDasar/index', ['page_title' => "Kompetensi Dasar"]);
    }
    public function all()
    {
        if (!$this->request->isAJAX() && ENVIRONMENT != 'development') {
            exit('No direct script access allowed');
        }
        $opt = [];
        if (!user()->hasRole('admin')) {
            $myClass = db_connect()->table('jadwal_pelajaran jp')->select("DISTINCT GROUP_CONCAT(kd.tingkat_id,'-',jp.mapel_id) tingmap");
            $myClass->join('kelas_data kd', 'kd.kelas_id=jp.kelas_id');
            $myClass->where('user_id', user()->id);
            $myClass = $myClass->get()->getRowArray();
            $myClass = explode(',', ($myClass['tingmap'] ?? ""));
            $opt['tingmap'] = $myClass;
        }
        if ($this->request->getGet('tingkat_id')) {
            $opt['tingkat_id'] = $this->request->getGet('tingkat_id');
        }
        if ($this->request->getGet('mapel_id')) {
            $opt['mapel_id'] = $this->request->getGet('mapel_id');
        }
        $data = $this->KDModel->getAll($opt);
        return $this->respond(['data' => $data, "csrf" =>  csrf_hash()]);
    }
    public function detail($id)
    {
        if (!$this->request->isAJAX() && ENVIRONMENT != 'development') {
            exit('No direct script access allowed');
        }
        if (!user()->hasRole('admin')) {
            $data =   $this->KDModel->where('user_id', user()->id)->find($id);
        } else {
            $data = $this->KDModel->find($id);
        }
        return $this->respond(['data' => $data]);
    }
    public function delete($id)
    {
        if (!$this->request->isAJAX() && ENVIRONMENT != 'development') {
            exit('No direct script access allowed');
        }
        $state = $this->KDModel->delete($id);
        return $this->respond(['deleted' => $state, 'message' => $state ? "Berhasil Menghapus" : "Gagal Menghapus"]);
    }
    public function config()
    {
        if (!$this->request->isAJAX() && ENVIRONMENT != 'development') {
            exit('No direct script access allowed');
        }
        $opt = [
            'fieldGuru' => user()->hasRole('admin') ? true : false
        ];
        return $this->respond($opt);
    }

    public function edit($id)
    {
        if (!$this->request->isAJAX() && ENVIRONMENT != 'development') {
            exit('No direct script access allowed');
        }

        $rules['nomor'] = [
            "alias" => "Nomor",
            'rules' => "integer|max_length[32]|greater_than[0]",
            'errors' => [
                'integer' => 'Karakter Tidak Valid',
                'max_length' => 'Maksimal 32 Karakter',
                'greater_than' => "Nomor harus lebih dari 0"
            ]
        ];
        $rules['nama'] = [
            "alias" => "Nama",
            'rules' => 'string|max_length[255]',
            'errors' => [
                'string' => '{value} Karakter Tidak Valid',
                'max_length' => '{value} Maksimal 255 Karakter'
            ]
        ];
        $rules['kode'] = [
            "alias" => "Kode",
            'rules' => 'string|in_list[KP,KK]',
            'errors' => [
                'string' => '{value} Karakter Tidak Valid',
                'in_list' => '{value} Tidak Valid!. Kode Hanya Boleh KP dan KK'
            ]
        ];
        $rules['mapel_id'] = [
            "alias" => "Mata Pelajaran",
            'rules' => 'integer|required',
            'errors' => [
                'integer' => '{value} Karakter Tidak Valid',
                'required' => 'Dibutuhkan'
            ]
        ];
        $rules['tingkat_id'] = [
            "alias" => "Tingkat",
            'rules' => 'integer|required',
            'errors' => [
                'integer' => '{value} Karakter Tidak Valid',
                'required' => 'Dibutuhkan'
            ]
        ];

        if (user()->hasRole('admin')) {
            $rules['user_id'] = [
                "alias" => "Guru",
                'rules' => 'integer|required',
                'errors' => [
                    'integer' => '{value} Karakter Tidak Valid',
                    'required' => '{value} Guru Dibutuhkan'
                ]
            ];
        }
        if (!$this->validate($rules)) {
            $errors = $this->validator->getErrors();
            $err = '';
            foreach ($errors as $key => $error) {
                $err = $err . $rules[$key]['alias'] . " : " . $error . '<br>';
            }
            return $this->fail(["csrf" => csrf_hash(), 'message' => $err]);
        }

        $data = [
            "nomor" => $this->request->getVar('nomor'),
            "nama" => $this->request->getVar('nama'),
            "kode" => $this->request->getVar('kode'),
            "mapel_id" => $this->request->getVar('mapel_id'),
            "tingkat_id" => $this->request->getVar('tingkat_id'),
        ];

        if (user()->hasRole('admin')) {
            $data['user_id'] = $this->request->getVar('user_id');
        } else {
            $data['user_id'] = user()->id;
        }

        $db =  db_connect();
        $getNomorInSameCategory = $db->table('kompetensi_dasar kd');
        $getNomorInSameCategory->select("GROUP_CONCAT(kd.nomor ORDER BY kd.nomor ASC) nomor");
        $getNomorInSameCategory->where(['kode' => "'$data[kode]'", 'id !=' => $id,  'tingkat_id' => $data['tingkat_id'], 'mapel_id' => $data['mapel_id']], null, false);

        $other = $db->table('kompetensi_dasar kd');
        $other->select("*,({$getNomorInSameCategory->getCompiledSelect()}) nomors", false);
        $other->where(['nomor' => $data['nomor'], 'id !=' => $id, 'kode' => "'$data[kode]'", 'tingkat_id' => $data['tingkat_id'], 'mapel_id' => $data['mapel_id']], null, false);
        $other = $other->get()->getRowArray();
        if ($other) {
            $nomors = explode(',', $other['nomors'] ?? '');
            $availNomor = $data['nomor'] + 1;
            if ($nomors) {
                foreach ($nomors as $k => $nomor) {
                    if ($nomor + 1 != ($nomors[$k + 1] ?? $nomor)) {
                        $availNomor = $nomor + 1;
                        break;
                    }
                }
            }
            if ($availNomor != 1 && $data['nomor'] != 1 && !in_array(1, $nomors)) $availNomor = 1;
            return $this->fail(["csrf" => csrf_hash(), 'message' => "Nomor '$data[nomor]' tidak tersedia,nomor '$availNomor' masih tersedia untuk digunakan"]);
        }


        $updated = $this->KDModel->update($id, $data);
        if (!$updated) return $this->fail(["csrf" => csrf_hash(), 'message' => 'Gagal Mengubah Kompetensi Dasar']);
        return $this->respond(["csrf" => csrf_hash(), 'message' => 'Berhasil Mengubah Kompetensi Dasar']);
    }
    public function add()
    {
        if (!$this->request->isAJAX() && ENVIRONMENT != 'development') {
            exit('No direct script access allowed');
        }

        $rules['nomor'] = [
            "alias" => "Nomor",
            'rules' => 'integer|max_length[32]|greater_than[0]',
            'errors' => [
                'integer' => 'Karakter Tidak Valid',
                'max_length' => 'Maksimal 32 Karakter',
                'greater_than' => "Nomor harus lebih dari 0"
            ]
        ];
        $rules['nama'] = [
            "alias" => "Nama",
            'rules' => 'string|max_length[255]',
            'errors' => [
                'string' => '{value} Karakter Tidak Valid',
                'max_length' => '{value} Maksimal 255 Karakter'
            ]
        ];
        $rules['kode'] = [
            "alias" => "Kode",
            'rules' => 'string|in_list[KP,KK]',
            'errors' => [
                'string' => '{value} Karakter Tidak Valid',
                'in_list' => '{value} Tidak Valid!. Kode Hanya Boleh KP dan KK'
            ]
        ];
        $rules['mapel_id'] = [
            "alias" => "Mata Pelajaran",
            'rules' => 'integer|required',
            'errors' => [
                'integer' => '{value} Karakter Tidak Valid',
                'required' => 'Dibutuhkan'
            ]
        ];
        $rules['tingkat_id'] = [
            "alias" => "Tingkat",
            'rules' => 'integer|required',
            'errors' => [
                'integer' => '{value} Karakter Tidak Valid',
                'required' => 'Dibutuhkan'
            ]
        ];

        if (user()->hasRole('admin')) {
            $rules['user_id'] = [
                "alias" => "Guru",
                'rules' => 'integer|required',
                'errors' => [
                    'integer' => '{value} Karakter Tidak Valid',
                    'required' => '{value} Guru Dibutuhkan'
                ]
            ];
        }
        if (!$this->validate($rules)) {
            $errors = $this->validator->getErrors();
            $err = '';
            foreach ($errors as $key => $error) {
                $err = $err . $rules[$key]['alias'] . " : " . $error . '<br>';
            }
            return $this->fail(["csrf" => csrf_hash(), 'message' => $err]);
        }
        $data = [
            "nomor" => $this->request->getVar('nomor'),
            "nama" => $this->request->getVar('nama'),
            "kode" => $this->request->getVar('kode'),
            "mapel_id" => $this->request->getVar('mapel_id'),
            "tingkat_id" => $this->request->getVar('tingkat_id'),
        ];
        if (user()->hasRole('admin')) {
            $data['user_id'] = $this->request->getVar('user_id');
        } else {
            $data['user_id'] = user()->id;
        }


        $db = db_connect();
        $getNomorInSameCategory = $db->table('kompetensi_dasar kd');
        $getNomorInSameCategory->select("GROUP_CONCAT(kd.nomor ORDER BY kd.nomor ASC) nomor");
        $getNomorInSameCategory->where(['kode' => "'$data[kode]'", 'tingkat_id' => $data['tingkat_id'], 'mapel_id' => $data['mapel_id']], null, false);

        $other = $db->table('kompetensi_dasar kd');
        $other->select("*,({$getNomorInSameCategory->getCompiledSelect()}) nomors", false);
        $other->where(['nomor' => $data['nomor'], 'kode' => "'$data[kode]'", 'tingkat_id' => $data['tingkat_id'], 'mapel_id' => $data['mapel_id']], null, false);
        $other = $other->get()->getRowArray();
        if ($other) {
            $nomors = explode(',', $other['nomors'] ?? '');
            $availNomor = $data['nomor'] + 1;
            if ($nomors) {
                foreach ($nomors as $k => $nomor) {
                    if ($nomor + 1 != ($nomors[$k + 1] ?? $nomor)) {
                        $availNomor = $nomor + 1;
                        break;
                    }
                }
            }
            if ($availNomor != 1 && $data['nomor'] != 1 && !in_array(1, $nomors)) $availNomor = 1;
            return $this->fail(["csrf" => csrf_hash(), 'message' => "Nomor '$data[nomor]' tidak tersedia,nomor '$availNomor' masih tersedia untuk digunakan"]);
        }

        $id = $this->KDModel->insert($data);
        if (!$id) return $this->fail(["csrf" => csrf_hash(), 'message' => 'Gagal Menambah Kompetensi Dasar']);
        return $this->respond(["csrf" => csrf_hash(), 'message' => 'Berhasil Menambah Kompetensi Dasar']);
    }

    public function mapel()
    {
        if (!$this->request->isAJAX() && ENVIRONMENT != 'development') {
            exit('No direct script access allowed');
        }
        if (user()->hasRole('admin')) {
            $data = (new MataPelajaran())->findAll();
            return $this->respond(['data' => $data]);
        }
        $db = db_connect();
        $builder = $db->table('m_mapel mm')->select('mm.*');
        $builder->distinct(true);
        $builder->join('jadwal_pelajaran jp', 'jp.mapel_id=mm.id');
        $builder->join('tahun_pelajaran tp', 'tp.id=jp.tahun_id');
        $builder->where('jp.user_id', user()->id);
        $builder->where('tp.is_active', 1);
        $data = $builder->get()->getResultArray();
        return $this->respond(['data' => $data]);
    }

    public function tingkat()
    {
        if (!$this->request->isAJAX() && ENVIRONMENT != 'development') {
            exit('No direct script access allowed');
        }
        if (user()->hasRole('admin')) {
            $data = (new Tingkat())->findAll();
            return $this->respond(['data' => $data]);
        }
        $db = db_connect();
        $builder = $db->table('m_tingkat mt')->select('mt.*');
        $builder->distinct(true);
        $builder->join('kelas_data kd', 'kd.tingkat_id=mt.id');
        $builder->join('jadwal_pelajaran jp', 'jp.kelas_id=kd.kelas_id');
        $builder->join('tahun_pelajaran tp', 'tp.id=jp.tahun_id');
        $builder->where('jp.user_id', user()->id);
        $builder->where('tp.is_active', 1);
        $data = $builder->get()->getResultArray();
        return $this->respond(['data' => $data]);
    }
}
