<?php

namespace App\Controllers\Panel\Elearning;

use App\Controllers\Panel\BC;
use App\Models\Panel\Elearning\JadwalPelajaran as ElearningJadwalPelajaran;
use CodeIgniter\API\ResponseTrait;

class JadwalPelajaran extends BC
{
    use ResponseTrait;
    private $JPModel;
    public function __construct()
    {
        parent::__construct();
        $this->JPModel = new ElearningJadwalPelajaran();
    }
    public function index()
    {
        return view('Panel/Elearning/JadwalPelajaran/index', ['page_title' => "Jadwal 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;
        }
        if ($this->request->getGet('kelas_id') && $this->request->getGet('kelas_id') != 'all') {
            $opt['kelas_id'] = $this->request->getGet('kelas_id');
        }
        if ($this->request->getGet('tahun_id')) {
            $opt['tahun_id'] = $this->request->getGet('tahun_id');
        }
        $data = [];
        foreach ($this->JPModel->getAll($opt) as $d) {
            $ed = $d['startTime'] > $d['endTime'] ? $d['startDay'] + 1 : $d['startDay'];
            $ed = $ed > 7 ? 1 : $ed;
            if (($this->request->getGet('startTime') && $this->request->getGet('endTime')) && !(get_time($d['startDay']) >= $this->request->getGet('startTime') && get_time($d['startDay'], $d['startTime'] > $d['endTime'] ? $d['endTime'] : "00:00:00") <= $this->request->getGet('endTime'))) continue;
            $d['startDateTime'] = get_time($d['startDay'], $d['startTime']);
            $d['endDateTime'] = get_time($ed, $d['endTime']);
            $data[] = $d;
        }
        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->JPModel->findId($id);
        if (!$data) return $this->failNotFound();
        $ed = $data['startTime'] > $data['endTime'] ? $data['startDay'] + 1 : $data['startDay'];
        $ed = $ed > 7 ? 1 : $ed;
        $data['startDateTime'] = get_time($data['startDay'], $data['startTime']);
        $data['endDateTime'] = get_time($ed, $data['endTime']);
        $data['startDay'] -= 1;
        return $this->respond(['data' => $data]);
    }
    public function delete($id)
    {
        if (!$this->request->isAJAX() && ENVIRONMENT != 'development') {
            exit('No direct script access allowed');
        }
        $state = $this->JPModel->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['countJam'] = [
            "alias" => "Jumlah Jam Pelajaran",
            'rules' => 'integer|required',
            'errors' => [
                'integer' => 'Karakter Tidak Valid',
                'required' => 'Dibutuhkan',
            ]
        ];
        $rules['startTime'] = [
            "alias" => "Jam Masuk",
            'rules' => 'integer',
            'errors' => [
                'integer' => '{value} Karakter Tidak Valid',
            ]
        ];
        $rules['endTime'] = [
            "alias" => "Jam Keluar",
            'rules' => 'integer',
            'errors' => [
                'integer' => '{value} Karakter Tidak Valid',
            ]
        ];
        $rules['kelas_id'] = [
            "alias" => "Kelas",
            'rules' => 'integer|required',
            'errors' => [
                'integer' => '{value} Karakter Tidak Valid',
                'required' => 'Dibutuhkan'
            ]
        ];
        $rules['mapel_id'] = [
            "alias" => "Mata Pelajaran",
            'rules' => 'integer|required',
            'errors' => [
                'integer' => '{value} Karakter Tidak Valid',
                'required' => 'Dibutuhkan'
            ]
        ];
        $rules['tahun_id'] = [
            "alias" => "Tahun 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]);
        }
        $startTime = $this->request->getVar('startTime');
        $endTime = $this->request->getVar('endTime');
        if (date("Y-m-d", $startTime) > date("Y-m-d", $endTime)) return $this->fail(["csrf" => csrf_hash(), 'message' => "Tidak Bisa Menerapkan Waktu Berbeda Hari!"]);
        if ($startTime > $endTime) return $this->fail(["csrf" => csrf_hash(), 'message' => "Waktu Tidak Valid!"]);
        $data = [
            "mapel_id" => $this->request->getVar('mapel_id'),
            "kelas_id" => $this->request->getVar('kelas_id'),
            "tahun_id" => $this->request->getVar('tahun_id'),
            "startDay" => date("w", $this->request->getVar('startTime')) + 1,
            "startTime" => date("H:i:00", $startTime),
            "endTime" => date("H:i:00", $endTime),
            "countJam" => $this->request->getVar('countJam'),
        ];
        if (user()->hasRole('admin')) {
            $data['user_id'] = $this->request->getVar('user_id');
        } else {
            $data['user_id'] = user()->id;
        }
        $updated = $this->JPModel->update($id, $data);
        if (!$updated) return $this->fail(["csrf" => csrf_hash(), 'message' => 'Gagal Mengubah Jadwal Pelajaran']);
        return $this->respond(["csrf" => csrf_hash(), 'message' => 'Berhasil Mengubah Jadwal Pelajaran']);
    }
    public function add()
    {
        if (!$this->request->isAJAX() && ENVIRONMENT != 'development') {
            exit('No direct script access allowed');
        }
        $rules['countJam'] = [
            "alias" => "Jumlah Jam Pelajaran",
            'rules' => 'integer|required',
            'errors' => [
                'integer' => 'Karakter Tidak Valid',
                'required' => 'Dibutuhkan',
            ]
        ];
        $rules['startTime'] = [
            "alias" => "Jam Masuk",
            'rules' => 'integer',
            'errors' => [
                'integer' => '{value} Karakter Tidak Valid',
            ]
        ];
        $rules['endTime'] = [
            "alias" => "Jam Keluar",
            'rules' => 'integer',
            'errors' => [
                'integer' => '{value} Karakter Tidak Valid',
            ]
        ];
        $rules['kelas_id'] = [
            "alias" => "Kelas",
            'rules' => 'integer|required',
            'errors' => [
                'integer' => '{value} Karakter Tidak Valid',
                'required' => 'Dibutuhkan'
            ]
        ];
        $rules['mapel_id'] = [
            "alias" => "Mata Pelajaran",
            'rules' => 'integer|required',
            'errors' => [
                'integer' => '{value} Karakter Tidak Valid',
                'required' => 'Dibutuhkan'
            ]
        ];
        $rules['tahun_id'] = [
            "alias" => "Tahun 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]);
        }
        $startTime = $this->request->getVar('startTime');
        $endTime = $this->request->getVar('endTime');
        if (date("Y-m-d", $startTime) > date("Y-m-d", $endTime)) return $this->fail(["csrf" => csrf_hash(), 'message' => "Tidak Bisa Menerapkan Waktu Berbeda Hari!"]);
        if ($startTime > $endTime) return $this->fail(["csrf" => csrf_hash(), 'message' => "Waktu Tidak Valid!"]);
        $data = [
            "mapel_id" => $this->request->getVar('mapel_id'),
            "kelas_id" => $this->request->getVar('kelas_id'),
            "tahun_id" => $this->request->getVar('tahun_id'),
            "startDay" => date("w", $this->request->getVar('startTime')) + 1,
            "startTime" => date("H:i:00", $startTime),
            "endTime" => date("H:i:00", $endTime),
            "countJam" => $this->request->getVar('countJam'),
            "created_at" => time(),
            "updated_at" => time(),
        ];
        if (user()->hasRole('admin')) {
            $data['user_id'] = $this->request->getVar('user_id');
        } else {
            $data['user_id'] = user()->id;
        }
        $id = $this->JPModel->insert($data);
        if (!$id) return $this->fail(["csrf" => csrf_hash(), 'message' => 'Gagal Menambah Jadwal Pelajaran']);
        return $this->respond(["csrf" => csrf_hash(), 'message' => 'Berhasil Menambah Jadwal Pelajaran']);
    }
}
