<?php

use Opencartvip\Opencart\Controller;
use Opencartvip\Utils\Arr;

class ControllerOpencartvipOpencartvip extends Controller {

	public function __construct($registry) {
		parent::__construct($registry);

		$this->load->model('opencartvip/opencartvip');
		$this->load->model('opencartvip/module');

		$this->load->language('error/permission');
	}

	public function index() {
		if (!$this->model_opencartvip_opencartvip->isInstalled()) {
			$this->model_opencartvip_opencartvip->install();
		} else {
			$this->model_opencartvip_opencartvip->database();
		}

		// language
		$this->load->language('opencartvip/opencartvip');

		// title
		$this->document->setTitle($this->language->get('Opencartvip'));

		// modernizr
		$this->document->addScript('../catalog/view/theme/opencartvip/lib/modernizr/modernizr-custom.js');

		// summernote / ckeditor
		// define('OPENCARTVIP_CKEDITOR', '//cdn.ckeditor.com/4.10.0/standard/ckeditor.js');
		// define('OPENCARTVIP_CKEDITOR', '//cdn.ckeditor.com/4.10.0/basic/ckeditor.js');
		// define('OPENCARTVIP_CKEDITOR', '//cdn.ckeditor.com/4.10.0/full/ckeditor.js');
		if (defined('OPENCARTVIP_CKEDITOR')) {
			$this->document->addScript(OPENCARTVIP_CKEDITOR);
		} else if ($this->opencartvip->isOC31()) {
			$this->document->addScript('view/javascript/ckeditor/ckeditor.js');
			$this->document->addScript('view/javascript/ckeditor/adapters/jquery.js');
		} else {
			$this->document->addStyle('view/javascript/summernote/summernote.css');
			$this->document->addScript('view/javascript/summernote/summernote.js');
			$this->document->addScript('view/javascript/summernote/opencart.js');
		}

		// font loader
		$this->document->addScript('https://ajax.googleapis.com/ajax/libs/webfont/1.4.7/webfont.js');
		$this->document->addStyle('https://fonts.googleapis.com/css?family=Montserrat:300,400,600');


		// icons
		$this->document->addStyle('../catalog/view/theme/opencartvip/icons/style.css');

		// opencartvip assets
		$this->document->addScript($this->adminUrl('opencartvip/opencartvip/js'));

		if ($this->opencartvip->isDev()) {
			$this->document->addScript('//' . parse_url(HTTP_SERVER, PHP_URL_HOST) . ':35729/livereload.js?snipver=1');
			$this->document->addScript('//' . parse_url(HTTP_SERVER, PHP_URL_HOST) . ':' . (defined('PORT') ? PORT : 4444) . '/vendor.js?t=' . time());
			$this->document->addScript('//' . parse_url(HTTP_SERVER, PHP_URL_HOST) . ':' . (defined('PORT') ? PORT : 4444) . '/main.js?t=' . time());

			$this->document->addStyle('view/javascript/opencartvip/dist/vendor.css?t=' . time());
			$this->document->addStyle('view/javascript/opencartvip/dist/style.css?t=' . time());
		} else {
			$this->document->addScript('view/javascript/opencartvip/dist/vendor.js?v=' . (defined('OPENCARTVIP_BUILD') ? OPENCARTVIP_BUILD : OPENCARTVIP_VERSION));
			$this->document->addScript('view/javascript/opencartvip/dist/main.js?v=' . (defined('OPENCARTVIP_BUILD') ? OPENCARTVIP_BUILD : OPENCARTVIP_VERSION));

			$this->document->addStyle('view/javascript/opencartvip/dist/vendor.css?v=' . (defined('OPENCARTVIP_BUILD') ? OPENCARTVIP_BUILD : OPENCARTVIP_VERSION));
			$this->document->addStyle('view/javascript/opencartvip/dist/style.css?v=' . (defined('OPENCARTVIP_BUILD') ? OPENCARTVIP_BUILD : OPENCARTVIP_VERSION));
		}

		// version
		$data['j3v'] = OPENCARTVIP_VERSION;

		$data['header'] = $this->load->controller('common/header');
		$data['column_left'] = $this->load->controller('common/column_left');
		$data['footer'] = $this->load->controller('common/footer');

		$this->renderOutput('opencartvip/opencartvip', $data);
	}

	public function menu() {
		if (!$this->user->hasPermission('access', 'opencartvip/opencartvip') || !$this->config->get('theme_opencartvip_status')) {
			return null;
		}

		$opencartvip = array();

//		// dashboard
//		$opencartvip[] = array(
//			'name'     => $this->language->get('Dashboard'),
//			'href'     => $this->adminUrl('opencartvip/opencartvip') . '#/dashboard',
//			'children' => array(),
//		);

		// variables
		if ($this->user->hasPermission('access', 'opencartvip/variable')) {
			$opencartvip[] = array(
				'name'     => $this->language->get('Değişkenler'),
				'href'     => $this->adminUrl('opencartvip/opencartvip') . '#/variable/color',
				'children' => array(),
			);
		}

		// styles
		if ($this->user->hasPermission('access', 'opencartvip/style')) {
			$opencartvip[] = array(
				'name'     => $this->language->get('Stiller'),
				'href'     => $this->adminUrl('opencartvip/opencartvip') . '#/style/page',
				'children' => array(),
			);
		}

		// skins
		if ($this->user->hasPermission('access', 'opencartvip/skin')) {
			$opencartvip[] = array(
				'name'     => $this->language->get('Şablonlar'),
				'href'     => $this->adminUrl('opencartvip/opencartvip') . '#/skin',
				'children' => array(),
			);
		}

		// layout
		if ($this->user->hasPermission('access', 'opencartvip/layout')) {
			$opencartvip[] = array(
				'name'     => $this->language->get('Bölümler'),
				'href'     => $this->adminUrl('opencartvip/opencartvip') . '#/layout',
				'children' => array(),
			);
		}

		// header modules
		if ($this->user->hasPermission('access', 'opencartvip/module_header')) {
			$opencartvip[] = array(
				'name'     => $this->language->get('Sitenin Üst Kısmı'),
				'href'     => $this->adminUrl('opencartvip/opencartvip') . '#/module_header/main_menu',
				'children' => array(),
			);
		}

		// footer modules
		if ($this->user->hasPermission('access', 'opencartvip/module_footer')) {
			$opencartvip[] = array(
				'name'     => $this->language->get('Sitenin Alt Kısmı'),
				'href'     => $this->adminUrl('opencartvip/opencartvip') . '#/module_footer/footer_menu',
				'children' => array(),
			);
		}

		// layout modules
		if ($this->user->hasPermission('access', 'opencartvip/module_layout')) {
			$opencartvip[] = array(
				'name'     => $this->language->get('Modüller'),
				'href'     => $this->adminUrl('opencartvip/opencartvip') . '#/module_layout/banners',
				'children' => array(),
			);
		}

		// product modules
		if ($this->user->hasPermission('access', 'opencartvip/module_product')) {
			$opencartvip[] = array(
				'name'     => $this->language->get('Ürün İçerikleri'),
				'href'     => $this->adminUrl('opencartvip/opencartvip') . '#/module_product/product_label',
				'children' => array(),
			);
		}

		// blog
		$children = array();

		if ($this->user->hasPermission('access', 'opencartvip/blog_setting')) {
			$children[] = array(
				'name'     => $this->language->get('Ayarlar'),
				'href'     => $this->adminUrl('opencartvip/opencartvip') . '#/blog_setting',
				'children' => array(),
			);
		}

		if ($this->user->hasPermission('access', 'opencartvip/blog_category')) {
			$children[] = array(
				'name'     => $this->language->get('Kategoriler'),
				'href'     => $this->adminUrl('opencartvip/opencartvip') . '#/blog_category',
				'children' => array(),
			);
		}

		if ($this->user->hasPermission('access', 'opencartvip/blog_post')) {
			$children[] = array(
				'name'     => $this->language->get('Yazılar'),
				'href'     => $this->adminUrl('opencartvip/opencartvip') . '#/blog_post',
				'children' => array(),
			);
		}

		if ($this->user->hasPermission('access', 'opencartvip/blog_comment')) {
			$children[] = array(
				'name'     => $this->language->get('Yorumlar'),
				'href'     => $this->adminUrl('opencartvip/opencartvip') . '#/blog_comment',
				'children' => array(),
			);
		}

		if ($children) {
			$opencartvip[] = array(
				'name'     => $this->language->get('Blog'),
				'href'     => '',
				'children' => $children,
			);
		}

		// system
		$children = array();

		// settings
		if ($this->user->hasPermission('access', 'opencartvip/setting')) {
			$children[] = array(
				'name'     => $this->language->get('Ayarlar'),
				'href'     => $this->adminUrl('opencartvip/opencartvip') . '#/setting',
				'children' => array(),
			);
		}

		// newsletter
		if ($this->user->hasPermission('access', 'opencartvip/newsletter')) {
			$children[] = array(
				'name'     => $this->language->get('Haber Bülteni'),
				'href'     => $this->adminUrl('opencartvip/opencartvip') . '#/newsletter',
				'children' => array(),
			);
		}

		// message
		if ($this->user->hasPermission('access', 'opencartvip/message')) {
			$children[] = array(
				'name'     => $this->language->get('Emailler'),
				'href'     => $this->adminUrl('opencartvip/opencartvip') . '#/message',
				'children' => array(),
			);
		}

		// import/export
		if ($this->user->hasPermission('access', 'opencartvip/import_export')) {
			$children[] = array(
				'name'     => $this->language->get('İçeri Aktar / Dışarı Aktar'),
				'href'     => $this->adminUrl('opencartvip/opencartvip') . '#/import_export',
				'children' => array(),
			);
		}

		// system settings
		if ($this->user->hasPermission('access', 'opencartvip/system')) {
			$children[] = array(
				'name'     => $this->language->get('Sistem'),
				'href'     => $this->adminUrl('opencartvip/opencartvip') . '#/system',
				'children' => array(),
			);
		}

		if ($children) {
			$opencartvip[] = array(
				'name'     => $this->language->get('Sistem'),
				'href'     => '',
				'children' => $children,
			);
		}

		return array(
			'id'       => 'opencartvip-theme',
			'icon'     => 'fa-cogs',
			'name'     => $this->language->get('Tema Ayarları'),
			'href'     => '',
			'children' => $opencartvip,
		);
	}

	public function js() {
		$data = array();

		// php options
		$data['php_ini'] = str_replace('\\', '/', php_ini_loaded_file());
		$data['php_upload_max_filesize'] = ini_get('upload_max_filesize');
		$data['php_post_max_size'] = ini_get('post_max_size');

		// version
		$data['j3v'] = OPENCARTVIP_VERSION;
		$data['j3ov'] = OPENCARTVIP_OC_VERSION;
		$data['ocv'] = VERSION;
		$data['j3debug'] = defined('OPENCARTVIP_DEBUG') && OPENCARTVIP_DEBUG;

		// webpack PORT
		if (defined('PORT')) {
			$data['PORT'] = PORT;
		}

		// base url
		$data['base'] = str_replace('&amp;', '&', $this->adminUrl('opencartvip/opencartvip'));

		// session token, needed for ajax calls
		if ($this->opencartvip->isOC3()) {
			$data['token'] = $this->session->data['user_token'];
		} else {
			$data['token'] = $this->session->data['token'];
		}

		// available stores
		$this->load->model('setting/store');
		$stores = $this->model_setting_store->getStores();
		array_unshift($stores, array(
			'store_id' => '0',
			'name'     => $this->config->get('config_name'),
		));
		$data['stores'] = $stores;

		// custom fields
		$this->load->model('customer/custom_field');
		$custom_fields = $this->model_customer_custom_field->getCustomFields();

		$data['custom_fields'] = array(
			'account' => array(),
			'address' => array(),
		);

		foreach ($custom_fields as $custom_field) {
			$data['custom_fields'][$custom_field['location']][] = array(
				'label' => $custom_field['name'],
				'value' => $custom_field['custom_field_id'],
			);
		}

		// customer groups
		$this->load->model('customer/customer_group');
		$customer_groups = $this->model_customer_customer_group->getCustomerGroups();

		$data['customer_groups'] = array();
		foreach ($customer_groups as $customer_group) {
			$data['customer_groups'][] = array(
				'customer_group_id' => $customer_group['customer_group_id'],
				'name'              => $customer_group['name'],
			);
		}

		// available languages
		$this->load->model('localisation/language');
		$data['languages'] = array_values($this->model_localisation_language->getLanguages());
		$data['default_language'] = $this->config->get('config_language_id');

		// tax classes
		$this->load->model('localisation/tax_class');

		$tax_classes = $this->model_localisation_tax_class->getTaxClasses();

		array_unshift($tax_classes, array(
			'tax_class_id' => '',
			'title'        => 'None',
		));

		$data['tax_classes'] = $tax_classes;

		// fonts
		$data['fonts']['system'] = json_decode(file_get_contents(DIR_SYSTEM . 'library/opencartvip/data/fonts/system.json'), true);
		$data['fonts']['google'] = json_decode(file_get_contents(DIR_SYSTEM . 'library/opencartvip/data/fonts/google.json'), true);

		// icons
		$icons = json_decode(file_get_contents(DIR_CATALOG . 'view/theme/opencartvip/icons/selection.json'), true);

		foreach ($icons['icons'] as $icon) {
			$classes = explode(',', $icon['properties']['name']);
			$name = trim($classes[0]);
			$code = $icon['properties']['code'];
			if ($name !== 'youtube22') {
				$data['icons'][] = array(
					'name' => $name,
					'code' => dechex($code),
				);
			}
		}

		// variables
		$data['variables'] = $this->model_opencartvip_opencartvip->getVariables();

		// styles
		$data['styles'] = $this->model_opencartvip_opencartvip->getStyles();

		// modules
		$data['modules'] = $this->model_opencartvip_opencartvip->getModules();

		// layouts
		$this->load->model('design/layout');
		$data['layouts'] = array_map(function ($layout) {
			return array('id' => $layout['layout_id'], 'name' => $layout['name']);
		}, $this->model_design_layout->getLayouts());

		// filters
		$data['attributes'] = $this->model_opencartvip_opencartvip->getAllAttributes();
		$data['options'] = $this->model_opencartvip_opencartvip->getAllOptions();
		$data['filters'] = $this->model_opencartvip_opencartvip->getAllFilters();

		// authors
		$data['authors'] = $this->model_opencartvip_opencartvip->authors();

		// response
		$this->response->addHeader('Content-Type: application/javascript');
		$this->response->setOutput($this->load->view('opencartvip/js', array('data' => $data)));
	}

	public function get_variable() {
		return $this->renderJson(self::SUCCESS, $this->model_opencartvip_opencartvip->getVariables());
	}

	public function get_style() {
		return $this->renderJson(self::SUCCESS, $this->model_opencartvip_opencartvip->getStyles());
	}

	public function get_module() {
		return $this->renderJson(self::SUCCESS, $this->model_opencartvip_opencartvip->getModules());
	}

	public function get_skins() {
		$this->load->model('opencartvip/skin');

		return $this->renderJson(self::SUCCESS, $this->model_opencartvip_skin->all());
	}

	public function search() {
		try {
			$type = $this->input(self::GET, 'type');
			$keyword = $this->input(self::GET, 'keyword', '');
			$id = $this->input(self::GET, 'id', '');

			$results = array();

			switch ($type) {
				case 'product':
					$results = $this->model_opencartvip_opencartvip->getProducts($keyword, $id);
					break;

				case 'category':
					$results = $this->model_opencartvip_opencartvip->getCategories($keyword, $id);
					break;

				case 'manufacturer':
					$results = $this->model_opencartvip_opencartvip->getManufacturers($keyword, $id);
					break;

				case 'information':
					$results = $this->model_opencartvip_opencartvip->getInformations($keyword, $id);
					break;

				case 'attribute':
					$results = $this->model_opencartvip_opencartvip->getAttributes($keyword, $id);
					break;

				case 'option':
					$results = $this->model_opencartvip_opencartvip->getOptions($keyword, $id);
					break;

				case 'filter':
					$results = $this->model_opencartvip_opencartvip->getFilters($keyword, $id);
					break;

				case 'blog_category':
					$results = $this->model_opencartvip_opencartvip->getBlogCategories($keyword, $id);
					break;

				case 'blog_post':
					$results = $this->model_opencartvip_opencartvip->getBlogPosts($keyword, $id);
					break;

				default:
					if ($id) {
						$result = $this->model_opencartvip_module->get($id);
						$results = array(
							array(
								'id'   => $id,
								'name' => Arr::get($result, 'general.name'),
							),
						);
					} else {
						$result = $this->model_opencartvip_module->all(array(
							'type' => $type,
							'name' => $keyword,
						));
						$results = $result['items'];
					}
					break;
			}

			array_walk($results, function (&$result) {
				$result['name'] = strip_tags(html_entity_decode($result['name'], ENT_QUOTES, 'UTF-8'));
			});

			if ($id && !$results) {
//				throw new \Exception(sprintf("ID %s not found!", $id));
			}

			$this->renderJson(self::SUCCESS, $results);
		} catch (Exception $e) {
			$this->renderJson(self::ERROR, $e->getMessage());
		}
	}

	public function clear_cache() {
		try {
			if (!$this->user->hasPermission('modify', 'opencartvip/opencartvip')) {
				throw new Exception($this->language->get('text_permission'));
			}

			$this->opencartvip->cache->delete();

			$this->opencartvip->minifier->clearCache();

			$this->renderJson(self::SUCCESS);
		} catch (Exception $e) {
			$this->renderJson(self::ERROR, $e->getMessage());
		}
	}

}
