<?php

class MY_Controller extends CI_Controller {

    protected $template = "app";
    protected $module = "";
    protected $data = array();
    protected $idUser = null;
    protected $idGroup = null;
    protected $roleAnalis = null;
    protected $uname = null;

    public function __construct() {
        parent::__construct();
        $this->load->model('m_master');

        $this->data['url_param'] = $_SERVER['QUERY_STRING'];

        $this->idUser = $userId = $this->session->userdata('r_userId');
        $this->idGroup = $idGroup = $this->session->userdata("r_idGroup");
        $this->roleAnalis = $this->session->userdata("r_analis");
        $this->uname = !is_null($this->session->userdata("r_realName")) ? $this->session->userdata("r_realName") : $this->session->userdata("r_username");

        if ($this->input->post('type') === 'login') { // login form submit
            $username = $this->input->post("username");
            $password = $this->input->post("password");
            $this->data["user_temp"] = $username;
            $this->data["pass_temp"] = $password;

            $result = $this->db->query("SELECT u.id_user, u.real_name, u.email, u.role_analis
                FROM user u
                WHERE (u.email = ? OR u.username = ?) AND u.password = SHA2(?, 256) AND u.is_active = 1", array($username,$username, $password));

            if ($result->num_rows() == 0) {
                $this->data["errorMessage"] = "Login gagal, cek kembali akun login Anda!";
                $this->template = "login";
                $this->render("login");
            } else {
                $row = $result->first_row();

                $this->session->set_userdata("r_username", $username);
                $this->session->set_userdata("r_realName", $row->real_name);
                $this->session->set_userdata("r_email", $row->email);
                $this->session->set_userdata("r_analis", $row->role_analis);

                $this->getGroupUser($row->id_user, $username, $password);
            }
        } else if (!$userId && uri_string() == "") { // Accessing index page and there is no user session (login form state)
            redirect(site_url()."/login");
        } else if (!$idGroup && (uri_string() == "login")) { // Accessing index page and there is no user session (login form state)
            $this->template = "login";

            if ($this->input->get("access_without_login") == "true") {
                $this->data["errorMessage"] = "Session anda telah berakhir, silahkan login kembali untuk masuk ke dashboard.";
            } else if ($this->input->get("logout") == "true") {
                $this->data["successMessage"] = "Anda telah keluar.";
            } else if ($this->input->get("forgot_password") == "true") {
                $this->data["successMessage"] = "Password anda berhasil diperbarui. Silahkan login dengan password baru.";
            } else if ($this->input->get("no_module") == "true") {
                $this->data["errorMessage"] = "Maaf modul untuk group tersebut belum tersedia.
                                        Silahkan login menggunakan role lain.";
            }

            $this->render("login");
        } else if (!$userId && !in_array(uri_string(), array("", "forgot_password", "forgot_password_reset", "logout", "frontend/galeri")
            ) && (explode('/',uri_string())[0] != 'frontend')) { // Accessing user page and there is no user session
            redirect("?access_without_login=true");
        } else if ($userId != null && $idGroup != null) { // Accessing user page and there is user session
            $this->setUserData();
            $this->SethasPermissionAct();
            $this->get_list_role_of_user();
        }

        if (is_array($this->input->get())) {
            foreach ($this->input->get() as $key => $value) {
                $this->data[$key] = $value;
            }
        }

        if (is_array($this->input->post())) {
            foreach ($this->input->post() as $key => $value) {
                if ($key == "description" || $key == "email" || $key == "is_active" || $key == "is_soft_delete" || $key == "username" || $key == "real_name") {
                    $this->data[$key . "Input"] = $value;
                } else {
                    $this->data[$key] = $value;
                }
            }
        }
    }

    protected function render($filename = null, $sub_folder = null) {

        $template = $this->load->view("template/" . $this->template, $this->data, true);

        $content = $this->load->view(($this->module != "" ? $this->module . "/" : "index/").(isset($sub_folder) ? $sub_folder. "/" : "") . $filename, $this->data, true);

        exit(str_replace("{CONTENT}", $content, $template));
    }

    protected function getGroupUser($id_user, $username, $password) {
        $query = "SELECT a.id_group, b.nama_group, b.keterangan
                    FROM user_group a
                    JOIN login_group b ON a.id_group = b.id_group
                    WHERE a.id_user = ? AND b.is_active = '1'";
        $result = $this->db->query($query, array($id_user));

        if ($result->num_rows() > 0) {
            if ($result->num_rows() == 1) {
                $row = $result->first_row();

                $this->session->set_userdata("r_userId", $id_user);
                $this->session->set_userdata("r_idGroup", $row->id_group);
                $this->session->set_userdata("r_groupName", $row->nama_group);

                $this->get_list_akses_modul_of_group();
                $this->setUserData();
            } else {
                $row = $result->result_array();

                $this->session->set_userdata("r_userId", $id_user);
                $this->session->set_userdata("r_userTemp", $id_user);
                $this->session->set_userdata("r_optionGroup", $row);

                $this->session->set_flashdata('user_temp', $username);
                $this->session->set_flashdata('pass_temp', $password);
                $this->session->set_flashdata('option', true);
            }
        } else {
            $this->session->unset_userdata("r_username");
            $this->session->unset_userdata("r_realName");
            $this->session->unset_userdata("r_email");

            $this->data["errorMessage"] = "Login gagal! Login role user yang Anda gunakan tidak ditemukan pada aplikasi ini!";

            $this->template = "login";
            $this->render("login");
        }
    }

    function get_list_akses_modul_of_group()
    {
        if (!empty($this->session->userdata("r_idGroup"))) {
            $result = $this->db->query("SELECT DISTINCT nama_modul, hak_akses
                                FROM akses_group_modul
                                WHERE id_group = ?
                                ORDER BY nama_modul", array($this->session->userdata("r_idGroup")));

            $userMenus = array();
            foreach ($result->result() as $row) {
                $userMenus[] = $row->nama_modul . "." . $row->hak_akses;
            }
            $this->session->set_userdata("r_userMenus", $userMenus);
        }
    }

    protected function setUserData() {
        $this->data["userId"] = $this->session->userdata("r_userId");
        $this->data["username"] = $this->session->userdata("r_username");
        $this->data["realName"] = $this->session->userdata("r_realName") != null ? $this->session->userdata("r_realName") : $this->data["username"];
        $this->data["email"] = $this->session->userdata("r_email") != null ? $this->session->userdata("r_email") : $this->session->userdata("r_groupName");
        $this->data["creationTime"] = $this->session->userdata("r_creationTime");
        $this->data["isActive"] = $this->session->userdata("r_isActive");
        $this->data["idGroup"] = $this->session->userdata("r_idGroup");
        $this->data["groupName"] = $this->session->userdata("r_groupName");
        $this->data["userMenus"] = $this->session->userdata("r_userMenus");

        $this->session->set_userdata("r_userId", $this->session->userdata("r_userId"));
        $this->session->set_userdata("r_username", $this->session->userdata("r_username"));
        $this->session->set_userdata("r_realName", $this->session->userdata("r_realName"));
        $this->session->set_userdata("r_email", $this->session->userdata("r_email"));
        $this->session->set_userdata("r_idGroup", $this->session->userdata("r_idGroup"));
        $this->session->set_userdata("r_creationTime", $this->session->userdata("r_creationTime"));
        $this->session->set_userdata("r_isActive", $this->session->userdata("r_isActive"));
        $this->session->set_userdata("r_groupName", $this->session->userdata("r_groupName"));
    }

    protected function unSetUserData() {
        $this->session->unset_userdata("r_userId");
        $this->session->unset_userdata("r_username");
        $this->session->unset_userdata("r_realName");
        $this->session->unset_userdata("r_email");
        $this->session->unset_userdata("r_idGroup");
        $this->session->unset_userdata("r_creationTime");
        $this->session->unset_userdata("r_isActive");
        $this->session->unset_userdata("r_groupName");
    }

    protected function SethasPermissionAct(){
        $this->data['readAct'] = true;
        $this->data['createAct'] = true;
        $this->data['updateAct'] = true;
        $this->data['deleteAct'] = true;

        $permRead= $this->module."."."read";
        $permCreate= $this->module."."."create";
        $permUpdate= $this->module."."."update";
        $permDelete= $this->module."."."delete";

        $this->data["userMenus"] = is_null($this->data["userMenus"]) ? array() : $this->data["userMenus"];

        if (in_array($permRead, $this->data["userMenus"]) == false) $this->data['readAct'] = false;
        if (in_array($permCreate, $this->data["userMenus"]) == false) $this->data['createAct'] = false;
        if (in_array($permUpdate, $this->data["userMenus"]) == false) $this->data['updateAct'] = false;
        if (in_array($permDelete, $this->data["userMenus"]) == false) $this->data['deleteAct'] = false;

    }

    protected function hasPermission($PermName1 = "", $PermName2 = "", $PermName3 = "", $PermName4 = "")
    {
        if ($this->module != NULL && $this->module != 'index') {
            $hasPermission = $this->process_hasPermission($PermName1, $PermName2, $PermName3, $PermName4);
            if (!$hasPermission) {
                $message = "Maaf, Anda tidak memiliki akses ke halaman ini.";
                echo "<script language=javascript>alert('$message');window.history.back();</script>";
                die();
            } else {
                return true;
            }
        }
    }

    protected function checkHasPermission($PermName1 = "", $PermName2 = "", $PermName3 = "", $PermName4 = "")
    {
        if ($this->module != NULL && $this->module != 'index') {
            $hasPermission = $this->process_hasPermission($PermName1, $PermName2, $PermName3, $PermName4);
            return $hasPermission;
        } else {
            return true;
        }
    }

    protected function process_hasPermission($PermName1 = "", $PermName2 = "", $PermName3 = "", $PermName4 = ""){
        $hasPermission = false;
        for($i=1; $i <= 4; $i++){
            if(in_array($this->module .'.'.${'PermName'.$i}, $this->data["userMenus"]) != 0) {
                $hasPermission = true;
                break;
            }
        }
        return $hasPermission;
    }

    function get_list_role_of_user()
    {
        if (!empty($this->session->userdata("r_userId"))) {
            $id_user = $this->session->userdata("r_userId");
            $query = $this->db->query("SELECT lg.id_group, lg.nama_group FROM login_group lg
                        LEFT JOIN user_group ug ON lg.id_group = ug.id_group
                        WHERE ug.id_user = ? AND lg.is_active = '1'"
                        , array($id_user))->result_array();
            $this->data["data_role"] = $query;
        }
    }

}
