<?php namespace App\Models\Admin;

class AuthorizeModel extends AdminModel{
	private $table;
	
    public function __construct(){
        parent::__construct();
		$this->table = "authorization";
    }
	
	public function get_user_list(){
		$builder = $this->db->table('user');
		$query = $builder->select('user_id, user_type, name, status')
					->where('user_type !=','Developer')
					->where('user_type !=','Admin')
					->where('is_deleted','No')
					->orderBy('name','ASC')
					->get();
		return $query->getResultArray();
	}
	
	public function get_user_dtl($user_id){
		$builder = $this->db->table('user');
		$query = $builder->where('user_id',$user_id)->get();
		return $query->getRowArray();
	}
	
	public function get_role_tree($user_id){
		$builder = $this->db->table('menu AS m');
		$query = $builder->select('m.menu_id,m.parent_menu_id,m.title,a.authorization_id,a.is_add,a.is_edit,a.is_list')
				->join('authorization AS a','m.menu_id=a.menu_id AND a.user_id='.$user_id,'left')
				->where('m.is_deleted','No')
				->where('m.user_type !=','Developer')
				->orderBy('m.sequence','ASC')
				->get();
		$rec_list = $query->getResultArray();
		return $this->build_menu_tree($rec_list,0);
	}
	
	public function save($user_id,$post_data){
		$batch_up_data = $batch_in_data = [];
		$total_roles = count($post_data['menu_id']);
		$selected_list_role = $post_data['is_list'] ?? [];
		$selected_add_role = $post_data['is_add'] ?? [];
		$selected_edit_role = $post_data['is_edit'] ?? [];
		for($i=0; $i<$total_roles; $i++){
			$data = [];
			$data['is_list'] = in_array($post_data['menu_id'][$i],$selected_list_role) ? "Yes" : "No";
			$data['is_add'] = in_array($post_data['menu_id'][$i],$selected_add_role) ? "Yes" : "No";
			$data['is_edit'] = in_array($post_data['menu_id'][$i],$selected_edit_role) ? "Yes" : "No";
			if($post_data['authorization_id'][$i]){
				$data['authorization_id'] = $post_data['authorization_id'][$i];
				$this->add_update_log($data);
				array_push($batch_up_data,$data);
			}else{
				$data['user_id'] = $user_id;
				$data['menu_id'] = $post_data['menu_id'][$i];
				$this->add_insert_log($data);
				array_push($batch_in_data,$data);
			}
		}
		if($batch_in_data){
			$builder = $this->db->table($this->table);
			$builder->insertBatch($batch_in_data);
		}
		if($batch_up_data){
			$builder = $this->db->table($this->table);
			$builder->updateBatch($batch_up_data,"authorization_id");
		}
	}
}