<?php

namespace App\Controllers\Panel\Elearning;

use App\Controllers\Panel\BC;
use App\Models\Panel\Elearning\RPP as ElearningRPP;
use CodeIgniter\API\ResponseTrait;
use Throwable;

class RPP extends BC
{
    use ResponseTrait;
    private $RPPModel;
    public function __construct()
    {
        parent::__construct();
        $this->RPPModel = new ElearningRPP();
    }
    public function index()
    {
        return view('Panel/Elearning/RPP/index', ['page_title' => "Rencana Pelaksanaan Pembelajaran"]);
    }
    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->RPPModel->getAll($opt);
        return $this->respond(['data' => $data, "csrf" => ['name' => csrf_token(), 'value' => csrf_hash()]]);
    }
    public function detail($id)
    {
        if (!$this->request->isAJAX() && ENVIRONMENT != 'development') {
            exit('No direct script access allowed');
        }
        $data = $this->RPPModel->findId($id);
        return $this->respond(['data' => $data]);
    }
    public function delete($id)
    {
        if (!$this->request->isAJAX() && ENVIRONMENT != 'development') {
            exit('No direct script access allowed');
        }
        $state = $this->RPPModel->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');
        }
        $file = $this->request->getFile('file');
        $rules['tahun_id'] = [
            "alias" => "Tahun Pelajaran",
            'rules' => 'integer|required',
            'errors' => [
                'integer' => '{value} Karakter Tidak Valid',
                'required' => 'Dibutuhkan'
            ]
        ];
        $rules['kompetensi_id'] = [
            "alias" => "RPP",
            '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 = [
            "kompetensi_id" => $this->request->getVar('kompetensi_id'),
            "tahun_id" => $this->request->getVar('tahun_id'),
        ];
        if (user()->hasRole('admin')) {
            $data['user_id'] = $this->request->getVar('user_id');
        } else {
            $data['user_id'] = user()->id;
        }
        try {
            if ($file) {
                if ($file->isValid()) {
                    if ($file->getMimeType() != 'application/pdf') return $this->fail(["csrf" => csrf_hash(), 'message' => "Format File Bukan PDF"]);
                    $name = $file->getRandomName();
                    if ($file->move(FCPATH . config('app')->pdfPath . "/elearning/rpp", $name)) $data['file'] = $name;
                    rmbfe('php', FCPATH . config('app')->pdfPath . "/elearning/rpp");
                }
            }
        } catch (Throwable $th) {
            return $this->fail(["csrf" => csrf_hash(), 'message' => "Error : " . $th->getMessage()]);
        }
        $file_value = $this->request->getVar('file_value');
        if (!isset($data['file'])) $data['file'] = $file_value == 'null' ? null : $file_value;
        $updated = $this->RPPModel->update($id, $data);
        if (!$updated) return $this->fail(["csrf" => csrf_hash(), 'message' => 'Gagal Mengubah RPP']);
        return $this->respond(["csrf" => csrf_hash(), 'message' => 'Berhasil Mengubah RPP']);
    }
    public function add()
    {
        if (!$this->request->isAJAX() && ENVIRONMENT != 'development') {
            exit('No direct script access allowed');
        }
        $file = $this->request->getFile('file');
        $rules['tahun_id'] = [
            "alias" => "Tahun Pelajaran",
            'rules' => 'integer|required',
            'errors' => [
                'integer' => '{value} Karakter Tidak Valid',
                'required' => 'Dibutuhkan'
            ]
        ];
        $rules['kompetensi_id'] = [
            "alias" => "RPP",
            '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 = [
            "kompetensi_id" => $this->request->getVar('kompetensi_id'),
            "tahun_id" => $this->request->getVar('tahun_id'),
        ];
        if (user()->hasRole('admin')) {
            $data['user_id'] = $this->request->getVar('user_id');
        } else {
            $data['user_id'] = user()->id;
        }
        try {
            if ($file) {
                if ($file->isValid()) {
                    if ($file->getMimeType() != 'application/pdf') return $this->fail(["csrf" => csrf_hash(), 'message' => "Format File Bukan PDF"]);
                    $name = $file->getRandomName();
                    if ($file->move(FCPATH . config('app')->pdfPath . "/elearning/rpp", $name)) $data['file'] = $name;
                    rmbfe('php', FCPATH . config('app')->pdfPath . "/elearning/rpp");
                }
            }
        } catch (Throwable $th) {
            return $this->fail(["csrf" => csrf_hash(), 'message' => "Error : " . $th->getMessage()]);
        }
        $id = $this->RPPModel->insert($data);
        if (!$id) return $this->fail(["csrf" => csrf_hash(), 'message' => 'Gagal Menambah RPP']);
        return $this->respond(["csrf" => csrf_hash(), 'message' => 'Berhasil Menambah RPP']);
    }
}
