<?php
class ControllerExtensionModuleTrackingInput extends Controller {
	private $error = array(); 
	private $name = 'tracking_input';
	private $_settings_default = array(
			'redirect' => 0,
			'show_close_button' => 1,
			'no_cookie_only' => 0,
			'show' => 'session',
			'status' => 0,
			'choose_code' => 1,
			'choose_code_checkout' => 0,
			'require_code' => 1,
			'edit_code' => 0,
			'dir_template' => '',
			'allow_coupon' => 0,
			'allow_marketing' => 0
		);		
	
	private $_events = array(
		array('module_t', 'catalog/view/extension/module/tracking_input_*/after', 'extension/module/tracking_input/event/eventModuleTAfter'),	
		array('add_affiliate', 'catalog/model/account/customer/addAffiliate/after', 'extension/module/tracking_input/event/eventAddEditAffiliateAfter'),
		array('edit_affiliate', 'catalog/model/account/customer/editAffiliate/after', 'extension/module/tracking_input/event/eventAddEditAffiliateAfter')		
	);
	
	public function install() {
		$_settings = array();
		foreach($this->_settings_default as $k => $v) {
			$_settings['module_' . $this->name . '_' . $k] = $v;
		}
		$_settings['module_' . $this->name . '_module'] = array(
        'default_column' => array('language_id' => 1,
			'text_heading' => 'Referral Code',		
            'text' => 'Were you referred by someone?&lt;br /&gt;Enter code here:',
            'text_thankyou' => 'Thank You!',
            'button' => 'OK',
            'error_message' => 'Sorry, this code does not exist !',
            'template' => 'default_column'
        ),
		'default_row' => array
			('language_id' => 1,
			'text_heading' => '',
            'text' => 'Were you referred by someone? Type-in the code here: ',
            'text_thankyou' => 'Thank you, your code is accepted !',
            'button' => 'OK',
            'error_message' => 'Sorry, this code does not exist !',
            'template' => 'default_row'
        )		
		);
		$this->load->model('setting/setting');
		$this->model_setting_setting->editSetting('module_' . $this->name, $_settings);

		$this->addPermissions();
		
		$this->load->model('setting/module');
		foreach($_settings['module_' . $this->name . '_module'] as $_k => $_v) {
			$_v['name'] = ucwords(str_replace('_', ' ', $_k));
			$_v['status'] = '0';
			$this->model_setting_module->addModule($this->name, $_v);
		}
		
		$this->load->model('setting/event');
		foreach($this->_events as $_e) {
			if(!$this->model_setting_event->getEventByCode('module_' . $this->name . '_' . $_e[0])) $this->model_setting_event->addEvent('module_' . $this->name . '_' . $_e[0], $_e[1], $_e[2]);
		}	
		$this->_install_default_templates();		
	}
	
	public function index() {   
		if(isset($this->request->get['module_id'])) {
			$this->index_module();
			return;
		}
		$data['accc'] = $this->config->get('module_account_combine_status');

		$this->load->language('extension/module/' . $this->name);

		$this->document->setTitle($this->language->get('heading_title'));
		
		$this->load->model('setting/setting');
				
		if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validate()) {
			if (!$this->user->hasPermission('modify', 'extension/module/' . $this->name)) $this->response->redirect($this->url->link('error/permission', 'user_token=' . $this->session->data['user_token'], true));
			$cfgdata = array();
			foreach($this->request->post as $k => $v) {
				if(strpos($k, $this->name) === 0) $cfgdata['module_' . $k] = $v;
			}
			
			$this->model_setting_setting->editSetting('module_' . $this->name, $cfgdata);
			if(isset($cfgdata['module_' . $this->name . '_module']['name']) && strlen($cfgdata['module_' . $this->name . '_module']['name']) > 0) {
				$this->load->model('setting/module');
				$this->model_setting_module->addModule($this->name, $cfgdata['module_' . $this->name . '_module']);
			}
			$this->session->data['success'] = $this->language->get('text_success');
			$this->response->redirect($this->url->link('marketplace/extension', 'type=module&user_token=' . $this->session->data['user_token'], true));
		}
		$data = array_merge($data, $this->load->language('extension/module/' . $this->name));	
		$data['text_explanation'] = str_replace('[[link_design_layouts]]', $this->url->link('design/layout', 'user_token=' . $this->session->data['user_token'], true), $data['text_explanation']);
		$data['error_warning'] = isset($this->error['warning']) ? $this->error['warning'] : '';
				
  		$data['breadcrumbs'] = array();

   		$data['breadcrumbs'][] = array(
       		'text'      => $this->language->get('text_home'),
			'href'      => $this->url->link('common/home', 'user_token=' . $this->session->data['user_token'], true),
      		'separator' => false
   		);

   		$data['breadcrumbs'][] = array(
       		'text'      => $this->language->get('text_module'),
			'href'      => $this->url->link('marketplace/extension', 'type=module&user_token=' . $this->session->data['user_token'], true),
      		'separator' => ' :: '
   		);
		
   		$data['breadcrumbs'][] = array(
       		'text'      => $this->language->get('heading_title'),
			'href'      => $this->url->link('extension/module/' . $this->name, 'user_token=' . $this->session->data['user_token'], true),
      		'separator' => ' :: '
   		);
		
		$data['action'] = $this->url->link('extension/module/' . $this->name, 'user_token=' . $this->session->data['user_token'], true);
		
		$data['cancel'] = $this->url->link('marketplace/extension', 'type=module&user_token=' . $this->session->data['user_token'], true);	


		$data['user_token'] = $this->session->data['user_token'];

		foreach($this->_settings_default as $k => $v) {	
			$data[$this->name . '_' . $k] = isset($this->request->post[$this->name . '_' . $k]) ? $this->request->post[$this->name . '_' . $k] : $this->config->get('module_' . $this->name . '_' . $k);
		}
		
		$data['modules'] = array();
		
		$this->load->model('setting/module');
		$_ms = $this->model_setting_module->getModulesByCode($this->name);
		foreach($_ms as $_m) {				
			$data['modules'][$_m['module_id']] = json_decode($_m['setting'], true);
		}
		
		$_res = $this->db->query("SELECT `code` FROM " . DB_PREFIX . "layout_module WHERE `code` LIKE '" . $this->db->escape($this->name . '.') . "%'");
		$_used = array();
		foreach($_res->rows as $_r) {
			$_used[] = $_r['code'];
		}
		$data['used_templates'] = array();
		foreach($data['modules'] as $_i => $_m) {
			if(isset($_m['template'])) $data['used_templates'][] = $_m['template'];
			$data['modules'][$_i]['removable'] = !in_array($this->name . '.' . $_i, $_used);
			$data['modules'][$_i]['key'] = $_i;
		}
		$data['used_templates'] = array_values(array_unique($data['used_templates']));
		
		$data['templates'] = $this->_get_templates();
		$data['templates_display'] = array();
		$theme_editor_link = $this->url->link('design/theme', 'user_token=' . $this->session->data['user_token'], true);
		foreach($data['templates'] as $_tpl) {
			$data['templates_display'][$_tpl] = array(
				'title' => ucwords(preg_replace("/[^a-z0-9]+/", ' ', strtolower($_tpl))),
				'tpl' => $_tpl,
				'used' => (in_array($_tpl, $data['used_templates'])),
				'text_edit' => sprintf($data['text_edit_template'], $theme_editor_link, $this->name . '_' . $_tpl . '.twig')
			);
		}				

		$this->load->model('localisation/language');
		$data['languages'] = $this->model_localisation_language->getLanguages();
		$data['num_languages'] = sizeof($data['languages']);	
	
		$data['header'] = $this->load->controller('common/header');
		$data['column_left'] = $this->load->controller('common/column_left');
		$data['footer'] = $this->load->controller('common/footer');
		$this->response->setOutput($this->load->view('extension/module/' . $this->name, $data));
	}
	
	public function tpl_create() {
		$default_dir = $this->_get_dir_template();
		$_REQUEST['format'] = $_GET['format'] = 'raw';//+mod by yp mijoshop
		$error = true;
		if (!$this->user->hasPermission('modify', 'extension/module/' . $this->name)) {
			$this->load->language('extension/module/' . $this->name);
			$this->response->setOutput($this->language->get('error_permission'));
			return;
		}
		
		if(preg_match("/^\w+$/", $this->request->request['tpl']) && file_exists($default_dir . $this->name . '_' . strtolower($this->request->request['tpl']) . '.twig') && preg_match("/^\w+$/", $this->request->request['name'])) {
			copy($default_dir . $this->name . '_' . strtolower($this->request->request['tpl']) . '.twig', $default_dir . $this->name . '_' . strtolower($this->request->request['name']) . '.twig');
			if(file_exists($default_dir . $this->name . '_' . strtolower($this->request->request['name']) . '.twig')) $error = false;
		}
		
		$this->response->setOutput($error ? '0' : '1');
	}

	public function tpl_delete() {		
		$_REQUEST['format'] = $_GET['format'] = 'raw';//+mod by yp mijoshop
		$error = true;
		if (!$this->user->hasPermission('modify', 'extension/module/' . $this->name)) {
			$this->load->language('extension/module/' . $this->name);
			$this->response->setOutput($this->language->get('error_permission'));
			return;
		}
		$dir_template = $this->_get_dir_template();
		$_f = $dir_template . $this->name . '_' . strtolower($this->request->request['tpl']) . '.twig';
		if(file_exists($_f)) @unlink($_f);
		if(!file_exists($_f)) $error = false;
		$this->response->setOutput($error ? '0' : '1');
	}	
	
	private function validate($check_tpl = true) {
		$this->_install_default_templates();
		if (!$this->user->hasPermission('modify', 'extension/module/' . $this->name)) $this->error['warning'] = $this->language->get('error_permission');
		return (!$this->error ? true : false);
	}
	
	private function _get_templates() {
		$default_dir = $this->_get_dir_template();
		$_ar = glob($default_dir . $this->name . '_*.twig');
//$this->log->write($default_dir . ' ' . print_r($_ar, 1));//tmp		
		$out = array();
		foreach($_ar as $f) {
			$out[] = substr(basename($f, '.twig'), strlen($this->name) + 1);
		}
		sort($out);		
		return $out;
	}

	private function _get_dir_template() {
		return DIR_CATALOG . 'view/theme/' . $this->config->get('theme_default_directory') . '/template/extension/module/';
	}
	
	protected function index_module() {
		$this->load->model('setting/module');
		$this->load->language('extension/module/' . $this->name);		
		if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validate(false)) {
			if (!$this->user->hasPermission('modify', 'extension/module/' . $this->name)) $this->response->redirect($this->url->link('error/permission', 'user_token=' . $this->session->data['user_token'], true));			
			if(isset($this->request->post[$this->name . '_module']['name']) && strlen($this->request->post[$this->name . '_module']['name']) > 0) $this->model_setting_module->editModule($this->request->get['module_id'], $this->request->post[$this->name . '_module']);
			$this->session->data['success'] = $this->language->get('text_success');
			$this->response->redirect($this->url->link('marketplace/extension', 'type=module&user_token=' . $this->session->data['user_token'], true));
		}	
		$this->document->setTitle($this->language->get('heading_title'));
		if(!isset($data)) $data = array();
		$data = array_merge($data, $this->load->language('extension/module/' . $this->name));	
		$data['error_warning'] = isset($this->error['warning']) ? $this->error['warning'] : '';
				
  		$data['breadcrumbs'] = array();

   		$data['breadcrumbs'][] = array(
       		'text'      => $this->language->get('text_home'),
			'href'      => $this->url->link('common/home', 'user_token=' . $this->session->data['user_token'], true),
      		'separator' => false
   		);

   		$data['breadcrumbs'][] = array(
       		'text'      => $this->language->get('text_module'),
			'href'      => $this->url->link('marketplace/extension', 'type=module&user_token=' . $this->session->data['user_token'], true),
      		'separator' => ' :: '
   		);
		
   		$data['breadcrumbs'][] = array(
       		'text'      => $this->language->get('heading_title'),
			'href'      => $this->url->link('extension/module/' . $this->name, 'user_token=' . $this->session->data['user_token'] . '&module_id=' . $this->request->get['module_id'], true),
      		'separator' => ' :: '
   		);
		
		$data['action'] = $this->url->link('extension/module/' . $this->name, 'user_token=' . $this->session->data['user_token'] . '&module_id=' . $this->request->get['module_id'], true);
		
		$data['cancel'] = $this->url->link('marketplace/extension', 'type=module&user_token=' . $this->session->data['user_token'], true);		

		$data['user_token'] = $this->session->data['user_token'];	
		
		
		if (isset($this->request->post[$this->name . '_module'])) {
			$data['module'] = $this->request->post[$this->name . '_module'];
		} else { 
			$data['module'] = $this->model_setting_module->getModule($this->request->get['module_id']);
		}	
		
		$data['name'] = $data['module']['name'];

		$data['templates'] = $this->_get_templates();
		$data['templates_display'] = array();
		foreach($data['templates'] as $_tpl) {
			$data['templates_display'][$_tpl] = array(
				'title' => ucwords(preg_replace("/[^a-z0-9]+/", ' ', strtolower($_tpl))),
				'tpl' => $_tpl				
			);
		}				
		$this->load->model('localisation/language');
		$data['languages'] = $this->model_localisation_language->getLanguages();
		$data['num_languages'] = sizeof($data['languages']);			
				
		$data['header'] = $this->load->controller('common/header');
		$data['column_left'] = $this->load->controller('common/column_left');
		$data['footer'] = $this->load->controller('common/footer');		
		$this->response->setOutput($this->load->view('extension/module/' . $this->name . '_module_edit', $data));		
	}


	public function uninstall() {
		if (!$this->user->hasPermission('modify', 'extension/module/' . $this->name)) return;
		$this->load->model('setting/setting');		
		$this->model_setting_setting->deleteSetting('module_' . $this->name);
		$this->load->model('setting/event');
		foreach($this->_events as $_e) {
			$this->model_setting_event->deleteEventByCode('module_' . $this->name . '_' . $_e[0]);
		}		
	}	

	protected function addPermissions() {
		$this->load->model('user/user_group');
		$routes = array('extension/module/' . $this->name, 'extension/module/' . $this->name . '/event');
		foreach($routes as $route) {
			foreach(array('access', 'modify') as $perm_type) {
				if(!$this->user->hasPermission($perm_type, $route)) {
					$this->model_user_user_group->addPermission($this->user->getGroupId(), $perm_type, $route);				
				}
			}
		}
	}	
	
	private function _install_default_templates() {
		$default_dir = $this->config->get('theme_default_directory');
		if($default_dir && $default_dir !== 'default' && is_dir(DIR_CATALOG . 'view/theme/' . $default_dir . '/template/extension/module')) {
			$_ddefault = DIR_CATALOG . 'view/theme/default/template/extension/module/';
			$_cdefault = $this->_get_dir_template();
			if(file_exists($_ddefault . $this->name . '_default_row.twig') && !file_exists($_cdefault . $this->name . '_default_row.twig')) copy($_ddefault . $this->name . '_default_row.twig', $_cdefault . $this->name . '_default_row.twig');
			if(file_exists($_ddefault . $this->name . '_default_column.twig') && !file_exists($_cdefault . $this->name . '_default_column.twig')) copy($_ddefault . $this->name . '_default_column.twig', $_cdefault . $this->name . '_default_column.twig');
		}		
	}
	
}
