<?php

/*
 * *************************************************
 * Copyright (C) 2021 Earworks.                    *
 * Codeigniter Project Template Modification       *
 * Please contact our email for more information : *
 * contact@earworks.co.id                          *
 * *************************************************
 */

defined('BASEPATH') OR exit('No direct script access allowed');
use Illuminate\Database\Capsule\Manager as Capsule;
/**
 * Description of Users
 *
 * @author Andhy Taslin <andhy@earworks.co.id>
 * @since 1.0
 */
class Users extends MY_Controller {

    /**
     * Base Url in this controller
     * @var string 
     */
    public $base = 'users/index';

    /**
     * Pre Load required file
     */
    public function __construct() {
        parent::__construct();
        $this->load->model(['user_role_model']);
        $this->load->helper(['form', 'pagination']);
    }

    public function index($pages = 1) {
        $this->granted_backoffice(User_model::ACCESS_USER_LIST);
        $query = User_model::get_dbo('users')
                ->leftJoin('user_profile', 'users.id', '=', 'user_profile.user_id');

        $query_pagination = query_pagination($query, [
            'per_page' => $this->get('show', 20),
            'pages' => $pages,
            'order' => $this->get('order', 'id'),
            'keyword' => $this->get('keyword'),
            'search_field' => ['users.username', 'user_profile.name', 'user_profile.email', 'user_profile.phone', 'users.status'],
            'uri_segment' => 3,
            'base_url' => base_url($this->base)
        ]);

        Ci::view(__METHOD__, [
            'query_pagination' => $query_pagination,
            'pagination' => create_pagination($query_pagination),
            'redir' => '?redir=' . urlencode(current_url() . url_query())
        ]);
    }

    public function create() {
        $this->granted_backoffice(User_model::ACCESS_USER_CREATE);
        $model = new User_model();
        $profile_model = new User_profile_model();
        // Post Data
        $data_user = [
            'username' => $this->post('username'),
            'password_default' => $this->post('password_default'),
            'status' => $this->post('status'),
        ];
        $data_profile = [
            'name' => $this->post('name'),
            'email' => $this->post('email'),
            'phone' => $this->post('phone'),
            'address' => $this->post('address'),
            'city' => $this->post('city')
        ];
        $roles = $this->post('roles');
        // validate data
        $validate = $this->validate_form(['name', 'email', 'username', 'password_default'], false);
        // processing data
        if ($validate === true) { // must exact true type data
            Capsule::beginTransaction();
            // save user data
            $this->load->helper('hash');
            $data_user['password'] = run_hash($data_user['password_default']);
            $model->save_update($data_user);
            // save profile user
            $data_profile['user_id'] = $model->id;
            $data_profile['avatar'] = 'user.png';
            $data_profile['phone'] = $data_profile['phone'] ? phone($data_profile['phone']) : null;
            $profile_model->save_update($data_profile);
            // save role
            User_role_model::arrange($model->id, $roles);
            // Commit data
            Capsule::commit();
            // default (false) = don't encode url (for redirect)
            redirect($this->get_redir());
        } elseif ($validate[static::$field_status] === static::CODE_INVALID_PARAMETER) {
            $this->_show_alert($validate);
        }
        // get master role
        $role_list = Role_model::get_dbo()->get();

        Ci::view(__METHOD__, [
            'data' => array_merge($data_profile, $data_user),
            'redir' => $this->get_redir(true), // true = encode url (for display)
            'model' => $model,
            'profile_model' => $profile_model,
            'role_list' => $role_list
        ]);
    }

    public function update($id = null) {
        $this->granted_backoffice(User_model::ACCESS_USER_UPDATE);
        $model = $this->_find($id);

        $profile_model = $model->profile;
        // post data
        $data_user = [
            'username' => $this->post('username', $model->username),
            'password_default' => $this->post('password_default', $model->password_default),
            'status' => $this->post('status', $model->status)
        ];
        $data_profile = [
            'name' => $this->post('name', $profile_model->name),
            'email' => $this->post('email', $profile_model->email),
            'phone' => $this->post('phone', $profile_model->phone),
            'address' => $this->post('address', $profile_model->address),
            'city' => $this->post('city', $profile_model->city)
        ];
        $roles = $this->post('roles');
        // validate data
        $validate = $this->validate_form(['username', 'password_default', 'name', 'email'], false);
        // prosessing data
        if ($validate === true) {
            Capsule::beginTransaction();
            // save user data
            if ($data_user['password_default']) {
                    $this->load->helper('hash');
                    $data_user['password'] = run_hash($data_user['password_default']);
                }
            $model->save_update($data_user);
            // save user profile
            $data_profile['phone'] = $data_profile['phone'] ? phone($data_profile['phone']) : null;
            $profile_model->save_update($data_profile);
            // save roles
            User_role_model::arrange($model->id, $roles);
            // commit save
            Capsule::commit();
            // default (false) = don't encode url (for redirect)
            redirect($this->get_redir());
        } elseif ($validate[static::$field_status] === static::CODE_INVALID_PARAMETER) {
            $this->_show_alert($validate);
        }
        // get master role
        $role_list = Role_model::get_dbo()->get();

        Ci::view(__METHOD__, [
            'data' => array_merge($data_user, $data_profile),
            'redir' => $this->get_redir(true), // true = encode url (for display)
            'model' => $model,
            'profile_model' => $profile_model,
            'role_list' => $role_list
        ]);
    }

    public function delete($id = null) {
        $this->granted_backoffice(User_model::ACCESS_USER_DELETE);
        $model = $this->_find($id);

        Capsule::beginTransaction();
        // delete user profile
        User_profile_model::get_dbo()->where('user_id', $id)->delete();
        // delete user roles
        User_role_model::get_dbo()->where('user_id', $id)->delete();
        // delete user
        $model->delete();
        // commit save data
        Capsule::commit();
        // default (false) = don't encode url (for redirect)
        redirect($this->get_redir());
    }

    protected function _delete_all($ids) {
        $this->granted_backoffice(User_model::ACCESS_USER_DELETE);
        Capsule::beginTransaction();
        // delete profiles
        User_profile_model::get_dbo()->whereIn('user_id', $ids)->delete();
        // delete roles
        User_role_model::get_dbo()->whereIn('user_id', $ids)->delete();
        // delete users
        User_model::get_dbo()->whereIn('id', $ids)->delete();
        // commit delete data
        Capsule::commit();
        // default (false) = don't encode url (for redirect)
        redirect($this->get_redir());
    }

    private function _find($id = null) {
        $model = User_model::get_dbo()->where('id', $id)->first();
        if (!$model || !$id) {
            // show err
            redirect($this->base);
        }
        return $model;
    }

}
