<?php

use Opencartvip\Opencart\ModuleController;
use Opencartvip\Options\Parser;
use Opencartvip\Utils\Arr;

class ControllerOpencartvipBlogPosts extends ModuleController {

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

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

	/**
	 * @param Parser $parser
	 * @param $index
	 * @return array
	 */
	protected function parseGeneralSettings($parser, $index) {
		$default = $parser->getSetting('default');

		$data = array(
			'classes'         => array(
				'module-blog_posts-' . $parser->getSetting('display'),
				'carousel-mode' => $parser->getSetting('carousel'),
				'isotope'       => $parser->getSetting('sectionsDisplay') === 'isotope',
			),
			'image_width'     => $parser->getSetting('imageDimensions.width', $this->opencartvip->settings->get('image_dimensions_blog.width')),
			'image_height'    => $parser->getSetting('imageDimensions.height', $this->opencartvip->settings->get('image_dimensions_blog.height')),
			'image_resize'    => $parser->getSetting('imageDimensions.resize'),
			'carouselOptions' => $this->opencartvip->carousel($parser->getJs(), 'carouselStyle'),
		);

		if ($this->opencartvip->settings->get('performanceLazyLoadImagesStatus')) {
			$data['dummy_image'] = $this->model_opencartvip_image->transparent($parser->getSetting('imageDimensions.width', $this->opencartvip->settings->get('image_dimensions_blog.width')), $parser->getSetting('imageDimensions.height', $this->opencartvip->settings->get('image_dimensions_blog.height')));
		}

		$data['text_tax'] = $this->language->get('text_tax');

		$data['button_cart'] = $this->language->get('button_cart');
		$data['button_wishlist'] = $this->language->get('button_wishlist');
		$data['button_compare'] = $this->language->get('button_compare');

		$data['default_index'] = $parser->getSetting('sectionsDisplay') === 'isotope' ? 0 : 1;

		if ($default) {
			foreach (Arr::get($this->module_data, 'items') as $index => $item) {
				if ($default === Arr::get($item, 'id')) {
					$data['default_index'] = $index + 1;
					break;
				}
			}
		}

		return $data;
	}

	/**
	 * @param Parser $parser
	 * @param $index
	 * @return array
	 */
	protected function parseItemSettings($parser, $index) {
		$preset = $parser->getSetting('filter.preset');
		$filter_data = $parser->getSetting('filter');

		switch ($preset) {
			case 'related':
				$posts = null;
				break;

			default:
				$results = $this->model_opencartvip_blog->getPosts($filter_data);
				$posts = $this->parsePosts($results);
		}

		return array(
			'tab_classes'   => array(
				'tab-' . $this->item_id,
			),
			'panel_classes' => array(
				'panel-collapse',
				'collapse',
			),
			'classes'       => array(
				'tab-pane'     => $this->settings['sectionsDisplay'] === 'tabs',
				'panel'        => $this->settings['sectionsDisplay'] === 'accordion',
				'swiper-slide' => ($this->settings['sectionsDisplay'] === 'blocks') && $this->settings['carousel'],
			),
			'posts'         => $posts,
		);
	}

	/**
	 * @param Parser $parser
	 * @param $index
	 * @return array
	 */
	protected function parseSubitemSettings($parser, $index) {
		return array();
	}

	protected function beforeRender() {
		if (!$this->settings['items']) {
			$this->settings = null;

			return;
		}

		foreach ($this->settings['items'] as $key => $item) {
			$posts = $item['posts'];

			if ($posts === null) {
				$filter_data = Arr::get($item, 'filter');
				$preset = Arr::get($filter_data, 'preset');
				$limit = Arr::get($filter_data, 'limit');

				switch ($preset) {
					case 'related':
						switch (Arr::get($this->request->get, 'route')) {
							case 'product/product':
								$product_id = (int)Arr::get($this->request->get, 'product_id');
								$results = $this->model_opencartvip_blog->getRelatedPosts($product_id, $limit);
								break;

							default:
								$results = array();
						}

						break;

					case 'custom':
						$results = $this->model_opencartvip_blog->getPost(Arr::get($filter_data, 'posts'));
						break;

					default:
						$results = $this->model_opencartvip_blog->getPosts($filter_data);
				}

				if (!$results) {
					unset($this->settings['items'][$key]);

					continue;
				}

				$posts = $this->parsePosts($results);
			}

			if (!$posts) {
				unset($this->settings['items'][$key]);

				continue;
			}

			$this->settings['items'][$key]['posts'] = $posts;

			if ($this->settings['sectionsDisplay'] === 'isotope') {
				foreach ($posts as $post) {
					if (!isset($this->settings['posts'][$post['post_id']])) {
						$this->settings['posts'][$post['post_id']] = $posts[$post['post_id']];
					}

					$this->settings['posts'][$post['post_id']]['classes'] = array_merge_recursive($this->settings['posts'][$post['post_id']]['classes'], array($this->settings['id'] . '-section-' . $key));
				}
			}
		}

		if (!$this->settings['items']) {
			$this->settings = null;

			return;
		}

		$keys = array_keys($this->settings['items']);

		if (!in_array($this->settings['default_index'], $keys)) {
			$this->settings['default_index'] = $keys[0];
		}

		if ($this->settings['sectionsDisplay'] === 'tabs') {
			$this->settings['items'][$this->settings['default_index']]['classes'][] = 'active';
			$this->settings['items'][$this->settings['default_index']]['tab_classes'][] = 'active';
		}

		if ($this->settings['sectionsDisplay'] === 'accordion') {
			$this->settings['items'][$this->settings['default_index']]['classes'][] = 'active';
			$this->settings['items'][$this->settings['default_index']]['panel_classes'][] = 'in';
		}
	}

	protected function afterRender() {
		if ($this->settings['sectionsDisplay'] === 'isotope') {
			$this->opencartvip->document->addScript('catalog/view/theme/opencartvip/lib/isotope/isotope.pkgd.min.js', 'footer');
		}

		if ($this->settings['carousel']) {
			$this->opencartvip->document->addStyle('catalog/view/theme/opencartvip/lib/swiper/swiper.min.css');
			$this->opencartvip->document->addScript('catalog/view/theme/opencartvip/lib/swiper/swiper.min.js', 'footer');
		}
	}

	private function parsePosts($results) {
		$posts = array();

		foreach ($results as $result) {
			if ($result['image']) {
				$image = $this->model_opencartvip_image->resize($result['image'], $this->settings['image_width'], $this->settings['image_height'], $this->settings['image_resize']);
				$image2x = $this->model_opencartvip_image->resize($result['image'], $this->settings['image_width'] * 2, $this->settings['image_height'] * 2, $this->settings['image_resize']);
			} else {
				$image = $this->model_opencartvip_image->resize('placeholder.png', $this->settings['image_width'], $this->settings['image_height'], $this->settings['image_resize']);
				$image2x = $this->model_opencartvip_image->resize('placeholder.png', $this->settings['image_width'] * 2, $this->settings['image_height'] * 2, $this->settings['image_resize']);
			}

			$posts[$result['post_id']] = array(
				'classes'     => array(
					'swiper-slide' => $this->settings['sectionsDisplay'] !== 'isotope' && $this->settings['carousel'],
					'isotope-item' => $this->settings['sectionsDisplay'] === 'isotope',
				),
				'post_id'     => $result['post_id'],
				'thumb'       => $image,
				'thumb2x'     => $image2x,
				'author'      => $this->model_opencartvip_blog->getAuthorName($result),
				'name'        => $result['name'],
				'comments'    => $result['comments'],
				'views'       => $result['views'],
				'date'        => date($this->opencartvip->settings->getWith('blogDateFormat', null, 'd \<\i\>M\<\/\i\>'), strtotime($result['date'])),
				'description' => utf8_substr(strip_tags(html_entity_decode($result['description'], ENT_QUOTES, 'UTF-8')), 0, $this->opencartvip->settings->get('blogPostsDescriptionLimit')) . '..',
				'href'        => $this->url->link('opencartvip/blog/post', 'opencartvip_blog_post_id=' . $result['post_id']),
			);
		}

		return $posts;
	}

}
