<?php
/*****************************************************************************
 * UploadMedia.php
 * Contains the media uploading controller
 *
 * Kabuki CMS (C) 2013-2015, Aaron van Geffen
 *****************************************************************************/

class UploadMedia extends HTMLController
{
	public function __construct()
	{
		// Ensure it's just admins at this point.
		if (!Registry::get('user')->isAdmin())
			throw new NotAllowedException();

		$page = new MediaUploader();
		parent::__construct('Upload new media - ' . SITE_TITLE);
		$this->page->adopt($page);

		// Are we saving something?
		if (isset($_POST['save']))
		{
			if (empty($_FILES) || empty($_FILES['new_asset']))
				return;

			// Any tags?
			$new_tags = [];
			if (isset($_POST['tag']) && is_array($_POST['tag']))
			{
				foreach ($_POST['tag'] as $id_tag => $bool)
					if (is_numeric($id_tag))
						$new_tags[] = $id_tag;
			}

var_dump($_FILES);
var_dump($_POST);

			foreach ($_FILES['new_asset']['tmp_name'] as $num => $uploaded_file)
			{
				if (empty($uploaded_file))
					continue;

				$asset = Asset::createNew([
					'filename_to_copy' => $uploaded_file,
					'preferred_filename' => $_FILES['new_asset']['name'][$num],
					'title' => !empty($_POST['title'][$num]) ? $_POST['title'][$num] : null,
				]);

				$asset->linkTags($new_tags);
			}

			// Prevent uploading twice.
			header('Location: ' . BASEURL . '/uploadmedia/');
			exit;
		}
	}
}