<?php

namespace App\Controllers\Referensi;

use App\Controllers\BaseController;
use CodeIgniter\API\ResponseTrait;

class Pdkunit extends BaseController
{
    use ResponseTrait;

    public function __construct()
    {
        $this->PdkunitModel = model('App\Models\Referensi\PdkunitModel');
    }

    private function setJsonHeader()
    {
        return $this->response->setHeader('Content-Type', 'application/json');
    }

    //Validation Rule
    private function ruleData($id = null)
    {
        return [
            'id'               => 'trim',
            'nama_unit'              => $id 
                ? "required|regex_match[/^[a-zA-Z0-9\s.,@-]+$/]|max_length[150]|is_unique[pdk_unit.nama_unit,id,{$id}]"
                : "required|regex_match[/^[a-zA-Z0-9\s.,@-]+$/]|max_length[150]|is_unique[pdk_unit.nama_unit]",
            'nama_sunit'              => $id 
                ? "required|regex_match[/^[a-zA-Z0-9\s.,@-]+$/]|max_length[150]|is_unique[pdk_unit.nama_sunit,id,{$id}]"
                : "required|regex_match[/^[a-zA-Z0-9\s.,@-]+$/]|max_length[150]|is_unique[pdk_unit.nama_sunit]",
        ];
    }

    public function index()
    {
        //function($modul, $menu) --------
        $links = genlinks('referensi', 'pdkunit');

        $rekam = $links['rekam']['status'];
        $link_rekam = $links['rekam']['link'];

        $ubah = $links['ubah']['status'];
        $link_ubah = $links['ubah']['link'];

        $hapus = $links['hapus']['status'];
        $link_hapus = $links['hapus']['link'];

        return view('referensi/pdkunit/pdkunit_list', [
            'rekam' => $rekam,
            'link_rekam' => $link_rekam,
            'ubah' => $ubah,
            'link_ubah' => $link_ubah,
            'hapus' => $hapus,
            'link_hapus' => $link_hapus,
        ]);
    }

    public function datagrid()
    {
        $this->setJsonHeader();

        $page           = trim($this->request->getPost('page')) ? trim($this->request->getPost('page')) : 1;
        $rows           = trim($this->request->getPost('rows')) ? trim($this->request->getPost('rows')) : 10;
        $sort           = trim($this->request->getPost('sort'));
        $order          = trim($this->request->getPost('order'));
        $filterRules    = trim($this->request->getPost('filterRules'));
        $start          = ($page - 1) * $rows;

        if ($sort && $order) {
            $sortOrder = multi_sort($sort, $order);
        } else {
            $sortOrder = multi_sort('id', 'ASC');
        }

        $datas = $this->PdkunitModel->get_rows($rows, $start, $filterRules, $sortOrder);
        foreach ($datas as $k => $v)
        {
            $datas[$k]->id = encrypt_url($v->id);
        }


        $res['total']  = $this->PdkunitModel->get_total($filterRules);
        $res['rows']   = $datas;

        return $this->response->setJSON($res);
    }

    //menampilkan laman manual
    public function manualx()
    {
        return view('referensi/manualx');
    }

    public function show($id)
    {
        $row = $this->PdkunitModel->find(decrypt_url($id));

        if (!$row) {
            exit('Data tidak ditemukan');
        }

        return view('referensi/pdkunit/pdkunit_show', [
			'nama_unit' => $row->nama_unit,
			'nama_sunit' => $row->nama_sunit,
        ]);
    }

    public function new()
    {
        return view('referensi/pdkunit/pdkunit_form', [
            'action' => base_url('referensi/pdkunit/create'),
            'button' => 'SIMPAN DATA',
			'id' => '',
			'nama_unit' => '',
			'nama_sunit' => '',
        ]);
    }

    public function create()
    {
        $this->setJsonHeader();

        //jika tdk memiliki akses utk rekam data
        if (!priv_menu('pdkunit', 'rekam')) {
            return $this->fail(['message' => NO_AKSES], 403);
        }

        //Collect form data
        $data = [
			'nama_unit' => $this->request->getPost('nama_unit', FILTER_SANITIZE_SPECIAL_CHARS),
			'nama_sunit' => $this->request->getPost('nama_sunit', FILTER_SANITIZE_SPECIAL_CHARS),
        ];

        $vrData = $this->ruleData();
        //jika validasi gagal
        if (!$this->validate($vrData)) {
            return $this->fail($this->validator->getErrors(), 400);
        }

        //jika insert gagal
        if (!$this->PdkunitModel->insert($data)) {
            return $this->fail($this->PdkunitModel->errors(), 500);
        }

        return $this->respond(['message' => B_SIMPAN], 201);
    }

    public function edit($id)
    {
        $row = $this->PdkunitModel->find(decrypt_url($id));

        if (!$row) {
            exit('Data tidak ditemukan');
        }

        return view('referensi/pdkunit/pdkunit_form', [
            'action' => base_url('referensi/pdkunit/update'),
            'button' => 'UBAH DATA',
			'id' => encrypt_url($row->id),
			'nama_unit' => $row->nama_unit,
			'nama_sunit' => $row->nama_sunit,
        ]);
    }

    public function update()
    {
        $this->setJsonHeader();

        //jika tdk memiliki akses utk rekam data
        if (!priv_menu('pdkunit', 'ubah')) {
            return $this->fail(['message' => NO_AKSES], 403);
        }

        //collect form data
        $id = decrypt_url(trim($this->request->getPost('id')));
        $data = [
            'id'  => $id,
			'nama_unit' => $this->request->getPost('nama_unit', FILTER_SANITIZE_SPECIAL_CHARS),
            'nama_sunit' => $this->request->getPost('nama_sunit', FILTER_SANITIZE_SPECIAL_CHARS),
        ];

        $vrData = $this->ruleData($id);
        //jika validasi gagal
        if (!$this->validate($vrData)) {
            return $this->fail($this->validator->getErrors(), 400);
        }

        if (!$this->PdkunitModel->update($id, $data)) {
            return $this->fail($this->PdkunitModel->errors(), 500);
        }

        return $this->respond(['message' => B_UBAH], 200);
    }

    public function delete()
    {
        header('Content-Type: application/json');

        $ids  = $this->request->getPost('ids');

        $del = array();
        foreach ($ids as $id) {
            $del[] = decrypt_url($id);
        }

        if (!$this->PdkunitModel->delete($del)) {
            return $this->fail($this->PdkunitModel->errors(), 500);
        } else {
            return $this->respond(['message' => count($del).lang('App.delete_success')]);
        }
    }

}