<?php

class ImagesController extends Controller
{

	static function actionGet()
	{
		$pointId = (int) App::getParam('id');
		$width = (int) App::getParam('width');
		$height = (int) App::getParam('height');

		if ($width <= 0 || $width > 200) {
			$width = 200;
		}

		if ($height <= 0 || $height > 200) {
			$height = 200;
		}

		if (!$pointId) {
			App::error404();
		}

		$point = Point::model()->getByPK($pointId);

		if (!$point) {
			App::error404();
		}

		$photos = $point->photos;
		$img = array_shift($photos);


		if ($img) {
			$photo = $photo = App::getBasedir() . '../public/' . 'photos/' . $img->name;
		} else {
			$photo = $photo = App::getBasedir() . '../public/' . 'img/noPhoto.png';
		}

		if (!file_exists($photo)) {
			$photo = $photo = App::getBasedir() . '../public/' . 'img/noPhoto.png';
		}

		Image::createCustomSize($photo, $width, $height);
//		print $photo;
	}

	static function actionLoadPhoto()
	{
		if (isset($_FILES) && !empty($_FILES) && App::$user) {
			$userId = App::$user->id;
			$uploaddir = App::getBasedir() . '../public/photos/articles/';
			$fileName = (string)$_FILES['photo']['name'];
			$temp = pathinfo($fileName);
			$extension = strtolower($temp['extension']) ? strtolower($temp['extension']) : 'jpg';
			$photo = $userId . strtolower('_' . substr(md5($fileName . time()), 0, 5) . '.' . $extension);
			if (move_uploaded_file($_FILES['photo']['tmp_name'], $uploaddir . $photo)) {
				ArticlePhotos::model()->add(array(
					'name' => $photo,
					'owner' => $userId,
					'caption' => isset($_POST['caption'])?$_POST['caption']:'',
					'uploaded' => time(),
				));

				Image::createAllSizes($photo, true, 'articles/');

				die($photo);
			}
		} else {
			App::error404();
		}

		die;
	}

}
