<?php

namespace App\Controllers\Panel\LainLain;

use App\Controllers\Panel\BC;
use App\Models\Panel\Elearning\TahunPelajaran;
use App\Models\Panel\LainLain\BeritaAcara as BeritaModel;
use CodeIgniter\API\ResponseTrait;

class BeritaAcara extends BC
{
    use ResponseTrait;
    private $beritaModel;
    public function __construct()
    {
        parent::__construct();
        $this->beritaModel = new BeritaModel();
    }
    public function index()
    {
        $data['page_title'] = "Berita Acara";
        return view('Panel/LainLain/BeritaAcara/index', $data);
    }
    public function print($id)
    {
        $ba = $this->beritaModel->findId($id);
        if (!$ba) return $this->failNotFound();
        $btemp = [];
        $temp = [];
        if ($ba['siswa_tidak_hadir']) {
            foreach (explode(',', $ba['siswa_tidak_hadir']) as $key => $sth) {
                $temp[] = $sth;
                if (!(($key + 1) % 10)) {
                    $btemp[] = implode(",", $temp);
                    $temp = [];
                }
            }
            $btemp[] = implode(",", $temp);
        }
        $ba['siswa_tidak_hadir'] = $btemp;
        $data['page_title'] = "Print";
        $data['logo'] = logo();
        $data['kementrian'] = kementrian();
        $data['ba'] = $ba;
        $data['tp'] = (new TahunPelajaran())->getActiveName();
        return view('Panel/LainLain/BeritaAcara/print', $data);
    }

    public function all()
    {
        if (!$this->request->isAJAX() && ENVIRONMENT != 'development') {
            exit('No direct script access allowed');
        }
        $data = $this->beritaModel->getAll();
        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->beritaModel->findId($id);
        return $this->respond(['data' => $data]);
    }
    public function add()
    {
        if (!$this->request->isAJAX() && ENVIRONMENT != 'development') {
            exit('No direct script access allowed');
        }
        $data = (array) $this->request->getVar();
        $state = $this->beritaModel->insert($data);
        if (!$state) return $this->fail(["csrf" => csrf_hash(), 'message' => 'Gagal Menambah Jadwal']);
        return $this->respond(["csrf" => csrf_hash(), 'message' => 'Berhasil Menambah Jadwal']);
    }
    public function delete($id)
    {
        if (!$this->request->isAJAX() && ENVIRONMENT != 'development') {
            exit('No direct script access allowed');
        }
        $state = $this->beritaModel->delete($id);
        return $this->respond(['deleted' => $state, 'message' => $state ? "Berhasil Menghapus" : "Gagal Menghapus"]);
    }
}
