<?php

/**
 * Base controllers for different purposes
 * 	- MY_Controller: for Frontend Website
 * 	- Admin_Controller: for Admin Panel (require login), extends from MY_Controller
 * 	- API_Controller: for API Site, extends from REST_Controller
 */
class MY_Controller extends MX_Controller {
	// Values to be obtained automatically from router
	public $mModule = '';			// module name (empty = Frontend Website)
	public $mCtrler = 'home';		// current controller
	public $mAction = 'index';		// controller function being called
	public $mMethod = 'GET';			// HTTP request method

	// Config values from config/ci_bootstrap.php
	protected $mConfig = array();
	protected $mBaseUrl = array();
	protected $mSiteName = '';
	protected $mMetaData = array();
	protected $mScripts = array();
	public 	  $mSettings = NULL;
	protected $mStylesheets = array();

	// Values and objects to be overrided or accessible from child controllers
	protected $mPageTitlePrefix = '';
	protected $mPageTitle = '';
	protected $mBodyClass = '';
	protected $mMenu = array();
	protected $mBreadcrumb = array();

	// Multilingual
	protected $mMultilingual = FALSE;
	protected $mLanguage = 'en';
	protected $mAvailableLanguages = array();

	// Data to pass into views
	protected $data = array();

	// Login user
	public $mPageAuth = array();
	public $mUser = NULL;
	public $mUserGroups = array();
	public $mUserMainGroup;
	public $Admin = FALSE;

	// Constructor
	public function __construct()
	{
		parent::__construct();

		// router info
		$this->mCtrler = $this->router->fetch_class();
		$this->mAction = $this->router->fetch_method();
		$this->mMethod = $this->input->server('REQUEST_METHOD');
		$this->load->model('main_model');
		$this->load->model('settings_model');
		$this->load->model('reparation_model');
		$this->mSettings = $this->settings_model->getSettings();
		$this->lang->load('main_lang', $this->mSettings->language);
		$this->lang->load('auth', $this->mSettings->language);
		$this->lang->load('ion_auth', $this->mSettings->language);
		$this->main_model->gen_token();
		// initial setup
		$this->_setup();
	}

	// Setup values from file: config/ci_bootstrap.php
	private function _setup()
	{
		$config = $this->config->item('my_config');
		// load default values
		$this->mBaseUrl = empty($this->mModule) ? base_url() : base_url($this->mModule).'/';
		$this->mSiteName = empty($config['site_name']) ? '' : $config['site_name'];
		$this->mPageTitlePrefix = empty($config['page_title_prefix']) ? '' : $config['page_title_prefix'];
		$this->mPageTitle = empty($config['page_title']) ? '' : $config['page_title'];
		$this->mBodyClass = empty($config['body_class']) ? '' : $config['body_class'];
		$this->mMenu = empty($config['menu']) ? array() : $config['menu'];

		if ($this->mSettings->show_settings_menu) {
			$this->mMenu['settings'] = array(
				'name'		=> 'settings/index',
				'url'		=> 'settings',
				'icon'		=> 'fas fa-cog',
				'children'  => array(
					'settings/index'			=> 'settings/index',
					'auth/index'			=> 'auth/index',
					'auth/user_groups'			=> 'auth/user_groups',
					'repair_statuses/index'			=> 'settings/repair_statuses',
					'tax_rates/index' => 'settings/tax_rates',
					'categories/index' => 'settings/categories',
					'utilities/index' => 'utilities/list_db',
				)
			);
			# code...
		}

        $this->data['users'] = $this->ion_auth->users()->result();
		

		$this->mMetaData = empty($config['meta_data']) ? array() : $config['meta_data'];
		$this->mScripts = empty($config['scripts']) ? array() : $config['scripts'];
		$this->mStylesheets = empty($config['stylesheets']) ? array() : $config['stylesheets'];
		$this->mPageAuth = empty($config['page_auth']) ? array() : $config['page_auth'];
		$this->mTRates = $this->settings_model->getTaxRates();
		$this->theme = $this->mSettings->theme.'/views/';
        if(is_dir(VIEWPATH.$this->mSettings->theme.DIRECTORY_SEPARATOR.'assets'.DIRECTORY_SEPARATOR)) {
            $this->data['assets'] = base_url() . 'themes/' . $this->mSettings->theme . '/assets/';
        } else {
            $this->data['assets'] = base_url() . 'themes/adminlte/assets/';
        }
		$this->data['settings'] = $this->mSettings;
        
		// restrict pages
		$uri = ($this->mAction=='index') ? $this->mCtrler : $this->mCtrler.'/'.$this->mAction;
		if ( !empty($this->mPageAuth[$uri]) && !$this->ion_auth->in_group($this->mPageAuth[$uri]) )
		{
			$page_404 = $this->router->routes['404_override'];
			$redirect_url = empty($this->mModule) ? $page_404 : $this->mModule.'/'.$page_404;
			redirect($redirect_url);
		}

		// push first entry to breadcrumb
		if ($this->mCtrler!='home')
		{
			$page = $this->mMultilingual ? lang('home') : 'Home';
			$this->push_breadcrumb($page, '');
		}

		// get user data if logged in
		if ( $this->ion_auth->logged_in() )
		{
			$this->mUser = $this->ion_auth->user()->row();
			$this->Admin = $this->repairer->in_group('admin') ? TRUE : FALSE;
            $this->data['Admin'] = $this->Admin;
            if(!$this->Admin) {
            	$gp = $this->settings_model->getGroupPermissions($this->ion_auth->get_users_groups()->row()->id);
	            $this->GP = $gp[0];
	            $this->data['GP'] = $gp[0];
	        } else {
	            $this->data['GP'] = NULL;
	        }
		}

		$this->mConfig = $config;
	}

	// Verify user login (regardless of user group)
	protected function verify_login($redirect_url = NULL)
	{
		if ( !$this->ion_auth->logged_in() )
		{
			if ( $redirect_url==NULL )
				$redirect_url = $this->mConfig['login_url'];

			redirect($redirect_url);
		}
	}

	// Verify user authentication
	// $group parameter can be name, ID, name array, ID array, or mixed array
	// Reference: http://benedmunds.com/ion_auth/#in_group
	protected function verify_auth($group = 'members', $redirect_url = NULL)
	{
		if ( !$this->ion_auth->logged_in() || !$this->ion_auth->in_group($group) )
		{
			if ( $redirect_url==NULL )
				$redirect_url = $this->mConfig['login_url'];
			
			redirect($redirect_url);
		}
	}

	// Add script files, either append or prepend to $this->mScripts array
	// ($files can be string or string array)
	protected function add_script($files, $append = TRUE, $position = 'foot')
	{
		$files = is_string($files) ? array($files) : $files;
		$position = ($position==='head' || $position==='foot') ? $position : 'foot';

		if ($append)
			$this->mScripts[$position] = array_merge($this->mScripts[$position], $files);
		else
			$this->mScripts[$position] = array_merge($files, $this->mScripts[$position]);
	}

	// Add stylesheet files, either append or prepend to $this->mStylesheets array
	// ($files can be string or string array)
	protected function add_stylesheet($files, $append = TRUE, $media = 'screen')
	{
		$files = is_string($files) ? array($files) : $files;

		if ($append)
			$this->mStylesheets[$media] = array_merge($this->mStylesheets[$media], $files);
		else
			$this->mStylesheets[$media] = array_merge($files, $this->mStylesheets[$media]);
	}

	// Render template
	protected function render($view_file, $layout = 'default')
	{
		// automatically generate page title
		if ( empty($this->mPageTitle) )
		{
			if ($this->mAction=='index')
				$this->mPageTitle = humanize($this->mCtrler);
			else
				$this->mPageTitle = humanize($this->mAction);
		}
		$this->data['module'] = $this->mModule;
		$this->data['ctrler'] = $this->mCtrler;
		$this->data['action'] = $this->mAction;
		$this->data['taxRates'] = $this->mTRates;

		$this->data['site_name'] = $this->mSiteName;
		$this->data['page_title'] = $this->mPageTitlePrefix.$this->mPageTitle;
		$this->data['current_uri'] = empty($this->mModule) ? uri_string(): str_replace($this->mModule.'/', '', uri_string());
		$this->data['meta_data'] = $this->mMetaData;
		$this->data['scripts'] = $this->mScripts;
		$this->data['stylesheets'] = $this->mStylesheets;
		$this->data['page_auth'] = $this->mPageAuth;
		$this->data['clients'] = $this->settings_model->getAllClients();
        $this->data['models'] = $this->reparation_model->getAllModels();
        $this->data['tax_rates'] = $this->settings_model->getTaxRates();
        $this->data['statuses'] = $this->settings_model->getRepairStatuses();
        $this->data['manufacturers'] = $this->settings_model->getAllManufacturers();

		$this->data['base_url'] = $this->mBaseUrl;
		$this->data['menu'] = $this->mMenu;
		$this->data['user'] = $this->mUser;
		$this->data['ga_id'] = empty($this->mConfig['ga_id']) ? '' : $this->mConfig['ga_id'];
		$this->data['body_class'] = $this->mBodyClass;

		// automatically push current page to last record of breadcrumb
		$this->push_breadcrumb($this->mPageTitle);
		$this->data['breadcrumb'] = $this->mBreadcrumb;
        $this->data['qty_alert_num'] = $this->settings_model->get_total_qty_alerts();

		$this->data['inner_view'] = $view_file;
		$this->load->view($this->theme . '_base/head', $this->data);
		$this->load->view($this->theme . '_layouts/'.$layout, $this->data);
		$this->load->view($this->theme . '_base/foot', $this->data);
	}

	// Output JSON string
	protected function render_json($data, $code = 200)
	{
		$this->output
			->set_status_header($code)
			->set_content_type('application/json')
			->set_output(json_encode($data));
			
		// force output immediately and interrupt other scripts
		global $OUT;
		$OUT->_display();
		exit;
	}

	// Add breadcrumb entry
	// (Link will be disabled when it is the last entry, or URL set as '#')
	protected function push_breadcrumb($name, $url = '#', $append = TRUE)
	{
		$entry = array('name' => $name, 'url' => $url);

		if ($append)
			$this->mBreadcrumb[] = $entry;
		else
			array_unshift($this->mBreadcrumb, $entry);
	}
	public function send_email($to, $subject, $message, $from = null, $from_name = null, $attachment = null, $cc = null, $bcc = null)
    {
    	
        $this->load->library('email');
        $config['useragent'] = "Library Management System";
        $config['protocol'] = 'smtp';
        $config['mailtype'] = "html";
        $config['crlf'] = "\r\n";
        $config['charset']   = 'utf-8';
		$config['newline']   = "\r\n";
       
        $this->load->library('encrypt');

        $config['smtp_host'] = $this->mSettings->smtp_host;
        $config['smtp_user'] = $this->mSettings->smtp_user;
        $config['smtp_pass'] = ($this->mSettings->smtp_pass);
        $config['smtp_port'] = $this->mSettings->smtp_port;
      

        $this->email->initialize($config);

        if ($from && $from_name) {
            $this->email->from($from, $from_name);
        } elseif ($from) {
            $this->email->from($from, $this->mSettings->title);
        } else {
            $this->email->from($this->mSettings->email, $this->mSettings->title);
        }

        $this->email->to($to);
        if ($cc) {
            $this->email->cc($cc);
        }
        if ($bcc) {
            $this->email->bcc($bcc);
        }
        $this->email->subject($subject);
        $this->email->message($message);
        if ($attachment) {
            if (is_array($attachment)) {
                foreach ($attachment as $file) {
                    $this->email->attach($file);
                }
            } else {
                $this->email->attach($attachment, "inline");
            }
        }


        if ($this->email->send()) {
            // echo $this->email->print_debugger(); die();
            return true;
        } else {
            echo $this->email->print_debugger(); die();
            return false;
        }
    }
}

// include base controllers
require APPPATH."core/Auth_Controller.php";
