<?php
if (!defined("ROOT_PATH"))
{
	header("HTTP/1.1 403 Forbidden");
	exit;
}
class pjAdminFloorplans extends pjAdmin
{
	private $imageFiles = array('small_path', 'medium_path', 'large_path', 'source_path');
	
	private $imageFillColor = array(255, 255, 255);
	
	public function pjActionCreate()
	{
		$this->checkLogin();
		
		if ($this->isAdmin() || $this->isEditor())
		{
			$post_max_size = pjUtil::getPostMaxSize();
			if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_SERVER['CONTENT_LENGTH']) && (int) $_SERVER['CONTENT_LENGTH'] > $post_max_size)
			{
				pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdminFloorplans&action=pjActionIndex&err=AF05");
			}
			if (isset($_POST['floorplan_create']))
			{
				$id = pjFloorplanModel::factory($_POST)->insert()->getInsertId();
				if ($id !== false && (int) $id > 0)
				{					
					if (isset($_FILES['image']) && !empty($_FILES['image']['name']))
					{
						$Image = new pjImage();
						$Image->setAllowedTypes(array('image/png', 'image/gif', 'image/jpg', 'image/jpeg', 'image/pjpeg'));
						if ($Image->load($_FILES['image']))
						{
							$resp = $Image->isConvertPossible();
							if ($resp['status'] === true)
							{
								$hash = md5(uniqid(rand(), true));
								$image_path = PJ_UPLOAD_PATH . 'floorplans/' . $id . '_' . $hash . '.' . $Image->getExtension();
								$original_image_path = PJ_UPLOAD_PATH . 'floorplans/original/' . $id . '_' . $hash . '.' . $Image->getExtension();
						
								$Image->loadImage();
								$Image->saveImage($image_path);
								$Image->saveImage($original_image_path);
									
								$data = array();
								$data['image'] = $image_path;
								$data['original_image'] = $original_image_path;
						
								pjFloorplanModel::factory()->where('id', $id)->limit(1)->modifyAll($data);
							}
						}else{
							if($Image->getErrorCode() == '121')
							{
								pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminFloorplans&action=pjActionUpdate&id=$id&err=AF07");
							}
							pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdminFloorplans&action=pjActionUpdate&id=$id&err=AF06");
						}
					}
					
					$err = 'AF03';
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminFloorplans&action=pjActionUpdate&id=$id&err=$err");
				} else {
					$err = 'AF04';
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminFloorplans&action=pjActionIndex&err=$err");
				}
				
			} else {
				$this->appendJs('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
				$this->appendJs('pjAdminFloorplans.js');
			}
		} else {
			$this->set('status', 2);
		}
	}
		
	public function pjActionDeleteFloorplan()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$response = array();
			$pjFloorplanModel = pjFloorplanModel::factory();
			$arr = $pjFloorplanModel->find($_GET['id'])->getData();
			if (pjFloorplanModel::factory()->setAttributes(array('id' => $_GET['id']))->erase()->getAffectedRows() == 1)
			{
				pjSectionModel::factory()->where('floorplan_id', $_GET['id'])->eraseAll();
				@clearstatcache();
				if (!empty($arr['image']) && is_file(PJ_INSTALL_PATH . $arr['image']))
				{
					@unlink(PJ_INSTALL_PATH . $arr['image']);
					@unlink(PJ_INSTALL_PATH . $arr['original_image']);
				}
				$pjGalleryModel = pjGalleryModel::factory();
				$arr = $pjGalleryModel->where('foreign_id', $_GET['id'])->findAll()->getData();
				if (count($arr) > 0)
				{
					foreach ($arr as $item)
					{
						foreach ($this->imageFiles as $file)
						{
							@clearstatcache();
							if (!empty($item[$file]) && is_file($item[$file]))
							{
								@unlink($item[$file]);
							}
						}
					}
					$pjGalleryModel->eraseAll();
				}
				$response['code'] = 200;
			} else {
				$response['code'] = 100;
			}
			pjAppController::jsonResponse($response);
		}
		exit;
	}
	
	public function pjActionDeleteFloorplanBulk()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if (isset($_POST['record']) && count($_POST['record']) > 0)
			{
				$pjFloorplanModel = pjFloorplanModel::factory();
				$arr = $pjFloorplanModel->whereIn('id', $_POST['record'])->findAll()->getData();
				$pjFloorplanModel->reset()->whereIn('id', $_POST['record'])->eraseAll();
				pjSectionModel::factory()->whereIn('floorplan_id', $_POST['record'])->eraseAll();
				foreach($arr as $v)
				{
					@clearstatcache();
					if (!empty($v['image']) && is_file(PJ_INSTALL_PATH . $v['image']))
					{
						@unlink(PJ_INSTALL_PATH . $v['image']);
						@unlink(PJ_INSTALL_PATH . $v['original_image']);
					}
				}
				$arr = pjGalleryModel::factory()->whereIn('foreign_id', $_POST['record'])->findAll()->getData();
				if (!empty($arr))
				{
					pjGalleryModel::factory()->whereIn('foreign_id', $_POST['record'])->eraseAll();
					foreach ($arr as $item)
					{
						foreach ($this->imageFiles as $file)
						{
							@clearstatcache();
							if (!empty($item[$file]) && is_file($item[$file]))
							{
								@unlink($item[$file]);
							}
						}
					}
				}
			}
		}
		exit;
	}
	
	public function pjActionGetFloorplan()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$pjFloorplanModel = pjFloorplanModel::factory();
			
			if (isset($_GET['q']) && !empty($_GET['q']))
			{
				$q = pjObject::escapeString($_GET['q']);
				$pjFloorplanModel->where("t1.title LIKE '%$q%'");
			}

			if (isset($_GET['status']) && !empty($_GET['status']) && in_array($_GET['status'], array('T', 'F')))
			{
				$pjFloorplanModel->where('t1.status', $_GET['status']);
			}
			
			$column = 'title';
			$direction = 'ASC';
			if (isset($_GET['direction']) && isset($_GET['column']) && in_array(strtoupper($_GET['direction']), array('ASC', 'DESC')))
			{
				$column = $_GET['column'];
				$direction = strtoupper($_GET['direction']);
			}

			$total = $pjFloorplanModel->findCount()->getData();
			$rowCount = isset($_GET['rowCount']) && (int) $_GET['rowCount'] > 0 ? (int) $_GET['rowCount'] : 10;
			$pages = ceil($total / $rowCount);
			$page = isset($_GET['page']) && (int) $_GET['page'] > 0 ? intval($_GET['page']) : 1;
			$offset = ((int) $page - 1) * $rowCount;
			if ($page > $pages)
			{
				$page = $pages;
			}
			
			$data = $pjFloorplanModel
				->select("t1.*, (SELECT COUNT(TG.id) FROM `".pjGalleryModel::factory()->getTable()."` AS TG WHERE TG.foreign_id=t1.id) AS cnt_images")
				->orderBy("$column $direction")
				->limit($rowCount, $offset)
				->findAll()
				->getData();
				
			pjAppController::jsonResponse(compact('data', 'total', 'pages', 'page', 'rowCount', 'column', 'direction'));
		}
		exit;
	}
		
	public function pjActionIndex()
	{
		$this->checkLogin();
		
		if ($this->isAdmin() || $this->isEditor())
		{
			$this->appendJs('jquery.datagrid.js', PJ_FRAMEWORK_LIBS_PATH . 'pj/js/');
			$this->appendJs('pjAdminFloorplans.js');
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionSaveFloorplan()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			pjFloorplanModel::factory()->where('id', $_GET['id'])->limit(1)->modifyAll(array($_POST['column'] => $_POST['value']));
		}
		exit;
	}
	
	public function pjActionUpdate()
	{
		$this->checkLogin();

		if ($this->isAdmin() || $this->isEditor())
		{
			$post_max_size = pjUtil::getPostMaxSize();
			if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_SERVER['CONTENT_LENGTH']) && (int) $_SERVER['CONTENT_LENGTH'] > $post_max_size)
			{
				pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdminFloorplans&action=pjActionIndex&err=AF09");
			}
			if (isset($_POST['floorplan_update']))
			{
				pjFloorplanModel::factory()->where('id', $_POST['id'])->limit(1)->modifyAll($_POST);
				
				if (isset($_FILES['image']) && !empty($_FILES['image']['name']))
				{
					$Image = new pjImage();
					$Image->setAllowedTypes(array('image/png', 'image/gif', 'image/jpg', 'image/jpeg', 'image/pjpeg'));

					if ($Image->load($_FILES['image']))
					{
						$resp = $Image->isConvertPossible();
						if ($resp['status'] === true)
						{
							$hash = md5(uniqid(rand(), true));
							$image_path = PJ_UPLOAD_PATH . 'floorplans/' . $_POST['id'] . '_' . $hash . '.' . $Image->getExtension();
							$original_image_path = PJ_UPLOAD_PATH . 'floorplans/original/' . $_POST['id'] . '_' . $hash . '.' . $Image->getExtension();
			
							$Image->loadImage();
							$Image->saveImage($image_path);
							$Image->saveImage($original_image_path);
								
							$data = array();
							$data['image'] = $image_path;
							$data['original_image'] = $original_image_path;
			
							pjFloorplanModel::factory()->where('id', $_POST['id'])->limit(1)->modifyAll($data);
						}
					}else{
						if($Image->getErrorCode() == '121')
						{
							pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminFloorplans&action=pjActionUpdate&id=".$_POST['id']."&err=AF10");
						}
						pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdminFloorplans&action=pjActionUpdate&id=".$_POST['id']."&err=AF11");
					}
				}
				
				pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdminFloorplans&action=pjActionUpdate&id=".$_POST['id']."&err=AF01");
			} else {
				$arr = pjFloorplanModel::factory()->find($_GET['id'])->getData();
				if (count($arr) === 0)
				{
					pjUtil::redirect(PJ_INSTALL_URL. "index.php?controller=pjAdminFloorplans&action=pjActionIndex&err=AF08");
				}

				$this->set('arr', $arr);
				$this->set('section_arr', pjSectionModel::factory()->where('floorplan_id', $_GET['id'])->orderBy("t1.id ASC")->findAll()->getData());
				
				# Gallery plugin
				$this->appendCss('pj-gallery.css', pjObject::getConstant('pjGallery', 'PLUGIN_CSS_PATH'));
				$this->appendJs('ajaxupload.js', pjObject::getConstant('pjGallery', 'PLUGIN_JS_PATH'));
				$this->appendJs('jquery.gallery.js', pjObject::getConstant('pjGallery', 'PLUGIN_JS_PATH'));
				
				$this->appendJs('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
				$this->appendJs('jquery.ui.rotatable.js', PJ_THIRD_PARTY_PATH . 'jquery_ui/js/');
				$this->appendJs('pjAdminFloorplans.js');
			}
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionAddSection()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$response = array();
			if(isset($_GET['id']))
			{
				$data = array();
				$data['floorplan_id'] = $_GET['id'];
				$data['top'] = $_GET['top'];
				$data['left'] = $_GET['left'];
				$data['type'] = $_GET['type'];
				$id = pjSectionModel::factory($data)->insert()->getInsertId();
				$response['code'] = 200;
				$response['id'] = $id;
			}else{
				$response['code'] = 100;
			}
			pjAppController::jsonResponse($response);
		}
		exit;
	}
	
	public function pjActionUpdateSize()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$response = array();
			if(isset($_GET['id']))
			{
				$data = array();
				$data['width'] = $_GET['width'];
				$data['height'] = $_GET['height'];
				pjSectionModel::factory()->where('id', $_GET['id'])->limit(1)->modifyAll($data);
				$response['code'] = 200;
			}else{
				$response['code'] = 100;
			}
			pjAppController::jsonResponse($response);
		}
		exit;
	}
	
	public function pjActionUpdatePos()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$response = array();
			if(isset($_GET['id']))
			{
				$data = array();
				$data['top'] = $_GET['top'];
				$data['left'] = $_GET['left'];
				if($_GET['type'] == 'info')
				{
					$data['width'] = 32;
					$data['height'] = 32;
				}
				pjSectionModel::factory()->where('id', $_GET['id'])->limit(1)->modifyAll($data);
				$response['code'] = 200;
			}else{
				$response['code'] = 100;
			}
			pjAppController::jsonResponse($response);
		}
		exit;
	}
	
	public function pjActionUpdateTransform()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$response = array();
			if(isset($_GET['id']))
			{
				$data = array();
				$data['deg'] = $_GET['deg'];
				pjSectionModel::factory()->where('id', $_GET['id'])->limit(1)->modifyAll($data);
				$response['code'] = 200;
			}else{
				$response['code'] = 100;
			}
			pjAppController::jsonResponse($response);
		}
		exit;
	}
	
	public function pjActionGetSection()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if(isset($_GET['id']))
			{
				$pjSectionModel = pjSectionModel::factory();
				$arr = $pjSectionModel->find($_GET['id'])->getData();

				$image_id_arr = $pjSectionModel
					->reset()
					->where('floorplan_id', $arr['floorplan_id'])
					->where('t1.id <>', $_GET['id'])
					->where('t1.type', 'image')
					->where('t1.image_id <>', 'NULL')
					->findAll()
					->getDataPair(null, 'image_id');
				$pjGalleryModel = pjGalleryModel::factory(); 
				if(!empty($image_id_arr))
				{
					$pjGalleryModel->whereNotIn('id', $image_id_arr);
				}
				$gallery_arr = $pjGalleryModel
					->where('t1.foreign_id', $arr['floorplan_id'])
					->orderBy('t1.sort ASC')
					->findAll()
					->getData();
				
				$this->set('gallery_arr', $gallery_arr);
				$this->set('arr', $arr);
			}
		}
	}
	
	public function pjActionUpdateSection()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$response = array();
			if(isset($_POST['id']))
			{
				if($_POST['type'] == 'image')
				{
					$data = array();
					$data['width'] = $_POST['size'];
					$data['height'] = $_POST['size'];
					$data['deg'] = $_POST['deg'];
					$data['image_id'] = $_POST['image_id'];
					$data['position'] = $_POST['position'];
					pjSectionModel::factory()->where('id', $_POST['id'])->limit(1)->modifyAll($data);
					$response['type'] = 'image';
					$response['data'] = $data;
				}else{
					$response['type'] = 'info';
					pjSectionModel::factory()->where('id', $_POST['id'])->limit(1)->modifyAll($_POST);
				}
				$response['code'] = 200;
			}else{
				$response['code'] = 100;
			}
			pjAppController::jsonResponse($response);
		}
		exit;
	}
	
	public function pjActionDeleteSection()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$response = array();
			if(isset($_GET['id']))
			{
				pjSectionModel::factory()->setAttributes(array('id' => $_GET['id']))->erase();
				$response['code'] = 200;
			}else{
				$response['code'] = 100;
			}
			pjAppController::jsonResponse($response);
		}
		exit;
	}
	
	public function pjActionDeleteImage()
	{
		$this->setAjax(true);
		
		$pjFloorplanModel = pjFloorplanModel::factory();
		$arr = $pjFloorplanModel->find($_POST['id'])->getData();
		$response = array();
		if(!empty($arr))
		{
			$image_path = $arr['image'];
			if (file_exists(PJ_INSTALL_PATH . $image_path)) {
				@unlink(PJ_INSTALL_PATH . $image_path);
			}
			$data = array();
			$data['image'] = ':NULL';
			$pjFloorplanModel->reset()->where(array('id' => $_POST['id']))->limit(1)->modifyAll($data);
			pjSectionModel::factory()->where('floorplan_id', $_POST['id'])->eraseAll();
		
			$response['code'] = 200;
		}else{
			$response['code'] = 100;
		}
		pjAppController::jsonResponse($response);
		exit;
	}
	
	public function pjActionResizeImage()
	{
		$this->setAjax(true);
		
		$pjFloorplanModel = pjFloorplanModel::factory();
		$arr = $pjFloorplanModel->find($_POST['id'])->getData();
		$response = array();
		if(!empty($arr))
		{
			$Image = new pjImage();
			$Image->loadImage($arr['image']);
			$Image->setFillColor($this->imageFillColor);
			$Image->resizeSmart($_POST['new_width'], $_POST['new_height']);
			$Image->saveImage($arr['image']);
			
			$response['code'] = 200;
		}else{
			$response['code'] = 100;
		}
		pjAppController::jsonResponse($response);
		exit;
	}
	
	public function pjActionRestoreImage()
	{
		$this->setAjax(true);
	
		$pjFloorplanModel = pjFloorplanModel::factory();
		$arr = $pjFloorplanModel->find($_GET['id'])->getData();
		$response = array();
		if(!empty($arr))
		{
			copy(PJ_INSTALL_PATH . $arr['original_image'], PJ_INSTALL_PATH . $arr['image']);
			$response['code'] = 200;
		}else{
			$response['code'] = 100;
		}
		pjAppController::jsonResponse($response);
		exit;
	}
}
?>