<?php

defined('BASEPATH') or exit('No direct script access allowed');
class System_users_model extends CI_Model
{

    public function __construct()
    {
        parent::__construct();
        $this->load->database();
        $this->load->library(['ion_auth', 'form_validation']);
        $this->load->helper(['url', 'language', 'function_helper']);
    }

    function update_user($data)
    {
        $data = escape_array($data);

        if (isset($data['edit_system_user'])) {

            $user_data = [
                'ip_address' => $this->input->ip_address(),
                'mobile' => $data['mobile'],
                'email' => $data['email'],
                'username' => $data['username'],
                'active' => 1
            ];
            if (isset($data['password']) && !empty($data['password']) && $data['password'] != "") {
                $password = $this->ion_auth->hash_password($data['password']);
                $user_data['password'] = $password;
            }
            $permission_data = [
                'role' => $data['role']
            ];
            if ($data['role'] > 0) {
                $permission_data['permissions'] = json_encode($data['permissions']);
            } else {
                $permission_data['permissions'] = NULL;
            }
            $this->db->set($permission_data)->where('user_id', $data['edit_system_user'])->update('user_permissions');
            $this->db->set($user_data)->where('id', $data['edit_system_user'])->update('users');
        } else {

            $password = $this->ion_auth->hash_password($data['password']);

            $user_data = [
                'ip_address' => $this->input->ip_address(),
                'mobile' => $data['mobile'],
                'email' => $data['email'],
                'username' => $data['username'],
                'password' => $password,
                'active' => 1,
                'created_on' => strtotime(date("Y-m-d H:i:s"))
            ];
            $permission_data = [
                'role' => $data['role']
            ];
            if ($data['role'] > 0) {
                $permission_data['permissions'] = json_encode($data['permissions']);
            } else {
                $permission_data['permissions'] = NULL;
            }

            $this->db->insert('users', $user_data);
            $last_id = $this->db->insert_id();
            $this->db->insert('users_groups', ['user_id' => $last_id, 'group_id' => '1']);
            $permission_data['user_id'] = $last_id;
            $this->db->insert('user_permissions', $permission_data);
        }
    }

    function get_users_list()
    {
        $offset = 0;
        $limit = 10;
        $sort = 'id';
        $order = 'ASC';
        $multipleWhere = '';


        if (isset($_GET['offset']))
            $offset = $_GET['offset'];
        if (isset($_GET['limit']))
            $limit = $_GET['limit'];

        if (isset($_GET['sort']))
            if ($_GET['sort'] == 'id') {
                $sort = "id";
            } else {
                $sort = $_GET['sort'];
            }
        if (isset($_GET['order']))
            $order = $_GET['order'];

        if (isset($_GET['search']) and $_GET['search'] != '') {
            $search = $_GET['search'];
            $multipleWhere = ['up.`id`' => $search, '`u.username`' => $search, 'u.`mobile`' => $search];
        }

        $count_res = $this->db->select(' COUNT(up.id) as `total` ')->join('users u', 'up.user_id=u.id');


        if (isset($multipleWhere) && !empty($multipleWhere)) {
            $count_res->or_like($multipleWhere);
        }
        if (isset($where) && !empty($where)) {
            $count_res->where($where);
        }

        $sys_user_count = $count_res->get('user_permissions up')->result_array();

        foreach ($sys_user_count as $row) {
            $total = $row['total'];
        }

        $search_res = $this->db->select('up.id,u.id as user_id,u.username,u.email,up.role,u.mobile,,up.permissions,u.active')->join('users u', 'up.user_id=u.id');
        if (isset($multipleWhere) && !empty($multipleWhere)) {
            $search_res->or_like($multipleWhere);
        }
        if (isset($where) && !empty($where)) {
            $search_res->where($where);
        }

        $sys_search_res = $search_res->order_by($sort, "asc")->limit($limit, $offset)->get('user_permissions up')->result_array();

        $bulkData = array();
        $bulkData['total'] = $total;
        $rows = array();
        $tempRow = array();
        $current_user_id = $this->ion_auth->user()->row()->id;
        $userData = fetch_details('user_permissions', ['user_id' => $current_user_id]);
        foreach ($sys_search_res as $row) {
            $operate = '';
            if ($current_user_id != $row['user_id'] && $userData[0]['role'] == 0) {

                $operate = '<div class="dropdown">
        <a class="" href="#" role="button" id="dropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
            <i class="fas fa-ellipsis-v"></i>
        </a>
        <div class="dropdown-menu" aria-labelledby="dropdownMenuLink">
        <a href="javascript:void(0)" class="edit_btn dropdown-item"  title="Edit" data-id="' . $row['id'] . '" data-url="admin/system_users/add_system_users"><i class="fa fa-pen"> </i> Edit</a>
            <a href="javascript:void(0)" class=" dropdown-item" id="delete-system-users" data-id=' . $row['user_id']  . ' title="Delete" ><i class="fa fa-trash"></i> Delete</a></div>';

                if ($row['active'] == '1') {
                    $tempRow['status'] = '<a class="badge bg-success text-white" ></a>';
                    $tempRow['status'] .= '<a class="form-switch update_active_status " data-table="users" title="Deactivate" href="javascript:void(0)" data-id="' . $row['user_id'] . '" data-status="' . $row['active'] . '" ><input class="form-check-input " type="checkbox" role="switch" checked></a>';
                } else {
                    $tempRow['status'] = '<a class="badge bg-danger text-white" ></a>';
                    $tempRow['status'] .= '<a class="form-switch update_active_status mr-1 mb-1" data-table="users" title="Deactivate" href="javascript:void(0)" data-id="' . $row['user_id'] . '" data-status="' . $row['active'] . '" ><input class="form-check-input " type="checkbox" role="switch" ></a>';
                }

            }

            $tempRow['id'] = $row['id'];
            $tempRow['user_id'] = $row['user_id'];
            $tempRow['username'] = ucfirst($row['username']);
           
            if (isset($row['email']) && !empty($row['email']) && $row['email'] != "" && $row['email'] != " ") {
                $tempRow['email'] = (defined('ALLOW_MODIFICATION') && ALLOW_MODIFICATION == 0) ? str_repeat("X", strlen($row['email']) - 3) . substr($row['email'], -3) : ucfirst($row['email']);
            } else {
                $tempRow['email'] = "";
            }
            if (isset($row['mobile']) && !empty($row['mobile']) && $row['mobile'] != "" && $row['mobile'] != " ") {
                $tempRow['mobile'] =  (defined('ALLOW_MODIFICATION') && ALLOW_MODIFICATION == 0) ? str_repeat("X", strlen($row['mobile']) - 3) . substr($row['mobile'], -3) : $row['mobile'];
            }else{
                $tempRow['mobile'] = "";
            }

            if ($row['role'] == '0') {
                $row['role'] = "<span class='badge bg-primary'>Super Admin</span>";
            }
            if ($row['role'] == '1') {
                $row['role'] = "<span class='badge bg-danger'>Admin</span>";
            }
            if ($row['role'] == '2') {
                $row['role'] = "<span class='badge bg-warning'>Editor</span>";
            }
            if ($row['role'] == '3') {
                $row['role'] = "<span class='badge bg-info'>Supporter</span>";
            }


            $tempRow['role'] = $row['role'];
            $tempRow['permissions'] = $row['permissions'];
            $tempRow['operate'] = $operate;
            $rows[] = $tempRow;
        }

        $bulkData['rows'] = $rows;
        print_r(json_encode($bulkData));
    }
}
