<?php
namespace App\Controllers\Admin;

use CodeIgniter\Controller;
use CodeIgniter\HTTP\CLIRequest;
use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;
/**
 * Class BaseController
 *
 * BaseController provides a convenient place for loading components
 * and performing functions that are needed by all your controllers.
 * Extend this class in any new controllers:
 *     class Home extends BaseController
 *
 * For security be sure to declare any new methods as protected or private.
 *
 * @package CodeIgniter
 */

class AdminController extends Controller
{

	/**
	 * An array of helpers to be loaded automatically upon
	 * class instantiation. These helpers will be available
	 * to all other controllers that extend BaseController.
	 *
	 * @var array
	 */
	protected $helpers = ['project','form','url'];

	/* Project Custom settings */
	protected $project; 
	
	/* Admin Model */
	protected $amObj;
	
	/* Bussiness logic model */
	public $cmObj;
	
	/* Current module menu_id */
	protected $menu_id;
	
	/* Store user roles */
	protected $user_roles;
	
	// Router
	protected $router;
	
	// Request
	public $request;
	
	// URI
	//public $uri;
	/**
	 * Constructor.
	 */
	public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
	{
		// Do Not Edit This Line
		parent::initController($request, $response, $logger);

		//--------------------------------------------------------------------
		// Preload any models, libraries, etc, here.
		//--------------------------------------------------------------------
		// E.g.:
		$this->session = \Config\Services::session();		 
		$this->project = config( 'Config\\Project' );
		$this->router = \Config\Services::router();
		//$this->uri = new \CodeIgniter\HTTP\URI();
		// Admin Model
		$this->amObj = model('App\Models\Admin\AdminModel');
		// Common Model
		$this->cmObj = new \App\Models\Admin\CommonModel();
		// Set user roles
		$this->set_user_roles();
	}

	// custom methods
	protected function view_inner_template($content_file="",$data=array()){
		$this->set_default_data($data);
		$this->set_required_class_obj($data);
		$menu_dtl = $this->amObj->get_menu_dtl();
		$data['menu_html'] = $this->get_header_menu_html($menu_dtl);
		$data['menu_breadcrumb'] = $this->get_menu_breadcrumb($menu_dtl['active_link_path']);		
		
		$html =  view('admin/template/inner/html_start',$data);
		$html .= view('admin/template/inner/header',$data);
		$html .= '<!--begin::Content-->';
		if(is_array($content_file)){
			foreach($content_file as $file_name){
				$html .= view('admin/'.$file_name,$data);
			}
		}else{
			$html .= view('admin/'.$content_file,$data);
		}
		$html .= '<!--end::Content-->';
		$html .= view('admin/template/inner/footer',$data);
		$html .= view('admin/template/inner/html_end',$data);
		return $html;
	}
	
	protected function view_print_template($content_file="",$data=array()){
		$this->set_default_data($data);		
		$html =  view('admin/template/print/header',$data);
		if(is_array($content_file)){
			foreach($content_file as $file_name){
				$html .= view('admin/'.$file_name,$data);
			}
		}else{
			$html .= view('admin/'.$content_file,$data);
		}
		$html .= '<!--end::Content-->';
		$html .= view('admin/template/print/footer',$data);
		return $html;
	}
	
	protected function view_partial($content_file="",$data=array()){
		$this->set_required_class_obj($data);
		$html = '';
		if(is_array($content_file)){
			foreach($content_file as $file_name){
				$html .= view('admin/'.$file_name,$data);
			}
		}else{
			$html .= view('admin/'.$content_file,$data);
		}
		return $html;
	}
	
	protected function view_login_template($content_file="",$data=array()){
		$this->set_default_data($data);
		$this->set_required_class_obj($data);
		echo view('admin/template/login/header',$data);
		echo view('admin/template/login/left_container_project_detail',$data);
		if(is_array($content_file)){
			foreach($content_file as $file_name){
				echo view('admin/'.$file_name,$data);
			}
		}else{
			echo view('admin/'.$content_file,$data);
		}
		echo view('admin/template/login/footer',$data);
	}	
	
	private function set_default_data(&$data=array()){
		// Set Meta content 
		$data['meta_data']['title'] = $data['meta_data']['title'] ?? $this->project->default_meta_title;
		$data['meta_data']['description'] = $data['meta_data']['description'] ?? $this->project->default_meta_description;
		$data['meta_data']['keywords'] = $data['meta_data']['keywords'] ?? $this->project->default_meta_keywords;
		// Set Plugins
		$data['plugins'] = $data['plugins'] ?? [];
		
		return $data;
	}
	
	private function set_required_class_obj(&$data){
		$data['project'] = $this->project;
		$data['cmObj'] = $this->cmObj;
		$data['session'] = $this->session;
		$data['router'] = $this->router;
		$data['acObj'] = $this;
		$data['validation'] = \Config\Services::validation();
	}
	
	public function get_header_menu_html($menu_dtl){
		$html = '<ul class="menu-nav">'."\n";
		foreach($menu_dtl['tree'] as $key => $item){
			$active_class = $item['menu_id']==$menu_dtl['active_link_path'][0]['menu_id'] ? 'menu-item-active' : '';
			if(isset($item['children'])){
				$html .= '<li class="menu-item menu-item-submenu menu-item-rel '.$active_class.'" data-menu-toggle="hover" aria-haspopup="true">'."\n";
				$html .= '<a href="javascript:;" class="menu-link menu-toggle">'."\n";
				$html .= '<span class="menu-text">'.$item['title'].'</span>'."\n";
				$html .= '<span class="menu-desc"></span>'."\n";
				$html .= '<i class="menu-arrow"></i>'."\n";
				$html .= '</a>'."\n";
				$html .= '<div class="menu-submenu menu-submenu-classic menu-submenu-left">'."\n";
				$html .= $this->get_submenu_html($item['children']);
				$html .= '</div>'."\n";
				$html .= '</li>'."\n";
			}else if( ! empty($item['url'])){
				$url = $item['external_url']=="Yes" ? $item['url'] : get_admin_path($item['url']);
				$target = $item['open_in_new_tab']=="Yes" ? 'target="_blank"' : '';
				$icon = $item['icon']!="" ? $item['icon'] : '';
				$html .= '<li class="menu-item '.$active_class.'" aria-haspopup="true">'."\n";
				$html .= '<a href="'.$url.'" '.$target.' class="menu-link">'."\n";
				$html .= '<span class="menu-text">'.$item['title'].'</span>'."\n";
				$html .= '</a>'."\n";
				$html .= '</li>'."\n";
			}
		}
		$html .= '</ul>'."\n";
		return $html;
	}
	
	private function get_submenu_html($item_list, $html = ""){
		$html .= '<ul class="menu-subnav">'."\n";
		foreach($item_list as $key => $item) {
			if(isset($item['children'])) {
				$html .= '<li class="menu-item menu-item-submenu" data-menu-toggle="hover" aria-haspopup="true">'."\n";
				$html .= '<a href="javascript:;" class="menu-link menu-toggle">'."\n";
				if($item['icon']!=""){
					$html .= $item['icon'];
				} 
				$html .= '<span class="menu-text">'.$item['title'].'</span>'."\n";
				$html .= '<i class="menu-arrow"></i>'."\n";
				$html .= '</a>'."\n";
				$html .= '<div class="menu-submenu menu-submenu-classic menu-submenu-right">'."\n";
				$html .= $this->get_submenu_html($item['children']);
				$html .=  '</div>'."\n";
				$html .= '</li>'."\n";
			} else if( ! empty($item['url'])){
				$url = $item['external_url']=="Yes" ? $item['url'] : get_admin_path($item['url']);
				$target = $item['open_in_new_tab']=="Yes" ? 'target="_blank"' : '';
				$icon = $item['icon']!="" ? $item['icon'] : '<i class="menu-bullet menu-bullet-dot"><span></span></i>';
				$html .= '<li class="menu-item" aria-haspopup="true">'."\n";
				$html .= '<a href="'.$url.'" '.$target.' class="menu-link">'."\n";
				$html .= $icon;
				$html .= '<span class="menu-text">'.$item['title'].'</span>'."\n";
				$html .= '</a>'."\n";
				$html .= '</li>'."\n";
			}
		}
		$html .= '</ul>'."\n";
		return $html;
	}
	
	private function get_menu_breadcrumb($path_arr){
		$breadcrumb = '';
		foreach($path_arr as $link){
			$breadcrumb .= $link['title'].' > ';
		}
		return rtrim($breadcrumb, ' > ');
	}
	
	protected function notify_success($msg){
		$data['msg'] = $msg;
		$data['type'] = "success";
		$this->session->setFlashdata('notify_alert',$data);
	}
	
	public function allowed($role,$menu_id=""){
		if(in_array($this->session->get('user_type'),['Admin','Developer'])){
			return true;
		}
		if($menu_id=="" && is_null($this->menu_id)){
			return false;
		}
		$menu_id = $menu_id ?: $this->menu_id;
		if(isset($this->user_roles[$menu_id][$role]) && $this->user_roles[$menu_id][$role]=="Yes"){
			return true;
		}
		return false;
	}
	
	private function set_user_roles(){
		$this->user_roles = [];
		if( ! is_null($this->session->get($this->project->session_admin_user_id))){
			$user_roles_list = $this->amObj->get_user_roles();
			foreach($user_roles_list as $role){
				$this->user_roles[$role['menu_id']]['is_list'] = $role['is_list'];
				$this->user_roles[$role['menu_id']]['is_add'] = $role['is_add'];
				$this->user_roles[$role['menu_id']]['is_edit'] = $role['is_edit'];
			}
		}
	}
	
	public function validate_access($role, $menu_id=""){
		if( ! $this->allowed($role, $menu_id)){			
			echo '<script>window.location="'.get_admin_path('secure/logoff').'"</script>';
			exit();
		}
		return true;
	}
}