<?php
defined('BASEPATH') OR exit('No direct script access allowed');

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
#[AllowDynamicProperties]
class MY_Controller extends CI_Controller {

	private $non_login_pages = array(
		'signup', 'user/signup',
		'login', 'user/login',
		'register', 'user/register',
		'forgotpassword', 'user/forgotpassword',
		'reset_confirm', 'user/reset_confirm',
		'reset_complete', 'user/reset_complete',
		'api/createorder'
	);

	private $public_pages = array(
		'obinfo', 'home/obinfo',
		'obabout', 'home/obabout',
		'obversion', 'home/obversion',
		'obsql', 'home/obsql',
		'checklic', 'home/checklic',
		'tenant', 'home/tenant',
		'ping', 'home/ping',
		'removeuserdevice','home/removeuserdevice',
		'printpdf', 'transaction/printpdf',
		'order', 'ecommerce/whatsapp_datafeed'
	);

	private $cron_pages = array(
		'rank', 'home/rank',
		'backupdb', 'update/backupdb',
		'cronack', 'update/cronack',
		'email_expire', 'home/email_expire',
		'resetdemodate','home/resetdemodate',
		'sendsms', 'home/sendsms',
		'cron/jobs',
	);

	private $ignore_pages = array(
		'api', 'api/index', 'api/authorize', 'api/token', 'api/refresh_token'
	);

	private $ignore_authendication = array(
		'logout', 'user/logout', 'home/delete_query_log'
	);

	function __construct()
	{
		$header = getallheaders();

		if ($header) {
			foreach ($header as $key => $val) {
				$header[strtolower($key)] = $val;
			}
		}
		// session login if exists
		$conf 	= get_config();
		if( !empty($header['obsesscode'])) {
			$_COOKIE[$conf['sess_cookie_name']] = $header['obsesscode'];
		}

		parent::__construct();
		$this->load->database();
		$this->load->model('users');
		$this->load->helper('cookie');
		
		$this->session->set_userdata('is_logged_in', false);
			
		$this->bId = get_user_data('defaultbId',true);
		$this->load->response();

		if(!empty($header['obsesscode']))
		{
			$dCode = $this->input->get_request_header('dCode', TRUE);
			if (!empty($dCode))
			{
				$dCode 	= stripslashes($dCode);
				if (session_id() && get_user_data('dCode',true)!=$dCode) 
				{
					$this->session->unset_userdata('user');
					$this->session->sess_destroy();
				}
			}
		}

		if (!get_user_data()) {
			if (!$this->users->login_with_token()) {
				$this->users->login_with_cookie();
			}
		}
		
		if (!$this->do_auth())
		{
			// authendication validation
			return false;
		}

		$url = $this->uri->uri_string();
		if (!in_array($url,$this->ignore_authendication))
		{
			$this->session->set_userdata('is_logged_in', true);
			// check device authendication
			if (!$this->session->userdata('device_authorized') && !$this->users->check_device_authendication())
			{
				return false;
			}
			else if (in_array($url,array('authorized', 'user/authorized')))
			{
				redirect('home');
			}
		}

		// restrict pages based on role
		// S - sales
		// I - sales & purchase
		// C - Accountant
		// A -> Administrator
		$roleCode = get_user_data('roleCode');
		$this->session->set_userdata('is_latest_server', $this->db->conn_id->server_version >= 100200 ? 1 : 0);	// 10.2.0
		if(isset($header['is_api_call'])) {
			$this->session->set_userdata('is_api_call', true);
		}
		if ($roleCode != 'A' && $roleCode != 'C')
		{
			$segment = $this->uri->segment(1);
			switch ($segment)
			{
				case 'home' : 
					if($roleCode == 'E')
					{
						// show_404();
					}
				break;
				case 'purchase':
					if($roleCode == 'S')
					{
						show_404();
					}
				break;
				case 'journal':
				case 'contra':
				case 'openingbalances':
				case 'account':
				case 'banks':
				case 'manage' :
					if(($roleCode == 'R' || $roleCode == 'S' || $roleCode == 'I' )) {
						if($this->uri->segment(2) == 'ratesheet' || $this->uri->segment(2) == 'bom' || $this->uri->segment(2) == 'mfgjournal')
						show_404();
					}
				break;
				case 'all-settings':
					if ($roleCode != "F" && $roleCode != "R" && $roleCode != "A")
					{
						$set_right = get_rights('SET');
						if (empty($set_right['actionRights']))
						{
							show_404();
						}
					}
				break;
				case 'users':
				case 'report':
					if(!in_array($roleCode,array('R', 'S', 'I','F','K')))
					{
						show_404();
					}
				break;
			}
		} else if($roleCode!='A' && $roleCode!='C' && in_array($this->uri->segment(1),array('all-settings','users'))) {
			show_404();
		}
		else {
				// $das_right = get_rights('DAS');
				// $set_right = get_rights('SET');
				// if ($this->uri->segment(1) == 'all-settings' && empty($set_right['actionRights']) && $roleCode=='C')
				// {
				// 	show_404();
				// }
				if (in_array($this->uri->segment(1),array('all-settings','modules')) && $roleCode=='C')
				{
					$set_right = get_rights('SET');
					if (empty($set_right['actionRights']))
					{
						show_404();
					}
				}
		}
	}

	public function set_ignore_pages($pages = array())
	{
		if ($pages)
		{
			if (!is_array($pages))
			{
				$this->ignore_pages[] = $pages;
			}
			else
			{
				$this->ignore_pages = array_merge($this->ignore_pages, $pages);
			}
		}
	}

	public function do_auth()
	{
		// $uriStr = $this->uri->uri_string();
		$uriStr = $this->uri->segment(1) . (empty($this->uri->segment(2)) ? '' : ('/' . $this->uri->segment(2)));

		// User try to access NoN protected pages (login/signup/forgotpassword)
		// If he already logged in then redirect to home / last access page
		// Else allow access to NoN protect page
		
		if (in_array($uriStr, $this->non_login_pages))
		{  
			if (!get_user_data('id'))
			{ 
				$this->session->set_userdata('is_logged_in', false);
				return false;
			}
           
			redirect(site_url('home'));
			return;
		}

		if (in_array($uriStr, $this->public_pages) || in_array($uriStr, $this->cron_pages))
		{
			return;
		}

		// User not logged IN & Try to access Protected page
		// Then redirect to login page
		if (!get_user_data('id'))
		{
			$reqBy = $this->input->get_request_header('REQBY');

			if ($reqBy && $reqBy == 'OB')
			{
				$this->response->error('Sorry your session has expired.');
				$this->response->write(array(
					'redirect' => site_url('login')
				));
				exit;
			}
			else
			{
				redirect(site_url('login'));
				return false;
			}
		}

		return true;
	}
}

class ReportParent_Controller extends MY_Controller {
	public function __construct()
	{
		parent::__construct();

		$this->load->model('ReportModel');
		$this->load->model('FieldsModel');
		$this->tTypes_array = array(
			'SI' => 'Sale',
			'SR' => 'Reti',
			'SC' => 'C/No',
			'SD' => 'D/No',
			'SP' => 'Rcpt',
			'PI' => 'Purc',
			'PR' => "C.Purc",
			'EI' => "Exp#",
			'PE' => "Pymt Exp#",
			'PC' => 'SC/N',
			'PD' => 'SD/N',
			'PP' => 'Pymt',
			'JV' => 'Jrnl',
			'JC' => 'Cntr',
			'AO' => ' ',
			'PO' => 'Ordr',
			'SE' => 'Quotes',
			'GR' => 'G.Rec',
			'SH' => 'Deliv',
			'MJ' => 'Mfg Jrnl'
		);
		$this->tTypes = array(
			'SI' => 'Sales Invoice',
			'SR' => 'Cash Invoice',
			'SC' => 'Credit Note',
			'SD' => 'Debit Note',
			'SP' => 'Receipt',
			'PI' => 'Purchase Bill',
			'PE' => 'Expense',
			'PC' => 'Supplier Credit Note',
			'PD' => ' Supplier Debit Note',
			'PP' => 'Bill Payment',
			'JV' => 'Journal',
			'JC' => 'Contra',
			'AO' => 'Opening Balance',
			'PO' => 'Order',
			'SO' => 'Sales Order',
			'PO' => 'Purchase Order',
			'GR' => 'Goods Receipt Note',
			'SH' => 'Delivery Chalan'
		);
		$this->currency_symbol = get_company('symbol');
		$this->currency_fraction = get_company('fraction');
	}
}
