<?php namespace App\Controllers\Admin;

class Authorize extends AdminController
{
	private $mObj;
	
	public function __construct(){		
        $this->mObj = model('App\Models\Admin\AuthorizeModel');
		$this->menu_id = 5;
    }
	
	public function user($user_id=""){
		$this->allowed('is_list');
		if($this->request->getMethod() === 'post'){
			$post_data = $this->request->getPost();
			if($user_id!=""){
				$this->mObj->save($user_id, $post_data);
				$this->notify_success('Changes Saved Successfully');
				return redirect()->to(get_admin_path('authorize/user/'.$user_id));
			}
		}
		$data['user_list'] = $this->mObj->get_user_list();
		$data['user_dtl'] = $data['role_list'] = [];
		if($user_id != ""){
			$data['user_dtl'] = $this->mObj->get_user_dtl($user_id);
			$data['role_list'] = $this->mObj->get_role_tree($user_id);
			$data['roles_table_rows'] = $this->generate_role_table_rows($data['role_list']);
		}
		$data['footer_includes'] = ['authorize_list_js'];		
		echo $this->view_inner_template('authorize_list',$data);
	}
	
	private function generate_role_table_rows($role_tree){
		$html = ''; $i=0; $level=0;
		foreach($role_tree as $key => $item){
			$i++;
			$data['role_dtl'] = $item;
			$data['role_dtl']['sr_no'] = $i;
			$data['role_dtl']['level'] = $level;
			if(isset($item['children'])){
				unset($data['role_dtl']['children']);
				$html .= view('admin/role_heading_row',$data);
				$html .= $this->generate_role_table_subrows($item['children'], $i , $level);
			}else{
				$html .= view('admin/role_action_row',$data);
			}
		}
		return $html;
	}
	
	private function generate_role_table_subrows($item_list, &$i, $level, $html = ""){
		$level++;
		foreach($item_list as $key => $item) {
			$i++;
			$data['role_dtl'] = $item;
			$data['role_dtl']['sr_no'] = $i;
			$data['role_dtl']['level'] = $level;
			if(isset($item['children'])) {				
				unset($data['role_dtl']['children']);
				$html .= view('admin/role_heading_row',$data);				
				$html .= $this->generate_role_table_subrows($item['children'], $i, $level++);
			} else {
				$html .= view('admin/role_action_row',$data);
			}
		}
		return $html;
	}
}