<?php

class MY_Controller2 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");

            $result = $this->db->query("SELECT u.id, 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, $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();
        }


        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->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");
        }
    }

    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");
    }


}
