<?php
class ControllerExtensionDashboardWebskyIranmap extends Controller {
	private $error = array();

	public function index() {
		$this->load->language('extension/dashboard/websky_iranmap');

		$this->document->setTitle($this->language->get('heading_title'));

		$this->load->model('setting/setting');

		if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validate()) {
			$settings = array(
				'dashboard_websky_iranmap_width'       => (int)$this->request->post['dashboard_websky_iranmap_width'],
				'dashboard_websky_iranmap_status'      => (int)$this->request->post['dashboard_websky_iranmap_status'],
				'dashboard_websky_iranmap_sort_order'  => (int)$this->request->post['dashboard_websky_iranmap_sort_order'],
				'dashboard_websky_iranmap_address'     => $this->request->post['dashboard_websky_iranmap_address'] === 'shipping' ? 'shipping' : 'payment',
				'dashboard_websky_iranmap_color'       => $this->sanitizeColor($this->request->post['dashboard_websky_iranmap_color'])
			);

			$previous_status = $this->config->get('dashboard_websky_iranmap_previous_map_status');

			if ($previous_status !== null) {
				$settings['dashboard_websky_iranmap_previous_map_status'] = (int)$previous_status;
			}

			$this->model_setting_setting->editSetting('dashboard_websky_iranmap', $settings);

			$this->session->data['success'] = $this->language->get('text_success');

			$this->response->redirect($this->url->link('marketplace/extension', 'user_token=' . $this->session->data['user_token'] . '&type=dashboard', true));
		}

		$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/dashboard', 'user_token=' . $this->session->data['user_token'], true)
		);
		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('text_extension'),
			'href' => $this->url->link('marketplace/extension', 'user_token=' . $this->session->data['user_token'] . '&type=dashboard', true)
		);
		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('heading_title'),
			'href' => $this->url->link('extension/dashboard/websky_iranmap', 'user_token=' . $this->session->data['user_token'], true)
		);

		$data['action'] = $this->url->link('extension/dashboard/websky_iranmap', 'user_token=' . $this->session->data['user_token'], true);
		$data['cancel'] = $this->url->link('marketplace/extension', 'user_token=' . $this->session->data['user_token'] . '&type=dashboard', true);
		$data['columns'] = range(3, 12);

		$defaults = array(
			'dashboard_websky_iranmap_width'      => 6,
			'dashboard_websky_iranmap_status'     => 1,
			'dashboard_websky_iranmap_sort_order' => 5,
			'dashboard_websky_iranmap_address'    => 'payment',
			'dashboard_websky_iranmap_color'      => '#1e91cf'
		);

		foreach ($defaults as $key => $default) {
			if (isset($this->request->post[$key])) {
				$data[$key] = $this->request->post[$key];
			} elseif ($this->config->get($key) !== null) {
				$data[$key] = $this->config->get($key);
			} else {
				$data[$key] = $default;
			}
		}

		$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/dashboard/websky_iranmap_form', $data));
	}

	protected function validate() {
		if (!$this->user->hasPermission('modify', 'extension/dashboard/websky_iranmap')) {
			$this->error['warning'] = $this->language->get('error_permission');
		}

		return !$this->error;
	}

	public function dashboard() {
		$this->load->language('extension/dashboard/websky_iranmap');

		$data['data_url'] = html_entity_decode($this->url->link('extension/dashboard/websky_iranmap/data', 'user_token=' . $this->session->data['user_token'], true), ENT_QUOTES, 'UTF-8');
		$data['map_url'] = 'view/javascript/websky_iranmap/iran.svg?v=1.0.0';
		$data['map_color'] = $this->sanitizeColor($this->config->get('dashboard_websky_iranmap_color'));
		$data['provinces_json'] = json_encode($this->language->get('text_provinces'), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

		return $this->load->view('extension/dashboard/websky_iranmap_info', $data);
	}

	public function data() {
		$json = array('provinces' => array(), 'total_orders' => 0, 'total_amount' => '');

		if (!$this->user->hasPermission('access', 'extension/dashboard/websky_iranmap')) {
			$this->response->addHeader('HTTP/1.1 403 Forbidden');
			$json['error'] = 'Permission denied';
		} else {
			$this->load->model('extension/dashboard/websky_iranmap');

			$source = $this->config->get('dashboard_websky_iranmap_address') === 'shipping' ? 'shipping' : 'payment';
			$results = $this->model_extension_dashboard_websky_iranmap->getOrderTotalsByProvince($source);
			$total_amount = 0;

			foreach ($results as $result) {
				$province_code = $this->model_extension_dashboard_websky_iranmap->resolveProvinceCode($result['zone_code'], $result['zone_name']);

				if (!$province_code) {
					continue;
				}

				if (!isset($json['provinces'][$province_code])) {
					$json['provinces'][$province_code] = array('total' => 0, 'amount_value' => 0);
				}

				$json['provinces'][$province_code]['total'] += (int)$result['total'];
				$json['provinces'][$province_code]['amount_value'] += (float)$result['amount'];
				$json['total_orders'] += (int)$result['total'];
				$total_amount += (float)$result['amount'];
			}

			foreach ($json['provinces'] as &$province) {
				$province['amount'] = $this->currency->format($province['amount_value'], $this->config->get('config_currency'));
				unset($province['amount_value']);
			}
			unset($province);

			$json['total_amount'] = $this->currency->format($total_amount, $this->config->get('config_currency'));
		}

		$this->response->addHeader('Content-Type: application/json; charset=utf-8');
		$this->response->setOutput(json_encode($json, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
	}

	public function install() {
		$this->load->model('setting/setting');

		$map_status = $this->config->get('dashboard_map_status');
		$map_width = (int)$this->config->get('dashboard_map_width');
		$map_sort_order = (int)$this->config->get('dashboard_map_sort_order');

		$this->model_setting_setting->editSetting('dashboard_websky_iranmap', array(
			'dashboard_websky_iranmap_width'               => $map_width >= 3 ? $map_width : 6,
			'dashboard_websky_iranmap_status'              => 1,
			'dashboard_websky_iranmap_sort_order'          => $map_sort_order,
			'dashboard_websky_iranmap_address'             => 'payment',
			'dashboard_websky_iranmap_color'               => '#1e91cf',
			'dashboard_websky_iranmap_previous_map_status' => $map_status ? 1 : 0
		));

		if ($map_status !== null) {
			$this->model_setting_setting->editSettingValue('dashboard_map', 'dashboard_map_status', 0);
		}
	}

	public function uninstall() {
		$this->load->model('setting/setting');

		$previous_status = $this->config->get('dashboard_websky_iranmap_previous_map_status');

		if ($previous_status !== null && $this->config->get('dashboard_map_status') !== null) {
			$this->model_setting_setting->editSettingValue('dashboard_map', 'dashboard_map_status', (int)$previous_status);
		}

		$this->model_setting_setting->deleteSetting('dashboard_websky_iranmap');
	}

	private function sanitizeColor($color) {
		if (is_string($color) && preg_match('/^#[0-9a-f]{6}$/i', $color)) {
			return strtolower($color);
		}

		return '#1e91cf';
	}
}
