<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class User_model extends CI_Model {
    private $sessData, $userType, $tblUsers;
    function __construct(){
        parent::__construct();
        $this->tblUsers     = $this->config->item('tbl_users');
        $this->sessData     = $this->session->userdata();
        $this->userType     = $this->sessData['user_type'];
    }

    function getDataUserDtTable($params){
        $total = $this->getQueryDataDtTable($params, 'rows');

        $output=array();
        $output['draw']=$params['draw'];
        $output['recordsTotal']=$output['recordsFiltered']=$total;
        $output['data']=array();

        $query = $this->getQueryDataDtTable($params,'list');
        $i = $params['start'] + 1;
        foreach($query->result_array() as $row){
            $idKey      = $row['user_id'];
            $row_array  = $row;
            $checkBox   = '<div class="custom-checkbox custom-control">
                              <input type="checkbox" data-checkboxes="mygroup" name="mycheck[]" value="'.$idKey.'" class="custom-control-input" id="checkbox-'.$idKey.'">
                              <label for="checkbox-'.$idKey.'" class="custom-control-label">&nbsp;</label>
                           </div>';

            if($row['user_type'] == '0'){
                $row_array['user_type_desk']  = 'Administrator';
            }else{
                $row_array['user_type_desk']  = 'User Biasa';
            }

            //Custom Field
            $row_array['DT_RowId']    = 'user_'.$idKey;
            $row_array['DT_RowAttr']  = array('data-key' => '', 'data-dataid' => $idKey);
            $row_array['check_data']  = $checkBox;
            array_push($output['data'], $row_array);
        }

        return $output;
    }

    function getQueryDataDtTable($params, $type='list'){
        $draw         = $params['draw'];
        $length       = $params['length'];
        $start        = $params['start'];
        $searchDt     = $params['search']["value"];
        $pencarian    = (isset($params['pencarian'])) ? $params['pencarian'] : '';

        $this->db->select("user_id, username, password, nama_lengkap, tgl_update, user_type");
        $this->db->from($this->tblUsers);

        if($pencarian != ''){
            $this->db->like('username', $pencarian);
            $this->db->or_like('nama_lengkap', $pencarian);
        }

        if($type != 'rows'){
            $this->db->order_by("username", 'asc');
            if($length != '-1'){
                $this->db->limit($length,$start);
            }
        }

        if($type == 'rows'){
            return $this->db->count_all_results();
        }else{
            $query = $this->db->get();
            return $query;
        }
    }

    function getdetailDataUser($params){
        if(!isset($params['user_id']) || $params['user_id'] == ''){
            return returnResponse('01', 'User ID wajib di isi');
        }

        $this->db->select("user_id, username, password, nama_lengkap, tgl_update, user_type");
        $this->db->from($this->tblUsers);
        $this->db->where('user_id', $params['user_id']);
        $query = $this->db->get();
        if($query->num_rows() > 0){
            $result = $query->result();
            $result = (array)$result[0];
            return returnResponse('00', 'Data user ditemukan', $result);
        }else{
            return returnResponse('01', 'Data user tidak ditemukan');
        }
    }

    function updateDataProfile($params){
        $userId     = $this->sessData['user_id'];
        $arrUpdate  = array('nama_lengkap' => $params['nama_lengkap']);

        $this->db->where('user_id', $userId);
        $qUpdate = $this->db->update($this->tblUsers, $arrUpdate);
        if($qUpdate){
            $this->session->unset_userdata('nama_lengkap');
            $this->session->set_userdata($arrUpdate);
            return returnResponse('00', 'Sukses update data profile');
        }else{
            return returnResponse('01', 'Gagal update data profile');
        }
    }

    function updateDataPassword($params){
        if(!isset($params['old_pass']) || $params['old_pass'] == ''){
            return returnResponse('01', 'Password lama wajib di isi');
        }
        if(!isset($params['new_pass']) || $params['new_pass'] == ''){
            return returnResponse('01', 'Password baru wajib di isi');
        }
        if(!isset($params['conf_pass']) || $params['conf_pass'] == ''){
            return returnResponse('01', 'Password konfirmasi wajib di isi');
        }

        $passDb     = $this->getPasswordUser();
        $userId     = $this->sessData['user_id'];
        $oldPass    = sha1($params['old_pass']);
        $newPass    = sha1($params['new_pass']);
        $confPass   = sha1($params['conf_pass']);

        if($oldPass != $passDb){
            return returnResponse('01', 'Password lama tidak sesuai');
        }
        if($newPass != $confPass){
            return returnResponse('01', 'Password baru dan konfirmasi tidak sesuai');
        }

        $arrUpdate  = array('password' => $newPass);
        $this->db->where('user_id', $userId);
        $qUpdate = $this->db->update($this->tblUsers, $arrUpdate);

        if($qUpdate){
            return returnResponse('00', 'Sukses merubah password');
        }else{
            return returnResponse('01', 'Gagal merubah password');
        }
    }

    function getPasswordUser(){
        $userId = $this->sessData['user_id'];
        $this->db->select('password');
        $this->db->where('user_id', $userId);
        $query = $this->db->get($this->tblUsers);
        if($query->num_rows() > 0){
            $pass = $query->row()->password;
        }else{
            $pass = '';
        }

        return $pass;
    }

    function resetPasswordUser($params){
        if($this->userType != '0'){
            return returnResponse('01', 'Anda tidak memiliki hak akses');
        }
        if(!isset($params['user_id']) || $params['user_id'] == ''){
            return returnResponse('01', 'User ID wajib di isi');
        }

        $isEksistUser   = $this->isEksistUser($params['user_id']);
        if(!$isEksistUser){
            return returnResponse('01', 'Data user tidak ditemukan');
        }

        $randCharPlain  = randomChar(6);
        $randCharHash   = sha1($randCharPlain);

        $arrUpdate  = array('password' => $randCharHash);
        $this->db->where('user_id', $params['user_id']);
        $qUpdate = $this->db->update($this->tblUsers, $arrUpdate);

        if($qUpdate){
            $arrUpdate['pass_plain'] = $randCharPlain;
            return returnResponse('00', 'Sukses reset password', $arrUpdate);
        }else{
            return returnResponse('01', 'Gagal reset password');
        }
    }

    function addUser($params){
        $msgValidate = $this->validateParams($params, 'insert');
        if($msgValidate != ''){
            return returnResponse('01', $msgValidate);
        }

        $isUsernameEksist = $this->isEksistUserByUsername($params['username']);
        if($isUsernameEksist){
            return returnResponse('01', 'Insert data gagal, username sudah terdaftar');
        }

        $arrInsert  = array('username' => $params['username'],
                            'nama_lengkap' => $params['nama_lengkap'],
                            'password' => sha1($params['password']),
                            'user_type' => $params['user_type'],
                            'tgl_update' => date('Y-m-d H:i:s')
                            );

        $qInsert = $this->db->insert($this->tblUsers, $arrInsert);
        if($qInsert){
            return returnResponse('00', 'Insert data sukses');
        }else{
            return returnResponse('01', 'Insert data gagal');
        }
    }

    function editUser($params){
        $msgValidate = $this->validateParams($params, 'update');
        if($msgValidate != ''){
            return returnResponse('01', $msgValidate);
        }

        $userIdOld        = $params['id_old'];
        $usernameOld      = $params['username_old'];
        $isUsernameEksist = $this->isEksistUserByUsername($params['username']);
        if($isUsernameEksist && $usernameOld != $params['username']){
            return returnResponse('01', 'Update data gagal, username sudah terdaftar');
        }

        $arrUpdate  = array('username' => $params['username'],
                            'nama_lengkap' => $params['nama_lengkap'],
                            'user_type' => $params['user_type'],
                            'tgl_update' => date('Y-m-d H:i:s')
                            );

        $this->db->where('user_id', $userIdOld);
        $qUpdate = $this->db->update($this->tblUsers, $arrUpdate);
        if($qUpdate){
            return returnResponse('00', 'Update data sukses');
        }else{
            return returnResponse('01', 'Update data gagal');
        }
    }

    function deleteDataUser($params){
        if(!isset($params['id']) || !is_array($params['id'])){
            return returnResponse('01', 'Parameter yang anda kirim salah');
        }
        if(count($params['id']) <= 0){
            return returnResponse('01', 'Data tidak ditemukan');
        }

        $jmlSccs = 0;
        $jmlErr  = 0;
        $dataArr = $params['id'];
        $jmlData = count($dataArr);
        for ($i=0; $i < $jmlData; $i++) {
            $this->db->where('user_id', $dataArr[$i]);
            $qDelete = $this->db->delete($this->tblUsers);
            if($qDelete){
                $jmlSccs++;
            }else{
                $jmlErr++;
            }
        }

        return returnResponse('00', 'Sukses delete '.$jmlSccs.' data, Gagal delete '.$jmlErr.' data');
    }

    function isEksistUser($userId){
        $this->db->select('count(user_id) as jml_data');
        $this->db->where('user_id', $userId);
        $query = $this->db->get($this->tblUsers);
        if($query->row()->jml_data <= 0){
            return false;
        }else{
            return true;
        }
    }

    function isEksistUserByUsername($username){
        $this->db->select('count(user_id) as jml_data');
        $this->db->where('username', $username);
        $query = $this->db->get($this->tblUsers);
        if($query->row()->jml_data <= 0){
            return false;
        }else{
            return true;
        }
    }

    private function validateParams($params, $type){
        if($this->userType != '0'){
            return 'Anda tidak memiliki hak akses';
        }
        if(!isset($params['username']) || $params['username'] == ''){
            return 'Username wajib di isi';
        }
        if(!isset($params['nama_lengkap']) || $params['nama_lengkap'] == ''){
            return 'Nama Lengkap wajib di isi';
        }
        if(!isset($params['password']) || $params['password'] == ''){
            return 'Password wajib di isi';
        }

        $isValidUsername = validateUsername($params['username']);
        if($isValidUsername == 0){
            return 'Username tidak valid, hanya boleh huruf, angka dan underscore';
        }

        if($type == 'update'){
            if(!isset($params['id_old']) || $params['id_old'] == ''){
                return 'User ID wajib di isi';
            }
        }

        return '';
    }

}
