<?php

class ModuleconnectionsController extends AppController {

	# Search through products.
	public function search() {
		$data = $this->request->data;
		$matched = $this->ModuleConnection->search($data);
		echo json_encode($matched);
		exit;
	}

	# Get all attached products for product with provided id.
	public function getAll($fatherModule, $sonModule, $id) {
		$matchedConnections = $this->ModuleConnection->getModuleConnections($fatherModule, $sonModule, $id);
		echo json_encode($matchedConnections);
		exit;
	}

	# Attach provided product to another product
	public function additem() {
		$data = $this->request->data;
		$this->ModuleConnection->save($data);
		echo json_encode([ 'status' => 'OK' ]);
		exit;
	}

	# Remove connection between two products.
	public function removeItem() {
		$data = $this->request->data;
		$this->ModuleConnection->removeConnection($data);
		echo json_encode([ 'status' => 'OK' ]);
		exit;
	}

	public function refreshOrdering($module, $connectedModule) {
		$data = $this->request->data;
		foreach ($data as $id => $order) {
			$this->ModuleConnection->save([
				'id'       => $id,
				'ordering' => $order
			]);
		}
		exit;
	}

	public function repairThumbs() {
		App::import('Helper', 'Format');
		$formatHelper = new FormatHelper(new View());
		$moduleConnections = $this->ModuleConnection->find('all');
		foreach ($moduleConnections as $moduleConn) {
			if (empty($moduleConn['ModuleConnection']['file']) && !empty($moduleConn['ModuleConnection']['son_module'])) {
				$sonInstance = ClassRegistry::init($moduleConn['ModuleConnection']['son_module']);
				$sonData = $sonInstance->find('first', $moduleConn['ModuleConnection']['son_fk']);

				if (isset($sonData['Image']) && !empty($sonData['Image']['file'])) {
					$moduleConn['ModuleConnection']['file'] = $formatHelper->image($sonData['Image'], 300, 200, false, [], true);
					$this->ModuleConnection->save($moduleConn);
				}
			}
		}
	}

}
