<?php

/**
 * The controller that handles upload of files.
 * Also shows the preview of temporal upload.
 */
class UploadController extends AppBackendController {

	public $front = [ 'index', 'preview' ];

	/**
	 * Allow the upload without authentication.
	 */
	public function beforeFilter() {
		$this->Auth->allow();
		parent::beforeFilter();
	}

	/**
	 * Handle the upload of a file.
	 */
	public function index() {
		try {

			// Extract from single and multiple upload
			$info = $this->request->data[Upload::POST_PLACEHOLDER];

			// Validate
			$file = new \Intellex\Upload\UploadFile($info['tmp_name']);
			if (!in_array($file->getExtension(), Upload::$ALLOWED_EXTENSIONS)) {
				// FIXME throw new Exception("Unsupported file type.");
			}

			# Handle the upload
			$handler = new \Intellex\Upload\Handler($file, TMP . 'upload', SECURITY_SALT);
			$handler->setMeta([
				'token'     => $handler->getToken(),
				'file'      => Upload::getPreviewURLForToken($handler->getToken(), $handler->getFile()->getExtension(true)),
				'thumbnail' => Upload::getPreviewURLForToken($handler->getToken(), $handler->getFile()->getExtension(true)),
				'extra'     => $handler->getFile()->getExtra(),
				'filesize'  => $handler->getFile()->getSize(),
				'size'      => formatBytes($handler->getFile()->getSize(), 0),
				'extension' => $handler->getFile()->getExtension(true)
			]);

			// If extension cannot be parsed
			if (!$handler->getMeta()['extension']) {
				throw new Exception(__('The type of the file cannot be verified.'));
			}

			// Send response
			$handler->respond();

		} catch (\Exception $ex) {
			\Intellex\Upload\Handler::error($ex);
		}
	}

	/**
	 * Show the preview of the file stored in the temporal directory.
	 *
	 * @param string $token The token of the file.
	 */
	public function preview($token) {

		# Clear the optional extension
		$token = preg_replace('~\.\w+$~', '', $token);

		# Get file
		try {
			$file = \Intellex\Upload\Handler::loadFile($token, TMP . 'upload', SECURITY_SALT);
		} catch (Exception $e) {
			$file = new \Intellex\Upload\File(VECTORCMS_ROOT . WEBROOT_DIR . DS . 'img' . DS . 'no-image.png');
		}

		# Get the requested size
		$width = key_exists('w', $this->request->query) ? $this->request->query['w'] : Upload::PREVIEW_WIDTH;
		$height = key_exists('h', $this->request->query) ? $this->request->query['h'] : Upload::PREVIEW_HEIGHT;

		# Display file
		$this->layout = false;
		$this->set(compact('file', 'width', 'height'));
	}

}
