<?php

class MappingsController extends AppBackendController {

	# ~ Initialize model before all- - - - - - - - - - - - - - - - - - - - - - - - #
	function beforeFilter() {
		parent::beforeFilter();
		$this->Mapping = ClassRegistry::init('Mapping');
		$this->Mapping->cache = false;
	}

	# ~ Add pin to upload- - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
	public function addPin() {
		if (empty($this->request->data['upload_id']))
			die;

		$data = $this->request->data;
		$data['top'] = $this->request->data['coordinates']['percent']['top'];
		$data['left'] = $this->request->data['coordinates']['percent']['left'];

		unset($data['coordinates']);

		$pin = $this->Mapping->save($data);

		echo json_encode([ 'status' => 'success', 'data' => [ 'id' => $pin['Mapping']['id'] ] ]);
		exit;
	}

	# ~ Get pins for upload with supplied id - - - - - - - - - - - - - - - - - - - #
	public function getPins() {
		if (empty($this->request->data['upload_id']))
			die;

		$pins = $this->Mapping->find('all', [
			'recursive'  => -1,
			'conditions' => [
				'Mapping.upload_id'  => $this->request->data['upload_id'],
				'Mapping.is_deleted' => false
			]
		]);
		$pins = Set::extract('/Mapping/.', $pins);

		echo json_encode([ 'status' => 'success', 'data' => $pins ]);
		exit;
	}

	# ~ Delete pin - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
	public function deletePin() {
		if (empty($this->request->data['upload_id']) || empty($this->request->data['id']))
			die;

		$this->Mapping->updateAll(
			[
				'Mapping.is_deleted' => true
			],
			[
				'Mapping.id'        => $this->request->data['id'],
				'Mapping.upload_id' => $this->request->data['upload_id'] ]
		);

		echo json_encode([ 'status' => 'success', 'data' => [] ]);
		exit;
	}

}

?>
