<?php

namespace App\Controllers\Admin;

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

class Modul extends BaseController
{
    use ResponseTrait;

    public function __construct()
    {
        $this->ModulModel = model('App\Models\Admin\ModulModel');
        $this->MenuModel = model('App\Models\Admin\MenuModel');
    }

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

    //Validation Rule untuk Modul
    private function ruleModul($id_modul = null)
    {
        return [
            'fname'       => $id_modul 
                ? "required|regex_match[/^[a-zA-Z0-9\s.,@-]+$/]|is_unique[moduls.fname,id_modul,{$id_modul}]"
                : "required|regex_match[/^[a-zA-Z0-9\s.,@-]+$/]|is_unique[moduls.fname]",
            'nama_modul'  => $id_modul 
                ? "required|regex_match[/^[a-zA-Z0-9\s.,@-]+$/]|is_unique[moduls.nama_modul,id_modul,{$id_modul}]"
                : "required|regex_match[/^[a-zA-Z0-9\s.,@-]+$/]|is_unique[moduls.nama_modul]",
            'urut'        => 'required|numeric',
            'ikon'        => 'required|regex_match[/^[a-zA-Z0-9\s.,@-]+$/]',
        ];
    }

    //Validation Rule untuk Menu
    private $vrMenu = [
        'id_modul'   => 'required|numeric',
        'nama_menu'  => 'required|regex_match[/^[a-zA-Z0-9\s.,@-]+$/]',
        'urut'       => 'required|numeric',
        'method'     => 'required|regex_match[/^[a-zA-Z0-9\s.,@-]+$/]',
    ];

    public function index()
    {
        if (priv_menu('modul', 'rekam')) {
            $rekam = 1;
            $link_rekam_modul = base_url('admin/modul/new_modul');
            $link_rekam_menu = base_url('admin/modul/new_menu');
        } else {
            $rekam = 0;
            $link_rekam_modul = '';
            $link_rekam_menu = '';
        }

        if (priv_menu('modul', 'ubah')) {
            $ubah = 1;
            $link_ubah_modul = base_url('admin/modul/edit_modul/');
            $link_ubah_menu = base_url('admin/modul/edit_menu/');
        } else {
            $ubah = 0;
            $link_ubah_modul = '';
            $link_ubah_menu = '';
        }

        if (priv_menu('modul', 'hapus')) {
            $hapus = 1;
            $link_hapus_modul = base_url('admin/modul/delete_modul');
            $link_hapus_menu = base_url('admin/modul/delete_menu');
        } else {
            $hapus = 0;
            $link_hapus_modul = '';
            $link_hapus_menu = '';
        }

        return view('admin/modul/modul_list', [
            'rekam' => $rekam,
            'link_rekam_modul' => $link_rekam_modul,
            'link_rekam_menu' => $link_rekam_menu,
            'ubah' => $ubah,
            'link_ubah_modul' => $link_ubah_modul,
            'link_ubah_menu' => $link_ubah_menu,
            'hapus' => $hapus,
            'link_hapus_modul' => $link_hapus_modul,
            'link_hapus_menu' => $link_hapus_menu,
        ]);
    }

    //DATAGRID MODUL
    public function datagrid_modul()
    {
        $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 = NULL;
        }

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


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

        return $this->response->setJSON($res);
    }//END DATAGRID MODUL

    //DATAGRID MENU
    public function datagrid_menu()
    {
        $this->setJsonHeader();

        $id_modul = (!empty($this->request->getPost('id_modul')) ? decrypt_url($this->request->getPost('id_modul')) : $this->session->get('id_modul_mm'));
        $this->session->set('id_modul_mm',$id_modul);

        $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('urut', 'ASC');
        }

        $datas = $this->MenuModel->get_rows2($id_modul, $rows, $start, $filterRules, $sortOrder);
        foreach ($datas as $k => $v)
        {
            $datas[$k]->id_menu = encrypt_url($v->id_menu);
        }


        $res['total']  = $this->MenuModel->get_total2($id_modul, $filterRules);
        $res['rows']   = $datas;

        return $this->response->setJSON($res);
    }//END DATAGRID MENU

    //FUNGSI SHOW --------------------------
    public function show_modul($id)
    {
        $row = $this->ModulModel->find(decrypt_url($id));

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

        return view('admin/modul/modul_show', [
			'fname' => $row->fname,
			'nama_modul' => $row->nama_modul,
			'urut' => $row->urut,
            'ikon' => $row->ikon,
			'ket' => $row->ket,
        ]);
    }

    public function show_menu($id)
    {
        $row = $this->MenuModel->find_by_id(decrypt_url($id));

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

        return view('admin/modul/menu_show', [
            'id_modul' => $row->id_modul,
            'id_parent' => $row->id_parent,
            'nama_modul' => $row->nama_modul,
            'nama_parent' => $row->nama_parent,
            'nama_menu' => $row->nama_menu,
            'urut' => $row->urut,
            'method' => $row->method,
        ]);
    } //END FUNGSI SHOW --------------------

    //FUNGSI REKAM---------------------
    //Tampilkan Form untuk Rekam Modul
    public function new_modul()
    {
        if (priv_menu('modul', 'rekam')) {
            return view('admin/modul/modul_form', [
                'action' => base_url('admin/modul/create_modul'),
    			'id_modul' => '',
    			'fname' => '',
    			'nama_modul' => '',
    			'urut' => '',
                'ikon' => '',
    			'ket' => '',
            ]);
        } else {
            return $this->fail(['message' => NO_AKSES]);
        }
    }//End Tampilkan Form untuk Rekam

    //Proses Simpan Modul
    public function create_modul()
    {
        $this->setJsonHeader();
        $vrModul = $this->ruleModul();

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

        //collect data form
        $data = [
            'fname' => $this->request->getPost('fname', FILTER_SANITIZE_SPECIAL_CHARS),
            'nama_modul' => $this->request->getPost('nama_modul', FILTER_SANITIZE_SPECIAL_CHARS),
            'urut' => $this->request->getPost('urut', FILTER_SANITIZE_NUMBER_INT),
            'ikon' => $this->request->getPost('ikon', FILTER_SANITIZE_SPECIAL_CHARS),
            'ket' => $this->request->getPost('ket', FILTER_SANITIZE_SPECIAL_CHARS),
            'created_by' => auth()->id(),
        ];

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

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

        return $this->respond(['message' => B_SIMPAN], 201);
    }//End Proses Simpan Modul

    //Tampilkan Form untuk Rekam Menu
    public function new_menu()
    {
        return view('admin/modul/menu_form', [
            'action' => base_url('admin/modul/create_menu'),
            'id_menu' => '',
            'id_modul' => '',
            'id_parent' => '',
            'nama_menu' => '',
            'urut' => '',
            'method' => '',
            'dd_moduls' => $this->ModulModel->dd_moduls(),
            'dd_menus' => $this->MenuModel->dd_menus(0),
        ]);
    }

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

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

        //collect data form
        $data = [
            'id_modul' => $this->request->getPost('id_modul', FILTER_SANITIZE_NUMBER_INT),
            'id_parent' => $this->request->getPost('id_parent', FILTER_SANITIZE_NUMBER_INT),
            'nama_menu' => $this->request->getPost('nama_menu', FILTER_SANITIZE_SPECIAL_CHARS),
            'urut' => $this->request->getPost('urut', FILTER_SANITIZE_NUMBER_INT),
            'method' => $this->request->getPost('method', FILTER_SANITIZE_SPECIAL_CHARS),
            'created_by' => auth()->id(),
        ];
        
        //jika validasi gagal
        if (!$this->validate($this->vrMenu)) {
            return $this->fail($this->validator->getErrors(), 400);
        }

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

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

    //FUNGSI UBAH---------------
    //Tampilkan Form Edit Modul
    public function edit_modul($id)
    {
        $row = $this->ModulModel->find(decrypt_url($id));

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

        return view('admin/modul/modul_form', [
            'action' => base_url('admin/modul/update_modul'),
            'button' => lang('App.update'), 
			'id_modul' => encrypt_url($row->id_modul),
			'fname' => $row->fname,
			'nama_modul' => $row->nama_modul,
			'urut' => $row->urut,
            'ikon' => $row->ikon,
			'ket' => $row->ket,
        ]);
    }//End Tampilkan Form Edit Modul

    //Tampilkan Form Edit Menu
    public function edit_menu($id)
    {
        $row = $this->MenuModel->find(decrypt_url($id));

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

        return view('admin/modul/menu_form', [
            'action' => base_url('admin/modul/update_menu'),
            'button' => lang('App.update'), 
            'id_menu' => encrypt_url($row->id_menu),
            'id_modul' => $row->id_modul,
            'id_parent' => $row->id_parent,
            'nama_menu' => $row->nama_menu,
            'urut' => $row->urut,
            'method' => $row->method,
            'dd_moduls' => $this->ModulModel->dd_moduls(),
            'dd_menus' => $this->MenuModel->dd_menus($row->id_modul),
        ]);
    }//End Tampilkan Form Edit Menu

    //Proses Update Modul
    public function update_modul()
    {
        $this->setJsonHeader();
        
        //jika tdk memiliki akses utk rekam data
        if (!priv_menu('modul', 'ubah')) {
            return $this->fail(['message' => NO_AKSES], 403);
        }

        //collect form data
        $id_modul = decrypt_url($this->request->getPost('id_modul'));
        $vrModul = $this->ruleModul($id_modul);

        $data = [
            'fname' => $this->request->getPost('fname', FILTER_SANITIZE_SPECIAL_CHARS),
            'nama_modul' => $this->request->getPost('nama_modul', FILTER_SANITIZE_SPECIAL_CHARS),
            'urut' => $this->request->getPost('urut', FILTER_SANITIZE_NUMBER_INT),
            'ikon' => $this->request->getPost('ikon', FILTER_SANITIZE_SPECIAL_CHARS),
            'ket' => $this->request->getPost('ket', FILTER_SANITIZE_SPECIAL_CHARS),
            'updated_at' => timestamp(),
            'updated_by' => auth()->id(),
        ];

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

        //jika proses update gagal
        if (!$this->ModulModel->update($id_modul, $data)) {
            return $this->fail($this->ModulModel->errors(), 500);
        }

        return $this->respond(['message' => B_UBAH], 200);
    }//End Proses Update Modul

    //Proses Update Menu
    public function update_menu()
    {
        $this->setJsonHeader();

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

        //collect form data
        $id_menu = decrypt_url(trim($this->request->getPost('id_menu')));

        $data = [
            'id_modul' => $this->request->getPost('id_modul', FILTER_SANITIZE_NUMBER_INT),
            'id_parent' => $this->request->getPost('id_parent', FILTER_SANITIZE_NUMBER_INT),
            'nama_menu' => $this->request->getPost('nama_menu', FILTER_SANITIZE_SPECIAL_CHARS),
            'urut' => $this->request->getPost('urut', FILTER_SANITIZE_NUMBER_INT),
            'method' => $this->request->getPost('method', FILTER_SANITIZE_SPECIAL_CHARS),
            'updated_at' => timestamp(),
            'updated_by' => auth()->id(),
        ];

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

        //jika proses update gagal
        if (!$this->MenuModel->update($id_menu, $data)) {
            return $this->fail($this->MenuModel->errors(), 500);
        }

        return $this->respond(['message' => B_UBAH], 200);
    }//End Proses Update Menu

    //FUNGSI HAPUS ---------------------
    //Proses Delete Modul
    public function delete_modul()
    {
        $this->setJsonHeader();

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

        //collect form data
        $ids  = $this->request->getPost('ids');
        $del = array();
        foreach ($ids as $id) {
            $del[] = decrypt_url($id);
        }

        if (!$this->ModulModel->delete($del)) {
            return $this->fail($this->ModulModel->errors(), 500);
        }

        return $this->respond(['message' => count($del).' '.B_HAPUS], 200);
    }

    //Proses Delete Menu
    public function delete_menu()
    {
        $this->setJsonHeader();

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

        //collect form data
        $ids  = $this->request->getPost('ids');
        $del = array();
        foreach ($ids as $id) {
            $del[] = decrypt_url($id);
        }

        if (!$this->MenuModel->delete($del)) {
            return $this->fail($this->MenuModel->errors(), 500);
        }

        return $this->respond(['message' => count($del).' '.B_HAPUS], 200);
    }
    //END FUNGSI HAPUS ----------------------

    //AMBIL DATA MENU UNTUK PARENT
    public function get_parent()
    {
        $this->setJsonHeader();

        $field      = $this->request->getPost('id_modul');
        $datas      = $this->MenuModel->get_parent($field);
        $datax = array("id_menu" => "", "nama_menu" => "Select Parent (for submenu)");
        array_unshift($datas , $datax);

        return json_encode($datas);
    }
}