<?php

namespace App\Controllers\Admin;

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

class UserPriv extends BaseController
{
    use ResponseTrait;

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

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

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

        #UBAH
        if (priv_menu('user_priv', 'ubah')) {
            $ubah = 1;
            $link_ubah = base_url('admin/user_priv/update');
        } else {
            $ubah = 0;
            $link_ubah = '';
        }

        #UBAH
        if (priv_menu('user_priv', 'hapus')) {
            $hapus = 1;
            $link_hapus = base_url('admin/user_priv/delete');
        } else {
            $hapus = 0;
            $link_hapus = '';
        }

        return view('admin/userpriv/userpriv_list', [
            'rekam' => $rekam,
            'link_rekam' => $link_rekam,
            'ubah' => $ubah,
            'link_ubah' => $link_ubah,
            'hapus' => $hapus,
            'link_hapus' => $link_hapus,
        ]);
    }

    public function datagrid_user()
    {
        $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->UsersModel->get_rows($rows, $start, $filterRules, $sortOrder);
        foreach ($datas as $k => $v)
        {
            $datas[$k]->id = encrypt_url($v->id);
        }

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

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

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

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

        $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->UsergroupModel->get_rows2($id_usr, $rows, $start, $filterRules, $sortOrder);

        foreach ($datas as $k => $v)
        {
            $datas[$k]->id_ug = encrypt_url($v->id_ug);
            $datas[$k]->id_modul = encrypt_url($v->id_modul);
            $datas[$k]->group_id = $v->group_id;
            $datas[$k]->user_id = $v->user_id;
            $datas[$k]->nama_modul = $v->nama_modul;
            $datas[$k]->nama_group = $v->nama_group;
            $datas[$k]->ket_rg = $v->ket_rg;
        }

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

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

    //function ambil data modul dan group saat rekam privilege
    public function get_modul()
    {
        $id_user = decrypt_url($this->request->getPost('id_usr'));
        $user  = $this->UsersModel->get_by_id($id_user);

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

        //prepare data modul
        $data_modul = $this->UsergroupModel->get_modul_by_user($id_user);
        
        if (!empty($data_modul)) {
            //buat array id_modul
            foreach ($data_modul as $k) {
                $ar_id_modul[] = $k->id_modul;
            }
            
            //ambil data rolegroup
            $data_grup = $this->UsergroupModel->get_group_by_modul($ar_id_modul);

            //gabungkan data
            $dtx = [];

            foreach ($data_modul as $m) {
                $dtx[$m->id_modul] = [
                    'id_modul' => $m->id_modul,
                    'nama_modul' => $m->nama_modul,
                    'ket' => $m->ket,
                    'role' => []
                ];
            }

            foreach ($data_grup as $g) {
                if (isset($dtx[$g->id_modul])) {
                    $dtx[$g->id_modul]['role'][] = [
                        'id_group' => $g->id_group,
                        'nama_group' => $g->nama_group,
                    ];
                }
            }
            return $this->respond(['dtmodul' => $dtx]);
        } else {
            return $this->respond('Semua modul telah ditambahkan');
        }
    }

    //ambil data rolegroup berdasarkan id_modul (proses edit)
    public function get_role()
    {
        $id_modul = decrypt_url($this->request->getPost('id_modul'));
        $dtrole = $this->UsergroupModel->get_rolegroup_by_modul($id_modul);
        return $this->respond($dtrole);
    }

    //proses rekam privilege
    public function create()
    {
        $this->setJsonHeader();

        if (priv_menu('user_priv', 'rekam')) {
            $id_user = decrypt_url($this->request->getPost('id_usr'));
            $id_groups = $this->request->getPost('id_group');

            for ($i = 0; $i < count($id_groups); $i++) {
                $data_child[] = [
                    'user_id'   => $id_user,
                    'group_id' => $id_groups[$i]
                ];
            }

            if (!$this->UsergroupModel->insert_batch($data_child)) {
                return $this->fail($this->UsergroupModel->errors(), 400);
            } else {
                return $this->respond(['message' => B_SIMPAN]);
            }
        } else {
            return $this->fail(['message' => NO_AKSES]);
        }
    }

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

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

            $data = [
                'id_ug'  => trim($this->request->getPost('id_ug')),
                'group_id' => trim($this->request->getPost('group_id')),
            ];

            if (!$this->UsergroupModel->update($id_ug, $data)) {
                return $this->fail($this->UsergroupModel->errors(), 400);
            } else {
                return $this->respond(['message' => B_UBAH]);
            }
        } else {
            return $this->fail(['message' => NO_AKSES]);
        }
    }

    //proses delete privilege
    public function delete()
    {
        $this->setJsonHeader();

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

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

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