<?php

namespace App\Controllers\Admin;

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

class Rolegroup extends BaseController
{
    use ResponseTrait;

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

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

    //Validation Rule untuk Role Group
    private $vrRg = [
        'nama_group'  => 'required|regex_match[/^[a-zA-Z0-9\s.,@-]+$/]',
        'ket'     => 'required|regex_match[/^[a-zA-Z0-9\s.,@-]+$/]',
    ];

    //Validation Rule untuk Role Menu
    private $vrRm = [
        'group_id'   => 'required|numeric',
        'menu_id'   => 'required|numeric',
    ];

    public function index()
    {
        //cek privilege dan link
        #REKAM
        if (priv_menu('rolegroup', 'rekam')) {
            $rekam = 1;
            $link_rekam_rg = base_url('admin/rolegroup/create_rg');
        } else {
            $rekam = 0;
            $link_rekam_rg = '';
        }

        #UBAH
        if (priv_menu('rolegroup', 'ubah')) {
            $ubah = 1;
            $link_ubah_rg = base_url('admin/rolegroup/update_rg');
            $link_ubah_rm = base_url('admin/rolegroup/update_rm');
            $link_add_rm = base_url('admin/rolegroup/add_rm');
        } else {
            $ubah = 0;
            $link_ubah_rg = '';
            $link_ubah_rm = '';
            $link_add_rm = '';
        }

        #HAPUS
        if (priv_menu('rolegroup', 'hapus')) {
            $hapus = 1;
            $link_hapus_rg = base_url('admin/rolegroup/delete_rg');
            $link_hapus_rm = base_url('admin/rolegroup/delete_rm');
        } else {
            $hapus = 0;
            $link_hapus_rg = '';
            $link_hapus_rm = '';
        }

        return view('admin/rolegroup/rolegroup_list', [
            'rekam' => $rekam,
            'link_rekam_rg' => $link_rekam_rg,
            'ubah' => $ubah,
            'link_ubah_rg' => $link_ubah_rg,
            'link_ubah_rm' => $link_ubah_rm,
            'link_add_rm' => $link_add_rm,
            'hapus' => $hapus,
            'link_hapus_rg' => $link_hapus_rg,
            'link_hapus_rm' => $link_hapus_rm,
            'dd_moduls' => $this->ModulModel->dd_moduls(),
        ]);
    }

    public function datagrid_rg()
    {
        $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;
        }

        // save to session for export excel
        $sessionDatagrid = array(
            'sortOrder' => $sortOrder,
            'filterRules' => $filterRules,
        );
        $this->session->set($sessionDatagrid);

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


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

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

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

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

        $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;
        }

        // save to session for export excel
        $sessionDatagrid = array(
            'sortOrder' => $sortOrder,
            'filterRules' => $filterRules,
        );
        $this->session->set($sessionDatagrid);

        $datas = $this->RolemenuModel->get_rows2($id_group, $rows, $start, $filterRules, $sortOrder);

        foreach ($datas as $k => $v)
        {
            $datas[$k]->id_rm = encrypt_url($v->id_rm);
            $datas[$k]->id_parent = $v->id_parent == 0 ? 'Y':'';
            $datas[$k]->rekam = $v->rekam == 1 ? 'Y':'N';
            $datas[$k]->ubah = $v->ubah == 1 ? 'Y':'N';
            $datas[$k]->hapus = $v->hapus == 1 ? 'Y':'N';
            $datas[$k]->exp = $v->exp == 1 ? 'Y':'N';
        }


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

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

    //ambil data menu berdasarkan modul - saat rekam role
    public function get_related_menu() 
    {
        $this->setJsonHeader();
        $id_modul = $this->request->getPost('id_modul');
        $data_menu = $this->RolegroupModel->get_menu_bymodul($id_modul);
        return $this->respond($data_menu);
    }

    //ambil data menu yg belum ada di role berdasarkan modul - saat tambah menu role
    public function get_related_menu2() 
    {
        $this->setJsonHeader();
        $id_group = $this->request->getPost('id_group');
        $id_modul = $this->request->getPost('id_modul');
        $data_menu = $this->RolegroupModel->get_menu_bymodul2($id_group, $id_modul);
        return $this->respond($data_menu);
    }

    //FUNGSI ADD ------------------------
    public function create_rg()
    {
        $this->setJsonHeader();

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

        //collect data form
        $data_tabel = $this->request->getPost('data_tabel');

        $data = [
            'nama_group' => $this->request->getPost('nama_group', FILTER_SANITIZE_SPECIAL_CHARS),
            'id_modul' => $this->request->getPost('id_modul', FILTER_SANITIZE_NUMBER_INT),
            'ket' => $this->request->getPost('ket', FILTER_SANITIZE_SPECIAL_CHARS),
        ];

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

        //insert role group
        $newID = $this->RolegroupModel->insert($data);

        //insert role menu
        if ($newID) {
            // Siapkan array untuk batch insert
            $dtmenu = [];

            foreach ($data_tabel as $row) {
                $dtmenu[] = [
                    'group_id' => $newID,
                    'menu_id' => $row['id_menu'],
                    'rekam'   => $row['rekam'],
                    'ubah'    => $row['ubah'],
                    'hapus'   => $row['hapus'],
                    'exp'     => $row['exp'],
                ];
            }

            if (!$this->RolemenuModel->insert_batch($dtmenu)) {
                return $this->fail($this->RolemenuModel->errors(), 500);
            } else {
                return $this->respond(['message' => B_SIMPAN], 201);
            }
        }
    } //END REKAM ROLE

    //Tampilkan Form untuk Rekam/Tambah Menu Role (untuk menu yg belum ada)
    public function add_rm()
    {
        return view('admin/rolegroup/rolegroup_form', [
            'action' => base_url('admin/rolegroup/create_rm'),
            'id_rm' => '',
            'group_id' => '',
            'menu_id' => '',
            'rekam' => '',
            'ubah' => '',
            'hapus' => '',
            'exp' => '',
            'dd_groups' => $this->RolegroupModel->dd_rolegroups(),
        ]);
    }

    //TAMBAH ROLEMENU
    public function create_rm()
    {
        $this->setJsonHeader();

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

        //collect data form
        $group_id = $this->request->getPost('group_id', FILTER_SANITIZE_NUMBER_INT);
        $data_tabel = $this->request->getPost('data_tabel');

        // Siapkan array untuk batch insert
        foreach ($data_tabel as $row) {
            $dtmenu[] = [
                'group_id' => $group_id,
                'menu_id' => $row['id_menu'],
                'rekam'   => $row['rekam'],
                'ubah'    => $row['ubah'],
                'hapus'   => $row['hapus'],
                'exp'     => $row['exp'],
            ];
        }

        if (!$this->RolemenuModel->insert_batch($dtmenu)) {
            return $this->fail($this->RolemenuModel->errors(), 500);
        } else {
            return $this->respond(['message' => B_SIMPAN], 201);
        }
    } //END REKAM ROLE
    //END FUNGSI ADD ---------------------

    //FUNGSI UBAH ----------------------
    public function update_rg()
    {
        $this->setJsonHeader();

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

        //collect data form
        $id_group = decrypt_url($this->request->getPost('id_group'));
        $data = [
            'nama_group' => trim($this->request->getPost('nama_group', FILTER_SANITIZE_SPECIAL_CHARS)),
            'ket' => trim($this->request->getPost('ket', FILTER_SANITIZE_SPECIAL_CHARS)),
        ];
        
        //jika validasi gagal
        if (!$this->validate($this->vrRg)) {
            return $this->fail($this->validator->getErrors(), 400);
        }

        if (!$this->RolegroupModel->update($id_group, $data)) {
            return $this->fail($this->RolegroupModel->errors(), 500);
        } else {
            return $this->respond(['message' => B_UBAH], 200);
        }
    }

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

        if (priv_menu('rolegroup', 'ubah')) {
            $id_rm = decrypt_url(trim($this->request->getPost('id_rm')));

            $data = [
                'id_rm'  => trim($this->request->getPost('id_rm')),
                'rekam' => trim($this->request->getPost('rekam')),
                'ubah' => trim($this->request->getPost('ubah')),
                'hapus' => trim($this->request->getPost('hapus')),
                'exp' => trim($this->request->getPost('exp')),
            ];

            if (!$this->RolemenuModel->update($id_rm, $data)) {
                return $this->fail($this->RolemenuModel->errors(), 400);
            } else {
                return $this->respond(['message' => B_UBAH], 200);
            }
        } else {
            return $this->fail(['message' => NO_AKSES], 403);
        }
    }
    //END FUNGSI UBAH ------------------

    //FUNGSI HAPUS ----------------------
    public function delete_rg()
    {
        $this->setJsonHeader();

        if (priv_menu('rolegroup', 'hapus')) {
            $ids  = $this->request->getPost('ids');

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

            if (!$this->RolegroupModel->delete($del)) {
                return $this->fail($this->RolegroupModel->errors(), 400);
            } else {
                return $this->respond(['message' => count($del).' '.B_HAPUS], 200);
            }
        } else {
            return $this->fail(['message' => NO_AKSES], 403);
        }
    }

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

        if (priv_menu('rolegroup', 'hapus')) {
            $ids  = $this->request->getPost('ids');

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

            if (!$this->RolemenuModel->delete($del)) {
                return $this->fail($this->RolemenuModel->errors(), 400);
            } else {
                return $this->respond(['message' => count($del).' '.B_HAPUS], 200);
            }
        } else {
            return $this->fail(['message' => NO_AKSES], 403);
        }
    }
    //END FUNGSI HAPUS ------------------
}