<?php

class LanguagesController extends AppBackendController {

	var $name = 'Languages';
	var $uses = [ 'Language', 'Dictionary' ];
	var $paginate = [];
	var $components = [ 'Api' ];

	var $back = [ 'dictionary' ];

	function beforeIndex() {
		// $this->Language->refreshTables();
		$this->addAction('wrench', __('Repair polyglot'), [ C => 'languages', A => 'repair' ]);
		$this->addAction('book', __('Dictionary'), [ C => 'languages', A => 'dictionary' ]);
	}

	function beforeDelete($id) {

		# Do not allow administrators to delete default language
		$language = $this->Language->read('is_default', $id);
		if (!$language || reset(reset($language))) {
			$this->Session->setFlash(__('Cannot delete default language'), 'danger');
			$this->redirect([ C => 'languages', A => 'index' ]);
		}

		# Do not allow administrators to delete active language.
		$is_active = $this->Language->read('is_active', $id);
		if (!$is_active || reset(reset($is_active))) {
			$this->Session->setFlash(__('Cannot delete active language'), 'danger');
			$this->redirect([ C => 'languages', A => 'index' ]);
		}
	}

	# ~ Dictionary for translation of static text  - - - - - - - - - - - - - - - - #
	public function dictionary() {

		$this->crumbs[] = [ __('Languages'), [ C => 'languages', A => 'index' ] ];
		$this->crumbs[] = __('Dictionary');

		# Extract all static keys
		$this->Dictionary->extract();

		# Save if data
		if (!empty($this->request->data)) {

			# Just show informative message
			$this->Session->setFlash(__('Dictionary updated'));
			$this->redirect($this->request->here);
		}

		# Paste dictionary to view
		$this->set('dictionary', $this->Dictionary->find('all', [ 'conditions' => [ 'Dictionary.is_archive' => false ] ]));

		$this->render('/Languages/dictionary');
	}

	# ~ Get single term- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
	public function get_term() {
		foreach ([ 'key', 'domain', 'locale' ] as $key) {
			if (!isset($this->request->data[$key]))
				die;
		}

		$data = $this->request->data;

		$items = $this->Dictionary->find('all', [
			'cache'      => false,
			'recursive'  => -1,
			'callbacks'  => false,
			'fields'     => [ 'key', 'value' ],
			'conditions' => [
				'Dictionary.key'    => $data['key'],
				'Dictionary.domain' => $data['domain'],
				'Dictionary.locale' => $data['locale'],
			]
		]);

		// Case sensitive search
		// TODO: Implement this on db side
		$item = null;
		foreach ($items as $foundItem) {
			if ($foundItem['Dictionary']['key'] == $data['key']) {
				$item = $foundItem;
				break;
			}
		}

		$value = !empty($item) ? $item['Dictionary']['value'] : '';

		$this->Api->build(null, [
			'value' => $value
		]);
	}

	# ~ Save term- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
	public function save_term() {
		foreach ([ 'key', 'domain', 'locale', 'value' ] as $key) {
			if (!isset($this->request->data[$key]))
				die;
		}
		$data = $this->request->data;

		$items = $this->Dictionary->find('all', [
			'recursive'  => 1,
			'callbacks'  => false,
			'conditions' => [
				'Dictionary.key'    => $data['key'],
				'Dictionary.domain' => $data['domain'],
				'Dictionary.locale' => $data['locale'],
			]
		]);

		// Case sensitive search
		// TODO: Implement this on db side
		$item = null;
		foreach ($items as $foundItem) {
			if ($foundItem['Dictionary']['key'] == $data['key']) {
				$item = $foundItem;
				break;
			}
		}

		if (empty($item)) {
			$this->Api->build(null, [
				'success' => false,
				'message' => __('Item not saved')
			]);
		}

		$item['Dictionary']['value'] = $data['value'];

		$saved = $this->Dictionary->save($item);

		if ($saved) {
			$response = [
				'success' => true,
				'message' => __('Item saved')
			];

			$this->Api->build(null, $response);
		}

		$this->Api->build(null, [
			'success' => false,
			'message' => __('Item not saved')
		]);

	}

	/**
	 * Refreshes the tables for missing or corrupt polyglot columns.
	 * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
	public function repair() {
		$this->Language->refreshTables();
		$this->backtrack(__('Polyglot tables refreshed.'));
	}

}
