<?php

use app\libraries\TenantHelper;
use app\libraries\Tenants;
use app\libraries\Userstamp;

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Employee_model extends MY_Model
{

    use Tenants;

    public $short = "e";
    public $table;
    public $tbl;
    public $database;
	public $fullTbl;
	public $fullTable;

    //    protected $table = 'rbac_users';
    // TODO: place this value to setting_center table
    const days_before_payment_next_month = 7;

    public function __construct()
    {
        parent::__construct();
        $this->load->model('Tenant_model');
        $this->load->model('Rbac_user_role_model');
        $this->load->model('Rbac_role_model');
        $this->load->model('System_admin_model');
        $this->load->model('System_admin_tenant_model');
        $this->load->model('System_admin_landing_tenant_model');
        $this->load->model('Employee_income_lookup_model');

		$this->database = $this->getTenantNo();
        $this->tbl = 'rbac_users';
        $this->table = $this->tbl . ' ' . $this->short;
		$this->fullTbl = $this->tbl;
		$this->fullTable = $this->table;
    }

    public function listing()
    {
        $this->tenant();
        $employees = $this->db->from($this->fullTable)
            ->join($this->table_prefix . 'employee_income_lookup eil', 'e.id = eil.employee_id', 'left')
            ->join($this->table_prefix . 'employee_income_type eit', 'eil.employee_income_type_id = eit.id', 'left')
            ->select('e.*, eit.name AS income_type')
            ->get()->result_array();
        if (empty($employees)) {
            return [];
        }
        foreach ($employees as $k => $employee) {
            $employees[$k]['status'] = $this->status[$employee['status']];
        }
        return $employees;
    }

    public function listing_siteadmin()
    {
        //        $this->tenant();
        $res = [];
        foreach ($this->Tenant_model->listing() as $tenant) {
            $tenantNo = $tenant['code'];
            $tenantName = $tenant['name'];


            $this->tenant_reconnect($tenantNo);

            $employees = $this->db->from($this->fullTable)
                ->join($this->table_prefix . 'employee_income_lookup eil', 'e.id = eil.employee_id', 'left')
                ->join($this->table_prefix . 'employee_income_type eit', 'eil.employee_income_type_id = eit.id', 'left')
                ->select(sprintf('e.*, "%s" AS tenant_no, "%s" AS tenant_name, eit.name AS income_type', $tenantNo, $tenantName))
                ->get()->result_array();

            if (empty($employees)) {
                continue;
            }

            foreach ($employees as $employee) {
                $employee['status'] = $this->status[$employee['status']];
                array_push($res, $employee);
            }
        }

        $this->tenant_reset();
        return $res;
    }

    public function detail($id)
    {
        $this->tenant();

        return $this->db->from($this->fullTbl)->where('id', $id)->get()->row_array();
    }

    public function detail_tenant($id, $tenantNo)
    {
        $this->tenant_reconnect($tenantNo);

        $res = $this->db->from($this->fullTbl)->where('id', $id)->get()->row_array();

        $this->tenant_reset();

        return $res;
    }

    public function detail_username_tenant($username, $tenantNo)
    {
        $this->tenant_reconnect($tenantNo);

        $res = $this->db->from($this->fullTbl)->where('username', $username)->get()->row_array();

        $this->tenant_reset();

        return $res;
    }

    public function create($params, $tenantNo)
    {
        $this->tenant_reconnect($tenantNo);

        unset($params['id']);
        unset($params['isSiteAdmin']);
        unset($params['tenant_no']);
        Userstamp::$timestamp = true;
        $params = Userstamp::create($params, 'created_by', 'create_time');
        $this->db->insert($this->fullTbl, $params);

        $params['id'] = $this->db->insert_id();

        $this->tenant_reset();

        return $params;
    }
	
	 public function replace($params, $tenantNo)
    {
        $this->tenant_reconnect($tenantNo);

        unset($params['id']);
        unset($params['isSiteAdmin']);
        unset($params['tenant_no']);
        Userstamp::$timestamp = true;
        $params = Userstamp::create($params, 'created_by', 'create_time');
        $this->db->replace($this->fullTbl, $params);

        $params['id'] = $this->db->insert_id();

        $this->tenant_reset();

        return $params;
    }

    public function update($params, $id, $tenantNo)
    {
        $this->tenant_reconnect($tenantNo);

        Userstamp::$timestamp = true;
        $params = Userstamp::update($params, 'updated_by', 'update_time');
        $this->db->update($this->fullTbl, $params, ['id' => $id]);

        $params['id'] = $id;

        $this->tenant_reset();

        return $params;
    }

    public function create_in_employee_tenant($params)
    {
        $_params = [
            'username' => $params['username'],
            'password' => sha1($params['password']),
            'display_name' => $params['display_name'],
            'chi_name' => $params['chi_name'],
            'eng_name' => $params['eng_name'],
            'display_name' => $params['display_name'],
            'gender' => $params['gender'],
            'remark' => $params['remark'],
            'isSiteAdmin' => $params['isSiteAdmin'],
            'tenant_no' => $params['tenant_no'],
//			'role_id' => $params['role_id']
        ];

        // Account need sync
        $_params = $this->create($_params, $params['tenant_no']);

        $this->System_admin_model->create_in_employee_tenant($_params);

        $params['user_id'] = $_params['id'];
        $role = $this->Rbac_role_model->detail_tenant($params['role_id'], $params['tenant_no']);

        if ($role['site_admin'] == 1) {
            // Account
            $this->create_in_employee_tenant_siteadmin($_params, $params['tenant_no']);
            $this->Rbac_user_role_model->create_in_employee_tenant_siteadmin($params);
            $this->System_admin_landing_tenant_model->create_in_employee_tenant($params);
            $this->System_admin_tenant_model->create_in_employee_tenant_siteadmin($params);

            // Income Lookup
            $this->Employee_income_lookup_model->create_in_employee_tenant_siteadmin($params);
        } else {
            // Account
            $this->Rbac_user_role_model->create_in_employee_tenant($params, $params['tenant_no']);
            $this->System_admin_landing_tenant_model->create_in_employee_tenant($params);
            $this->System_admin_tenant_model->create_in_employee_tenant($params);

            // Income Lookup
            $this->Employee_income_lookup_model->create_in_employee_tenant($params, $params['tenant_no']);
        }

        $this->db->trans_commit();
    }

    public function create_in_employee_tenant_siteadmin($params, $tenantNo)
    {
        $this->load->model('Tenant_model');
        $tenants = $this->Tenant_model->listing();
        foreach ($tenants as $tenant) {
            if ($tenant['code'] == $tenantNo) {
                continue;
            }
            $this->create($params, $tenant['code']);
        }

        $this->tenant_reset();
        return true;
    }

    public function update_in_employee_tenant($params, $id)
    {
        $this->db->trans_strict(TRUE);

        $this->db->trans_begin();
        try {

            $_params = [
                'username' => $params['username'],
                'display_name' => $params['display_name'],
                'chi_name' => $params['chi_name'],
                'eng_name' => $params['eng_name'],
                'display_name' => $params['display_name'],
                'gender' => $params['gender'],
                'remark' => $params['remark']
            ];

            if (!empty($params['password'])) {
                $_params['password'] = $params['password'];
            }

            // Account need sync
			
            $_params = $this->update($_params, $id, $params['tenant_no']);
			
            $this->tenant_reset();

            $this->System_admin_model->update_in_employee_tenant($_params);
			//up to this is fine 
            $params['user_id'] = $_params['id'];
			$oldRole = $this->Rbac_role_model->detail_userId_tenant($id, $params['tenant_no']);
			
            $role = $this->Rbac_role_model->detail_tenant($params['role_id'], $params['tenant_no']);
			
            if (empty($oldRole['id'])) {
                $this->Rbac_user_role_model->create_in_employee_tenant($params, $params['tenant_no']);
            } else {
                $this->Rbac_user_role_model->update_in_employee_tenant($params, $params['tenant_no']);
            }

            $this->Employee_income_lookup_model->create_or_update_in_employee_tenant($params, $params['tenant_no']);

            switch (true) {
                case empty($oldRole['id']) && $role['site_admin'] != 1 && $role['tenant'] != 1:
                    $this->update_in_employee_tenant_as_non_siteadmin($_params, $params['tenant_no']);
                    $this->System_admin_tenant_model->update_in_employee_tenant_as_non_siteadmin($params);
                    $this->Rbac_user_role_model->update_in_employee_tenant($params, $params['tenant_no']);
                    $this->Rbac_user_role_model->update_in_employee_tenant_as_non_siteadmin($params, $params['tenant_no']);

                    break;
                    // No change
                case $oldRole['id'] == $params['role_id']:
                    // $this->Employee_income_lookup_model->create_or_update_in_employee_tenant($params, $params['tenant_no']);
                    break;
                case $role['site_admin'] == 1:
					//$this->Rbac_role_model->checker($_params);
					$_params['tenant_no'] = $params['tenant_no'];
                    $this->update_in_employee_tenant_as_siteadmin($_params);
					unset($_params['tenant_no']);
                    $this->System_admin_tenant_model->update_in_employee_tenant_as_siteadmin($params);
                    $this->Rbac_user_role_model->update_in_employee_tenant($params, $params['tenant_no']);
                    $this->Rbac_user_role_model->update_in_employee_tenant_as_siteadmin($params);

                    // $this->Employee_income_lookup_model->update_in_employee_tenant_as_siteadmin($params, $params['tenant_no']);
                    break;
                case $oldRole['site_admin'] == 1 || $oldRole['tenant'] == 1:
                    // $this->Employee_income_lookup_model->create_or_update_in_employee_tenant_as_non_siteadmin($params, $params['tenant_no']);
                    break;
            }

            $this->db->trans_commit();
        } catch (Exception $ex) {
            $this->db->trans_rollback();
            log_message('log_error', $ex->getMessage());
        }
    }

    public function update_in_employee_tenant_as_non_siteadmin($params, $tenantNo)
    {
        $this->load->model('Tenant_model');

        $tenants = $this->Tenant_model->listing();

        foreach ($tenants as $tenant) {
            if ($tenant['code'] == $tenantNo) {
                continue;
            }

            $this->tenant_reconnect($tenant['code']);

            $this->db->where('username', $params['username'])->delete();

            $this->tenant_reset();
        }

        return true;
    }

    public function update_in_employee_tenant_as_siteadmin($params)
    {
        $this->load->model('Tenant_model');
        $tenants = $this->Tenant_model->listing();
        foreach ($tenants as $tenant) {
            if ($tenant['code'] == $params['tenant_no']) {
                continue;
            }

            $this->replace($params, $tenant['code']);
        }
        return true;
    }
}
