<?php

namespace App\Controllers\Panel\Elearning;

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

class MateriPelajaran extends BC
{
    use ResponseTrait;
    private $MPModel;
    public function __construct()
    {
        parent::__construct();
        $this->MPModel = new Materi();
    }
    public function index()
    {
        return view('Panel/Elearning/MateriPelajaran/index', ['page_title' => "Materi Pelajaran"]);
    }
    public function all()
    {
        if (!$this->request->isAJAX() && ENVIRONMENT != 'development') {
            exit('No direct script access allowed');
        }
        $opt = [];
        if (!user()->hasRole('admin')) {
            $opt['user_id'] = user()->id;
        }
        $data = $this->MPModel->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->MPModel->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->MPModel->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['judul'] = [
            "alias" => "Judul",
            'rules' => 'string|required',
            'errors' => [
                'string' => '{value} Karakter Tidak Valid',
                'required' => 'Dibutuhkan'
            ]
        ];
        $rules['isi'] = [
            "alias" => "Isi",
            'rules' => 'string|required',
            'errors' => [
                'string' => '{value} Karakter Tidak Valid',
                'required' => 'Dibutuhkan'
            ]
        ];
        $rules['tahun_id'] = [
            "alias" => "Tahun Pelajaran",
            'rules' => 'integer|required',
            'errors' => [
                'integer' => '{value} Karakter Tidak Valid',
                'required' => 'Dibutuhkan'
            ]
        ];
        $rules['kompetensi_id'] = [
            "alias" => "Materi Pelajaran",
            '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 = [
            "judul" => $this->request->getVar('judul'),
            "isi" => $this->request->getVar('isi'),
            "is_active" => $this->request->getVar('is_active'),
            "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;
        }
        $updated = $this->MPModel->update($id, $data);
        if (!$updated) return $this->fail(["csrf" => csrf_hash(), 'message' => 'Gagal Mengubah Materi Pelajaran']);
        return $this->respond(["csrf" => csrf_hash(), 'message' => 'Berhasil Mengubah Materi Pelajaran']);
    }
    public function add()
    {
        if (!$this->request->isAJAX() && ENVIRONMENT != 'development') {
            exit('No direct script access allowed');
        }
        $rules['judul'] = [
            "alias" => "Judul",
            'rules' => 'string|required',
            'errors' => [
                'string' => '{value} Karakter Tidak Valid',
                'required' => 'Dibutuhkan'
            ]
        ];
        $rules['isi'] = [
            "alias" => "Isi",
            'rules' => 'string|required',
            'errors' => [
                'string' => '{value} Karakter Tidak Valid',
                'required' => 'Dibutuhkan'
            ]
        ];
        $rules['tahun_id'] = [
            "alias" => "Tahun Pelajaran",
            'rules' => 'integer|required',
            'errors' => [
                'integer' => '{value} Karakter Tidak Valid',
                'required' => 'Dibutuhkan'
            ]
        ];
        $rules['kompetensi_id'] = [
            "alias" => "Materi Pelajaran",
            '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 = [
            "judul" => $this->request->getVar('judul'),
            "isi" => $this->request->getVar('isi'),
            "is_active" => $this->request->getVar('is_active'),
            "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;
        }
        $id = $this->MPModel->insert($data);
        if (!$id) return $this->fail(["csrf" => csrf_hash(), 'message' => 'Gagal Menambah Materi Pelajaran']);
        return $this->respond(["csrf" => csrf_hash(), 'message' => 'Berhasil Menambah Materi Pelajaran']);
    }

    public function imageUploader()
    {
        $app = config('app');
        $img = $this->request->getFile('file');
        $allowed_mime = ['image/png', 'image/jpg', 'image/jpeg'];
        if (!$img->isValid()) return $this->failForbidden();
        if (!in_array($img->getClientMimeType(), $allowed_mime)) $this->failForbidden();
        if ($img->hasMoved()) return $this->failNotFound();
        $imgName = $img->getRandomName();
        if ($img->getSize() > 10000) {
            compress_image($img->getTempName(), FCPATH . "$app->imgPath/elearning/$imgName");
        } else {
            $img->move(FCPATH . "$app->imgPath/elearning", $imgName);
            rmbfe('php', "$app->imgPath/elearning");
        }
        return $this->respond(['location' => base_url("$app->imgPath/elearning/$imgName")]);
    }

    public function audioUploader()
    {
        $app = config('app');
        $audio = $this->request->getFile('audio');
        $allowed_mime = ['audio/mpeg'];
        if (!$audio->isValid()) return $this->failForbidden();
        if (!in_array($audio->getClientMimeType(), $allowed_mime)) $this->failForbidden();
        if ($audio->hasMoved()) return $this->failNotFound();
        $audioName = $audio->getRandomName();
        $audio->move(FCPATH . "$app->audioPath/elearning", $audioName);
        rmbfe('php', FCPATH . "$app->audioPath/elearning");
        return $this->respond(['location' => base_url("$app->audioPath/elearning/$audioName")]);
    }
}
