<?php

/**
 * Description of ParagraphImageDAL
 *
 * @author Kopi
 */
class ImageDAL {

	public static function Insert($obj) {

		$db = Registry::Get('db');
		$sql = "INSERT INTO mf_image SET " . SQL::ToUpdateSet($obj);

		$stmt = $db->prepare($sql)->execute();
		return $stmt->GetInsertionId();
	}

	public static function Update($obj)
	{
		$db = Registry::Get('db');

		$sql = "UPDATE mf_image SET ". SQL::ToUpdateSet($obj) ." WHERE id_mf_image=:1 ";
		$stmt=$db->prepare($sql)
		->bindParam(1, $obj->GetId())
		->execute();

	}

	public static function UpdateGroup($obj)
	{
		$db = Registry::Get('db');

		$sql = "UPDATE mf_image SET ". SQL::ToUpdateSet($obj) ." WHERE id_image_group=:1 ";
		$stmt=$db->prepare($sql)
		->bindParam(1, $obj->GetIdImageGroup())
		->execute();

	}
	public static function UpdateSort($id, $sort)
	{
		$db = Registry::Get('db');

		$sql = "UPDATE mf_image SET position = :2 WHERE id_mf_image=:1 ";
		$stmt=$db->prepare($sql)
		->bindParam(1, $id)
		->bindParam(2, $sort)
		->execute();

	}
	public static function UpdateTitle($idImageGroup,$title)
	{
		$db = Registry::Get('db');
		$sql = "UPDATE mf_image SET title=:*#1#* WHERE id_image_group=:*#2#*";
		$stmt=$db->prepare($sql)
		->bindParam("*#1#*", $title)
		->bindParam("*#2#*", $idImageGroup)
		->execute();
	}
	public static function UpdateAuthor($idImageGroup,$value)
	{
		$db = Registry::Get('db');
		$sql = "UPDATE mf_image SET author=:*#1#* WHERE id_image_group=:*#2#*";
		$stmt=$db->prepare($sql)
		->bindParam("*#1#*", $value)
		->bindParam("*#2#*", $idImageGroup)
		->execute();
	}
	public static function UpdateDescription($idImageGroup,$value)
	{
		$db = Registry::Get('db');
		$sql = "UPDATE mf_image SET description=:*#1#* WHERE id_image_group=:*#2#*";
		$stmt=$db->prepare($sql)
		->bindParam("*#1#*", $value)
		->bindParam("*#2#*", $idImageGroup)
		->execute();
	}

	public static function Delete($obj,$deleteLink = true)
	{
		
		$db = Registry::Get('db');

		$sql = "DELETE FROM mf_image WHERE id_mf_image =:1";
		$stmt=$db->Prepare($sql)
		->BindParam(1, $obj->GetId())
		->Execute();
	}


	public static function DeleteGroup($idGroup)
	{

		$imageGroupArray = self::GetResult(array("id_image_group" => $idGroup));

		foreach($imageGroupArray as $key => $image)
		{
			PhotoDAL::SimpleDelete(array(ArticleConst::$imageDir,$image->GetPath()));
		}


		//pobieramy wszystkie polaczenia zdjecia
		$mfLinkArrayObj = MfLinkDAL::GetResult(array('destination_type' => "'mf_image'", 'source_type' => "'mf_gallery'", 'id_destination' => $idGroup));

		//usuwanie raz wszytkich
		MfLinkDAL::DeleteFromLink(null, null, $idGroup, 'mf_image');

		foreach($mfLinkArrayObj as $key => $value)
		{
			// przeliczanie galerii
			MfLinkDAL::ReCountWeight($value->getIdSource(),"mf_gallery","mf_image");
		}


		$db = Registry::Get('db');
		$sql = "DELETE FROM mf_image WHERE id_image_group=:1";
		$stmt=$db->prepare($sql)
		->bindParam(1, $idGroup)
		->execute();


	}
	/**
	 *
	 * @param <ParagrafImage> $obj
	 * @param <array> $files - miejsce zapisu plikow array(katalog,plik)
	 * @param <array> $size - rozmiar array(x,y)
	 * @return <string> $fileName
	 */

	public static $imageSize = array(1=> array(282,194),
	2=> array(159,110),
	3=> array(280,200),
	4=> array(175,350),
	5=> array(279,198),
	6=> array(630,400),
	7=> array(100,130),
	8=> array(250,30),
	9=> array(470,280)
	);
	public static function AddImage($obj,$files,$size = 0,$localStorage = false,$sizeArray = array(),$cropForce = true,$imgDir = null)
	{
		$crop = false;
		switch($size)
		{
			case 1:
				$arraySize =  array(120,60);
				$crop = false;
				break;
			case 2:
				$arraySize =  array(80,80);
				$crop = false;
				break;
			case 3:
				$arraySize =  array(120,120);
				$crop = false;
				break;
			case 4:
				$arraySize =  array(100,120);
				$crop = false;
				break;
			case 5:
				$arraySize =  array(1600,1200);
				$crop = false;
				break;
			default:
				$arraySize =  array(120,120);
				break;
		}
		$cropOption = "center";
		if($cropForce !== null)
		{
			$crop = $cropForce;
			$cropOption = null;
		}
		if(count($sizeArray) > 0)
		$arraySize = $sizeArray;

		$src = md5(microtime());
		if($localStorage == true)
		$imagedir = is_null($imgDir)?'category':$imgDir;
		else
		$imagedir = is_null($imgDir)?'article':$imgDir;

		$file = PhotoDAL::SimpleFileUpload($files, array($imagedir,$src), $arraySize, $cropOption,$crop,$localStorage);

		if($file == "1")
		{
			MfLog::debug('nieprawidłowy plik bmp ');
			return false;
		}

		if($file == "" && $localStorage == false)
		{
			MfLog::debug('edysk przymulil zdjecie dodane ponownie ');
			self::AddImage($obj, $files, $size, $localStorage, $sizeArray, $cropForce);
		}

		return $file;
	}


	//dodajemy z zipa i robimy insert do tablic i linkow
	public static function AddImageFromZip(&$obj,$files,$table = null,$id =null)
	{
		$zip_name = md5(microtime());
		move_uploaded_file($files['tmp_name'], 'temp/' . $zip_name . '.zip');
		$zip = new ZipArchive;
		$zip->open("temp/" . $zip_name . ".zip");
		mkdir('temp/extracted/' . $zip_name);
		$zip->extractTo('temp/extracted/' . $zip_name);
		$zip->close();
		unlink('temp/' . $zip_name . '.zip');

		if ($handle = opendir('temp/extracted/' . $zip_name)) {

			$db = Registry::Get('db');
			$maxIdGroup = ImageDAL::GetMaxIdGroup();
			//$maxIdGroup++;
			MfLog::debug('pobrano max id grupy: '.$maxIdGroup);

			if($table != null)
			{
				$maxWeight = MfLinkDAL::GetCount($id,$table,"mf_image");
				if($maxWeight == "" || $maxWeight == 0)
				$maxWeight = 0;
			}
			while (false !== ($file = readdir($handle)))
			{
				if(strpos(strtolower($file), '.jpg',1) || strpos(strtolower($file), '.jpeg',1))
				{
					$db->BeginTransaction();

					$files = array();
					$files["tmp_name"] = 'temp/extracted/' . $zip_name .'/' . $file;
					$files["type"] = "image/jpeg";

					$obj->SetIdImageGroup($maxIdGroup);

					$obj->setPath(self::AddImage($obj, $files, 1));
					$obj->SetSize(1);
					$idImage = ImageDAL::Insert($obj);

					$obj->setPath(self::AddImage($obj, $files, 2));
					$obj->SetSize(2);
					$idImage = ImageDAL::Insert($obj);

					$obj->setPath(self::AddImage($obj, $files, 3));
					$obj->SetSize(3);
					$idImage = ImageDAL::Insert($obj);

					$obj->setPath(self::AddImage($obj, $files, 4));
					$obj->SetSize(4);
					$idImage = ImageDAL::Insert($obj);

					$obj->setPath(self::AddImage($obj, $files, 5));
					$obj->SetSize(5);
					$idImage = ImageDAL::Insert($obj);

					$obj->setPath(self::AddImage($obj, $files, 6));
					$obj->SetSize(6);
					$idImage = ImageDAL::Insert($obj);

					$obj->setPath(self::AddImage($obj, $files, 9));
					$obj->SetSize(9);
					$idImage = ImageDAL::Insert($obj);

					MfLog::debug('rozpakowany obrazek: '.$file);

					// linkujemy
					if($table != null)
					{
						$objLink = new MfLink();
						$objLink->SetSourceType($table);
						$objLink->SetIdSource($id);
						$objLink->SetDestinationType("mf_image");
						$objLink->SetIdDestination($maxIdGroup);
						$objLink->SetWeight($maxWeight);
						MfLinkDAL::Insert($objLink);

						$maxWeight++;
					}

					//usuwamy zdj�cie
					//unlink('temp/extracted/' . $zip_name .'/' .$file);
					$db->CommitTransaction();
					MfLog::debug('dodano obrazk do bazy: '.$file);

					$maxIdGroup = ImageDAL::GetMaxIdGroup();

					MfLog::debug('pobrano max id grupy: '.$maxIdGroup);
				}
				else
				{
					MfLog::debug('usuniety plik rozpoznany jako nieobrazek: '.$file);
					//if(is_file('temp/extracted/' . $zip_name .'/' .$file)) {unlink('temp/extracted/' . $zip_name .'/' .$file);}
				}
			}

			closedir($handle);
			//rmdir('temp/extracted/' . $zip_name);
		}
	}

	/**
	 * pobieranie listy rekordow
	 * @param <array> $data - pola do where
	 * @param <array> $queryFields - pobierane pola
	 * @param <string> $limit - limit rekordow
	 * @param <string> $sortBy - sortowanie
	 * @param <bool> $count - czy ma zwracac ilosc rekordow
	 * @param <string> $group - grupowanie
	 * @return <array> - tablica obiektow lub jesli usawiony count liczba rekordow
	 */

	public static function GetResult($data,$limit = 0, $sortBy = null,$count = null,$groupBy = null) {

		if(!is_array($data)){
			$data = array();
		}

		$db = Registry::Get('db');
		if($count == true)
		$select = 'count(*) as count';
		else
		$select =" " . SQL::ToSelect('Image');

		$sql = " SELECT $select FROM mf_image WHERE 1=1 ";

		foreach ($data as $key => $value)
		{
			if($key == "id")
			$key = 'id_mf_image' ;

			if(is_array($value))
			$sql .= ( is_numeric($value['value']) || $value ? " AND ".$key." ".$value['condition']." ". $value['value'] : "");
			else
			$sql .= ( is_numeric($value) || $value ? " AND ".$key." = ". $value : "");
		}

		$sql .= ( $groupBy ? " GROUP BY $groupBy " : "").
		( $sortBy ? " ORDER BY $sortBy " : "").
		( $limit ? " LIMIT " . $limit : "").
		" ";

		$stmt = $db->prepare($sql)
		->execute();

		$array = $stmt->fetchAllAssoc();

		if($count == true)
		return  $array[0]['count'];

		$done = array();

		for($i=0;$i<count($array);$i++)
		{
			$obj = new Image();
			$obj->FromArray($array[$i],1);



			$done[] = $obj;
		}
		return $done;

	}


	/**
	 * pobieranie listy rekordow
	 * @param <array> $data - pola do where
	 * @param <array> $queryFields - pobierane pola
	 * @param <string> $limit - limit rekordow
	 * @param <string> $sortBy - sortowanie
	 * @param <bool> $count - czy ma zwracac ilosc rekordow
	 * @param <string> $group - grupowanie
	 * @return <array> - tablica obiektow lub jesli usawiony count liczba rekordow
	 */

	public static function GetResultConnection($data,$limit = 0, $sortBy = null,$count = null,$groupBy = null) {

		if(!is_array($data)){
			$data = array();
		}

		$db = Registry::Get('db');
		if($count == true)
		$select = 'count(*) as count';
		else
		$select =" " . SQL::ToSelect('Image') . ", " . SQL::ToSelect('Article') . ", " . SQL::ToSelect('Gallery') .  ", " . SQL::ToSelect('Source') . ", " . SQL::ToSelect('Country');

		$sql = " SELECT $select FROM mf_image LEFT JOIN mf_link ON mf_image.id_image_group=mf_link.id_destination
											  LEFT JOIN wp_source ON wp_source.id_wp_source=mf_image.id_wp_source
											  LEFT JOIN mf_article ON mf_link.id_source=mf_article.id_mf_article AND mf_link.source_type='mf_article' AND mf_link.destination_type='mf_image'
											  LEFT JOIN mf_gallery ON mf_link.id_source=mf_gallery.id_mf_gallery AND mf_link.source_type='mf_gallery' AND mf_link.destination_type='mf_image'
											  LEFT JOIN wp_country ON mf_link.id_source=wp_country.id_wp_country AND mf_link.source_type='wp_country' AND mf_link.destination_type='mf_image' 

		WHERE 1=1 ";

		foreach ($data as $key => $value)
		{
			if($key == "id")
			$key = 'id_mf_image' ;

			if(is_array($value))
			$sql .= ( is_numeric($value['value']) || $value ? " AND ".$key." ".$value['condition']." ". $value['value'] : "");
			else
			$sql .= ( is_numeric($value) || $value ? " AND ".$key." = ". $value : "");
		}

		$sql .= ( $groupBy ? " GROUP BY $groupBy " : "").
		( $sortBy ? " ORDER BY $sortBy " : "").
		( $limit ? " LIMIT " . $limit : "").
		" ";

		$stmt = $db->prepare($sql)
		->execute();

		$array = $stmt->fetchAllAssoc();

		if($count == true)
		return  $array[0]['count'];

		$done = array();

		for($i=0;$i<count($array);$i++)
		{
			$obj = new Image();
			$obj->FromArray($array[$i],1);

			if(!isset($done[$obj->GetId()]))
			$done[$obj->GetId()] = $obj;

			$articleObj = new Article();
			$articleObj->FromArray($array[$i],1);

			$galleryObj = new Gallery();
			$galleryObj->FromArray($array[$i],1);

			$countryObj = new Country();
			$countryObj->FromArray($array[$i],1);

			$objSource = new Source();
			$objSource->FromArray($array[$i],1);

			$done[$obj->GetId()]->setSource($objSource);
			$done[$obj->GetId()]->setArticle($articleObj);
			$done[$obj->GetId()]->setGallery($galleryObj);
			$done[$obj->GetId()]->setCountry($countryObj);

		}
		return $done;

	}

	public static function GetResultByLink($table,$id,$data,$limit = 0, $sortBy = null,$count = null) {

		if(!is_array($data)){
			$data = array();
		}

		$db = Registry::Get('db');
		if($count == true)
		$select = 'count(*) as count';
		else
		$select =" " . SQL::ToSelect('Image') . ", mf_link.link_type ";

		$sql = " SELECT $select FROM mf_image INNER JOIN mf_link ON mf_image.id_image_group=mf_link.id_destination WHERE mf_link.source_type='$table' AND mf_link.id_source=$id AND mf_link.destination_type='mf_image '";

		foreach ($data as $key => $value)
		{
			if($key == "id")
			$key = 'id_mf_image' ;

			if(is_array($value))
			$sql .= ( is_numeric($value['value']) || $value ? " AND ".$key." ".$value['condition']." ". $value['value'] : "");
			else
			$sql .= ( is_numeric($value) || $value ? " AND ".$key." = ". $value : "");
		}

		$sql .= ( $sortBy ? " ORDER BY $sortBy " : "").
		( $limit ? " LIMIT " . $limit : "").
		" ";

		$stmt = $db->prepare($sql)
		->execute();

		$array = $stmt->fetchAllAssoc();

		if($count == true)
		return  $array[0]['count'];

		$done = array();

		for($i=0;$i<count($array);$i++)
		{
			$obj = new Image();
			$obj->setLinkType($array[$i]['link_type']);
			$obj->FromArray($array[$i],1);

			$done[] = $obj;
		}
		return $done;
	}







	public function GetMaxIdGroup()
	{
		$db = Registry::Get('db');

		//		$sql = "SELECT MAX(id_image_group) as max FROM mf_image";
		//
		//		$stmt = $db->prepare($sql)
		//		->execute();
		//
		//		$array = $stmt->fetchAllAssoc();
		//
		//		return  $array[0]['max'];

		//dodajemy do imagegroupdala
		$db->BeginTransaction();
		$imagegroupObj = new ImageGroup();
		$imagegroupObj->setAdds(1);
		$dalObj = ImageGroupDAL::GetDalDataObj();
		$dalObj->setObj($imagegroupObj);
		$id = ImageGroupDAL::Insert($dalObj);

		$db->CommitTransaction();
		return $id;

	}

	public static function AvatarSave($file) {
		$id = self::GetMaxIdGroup();

		Registry::get('db')->BeginTransaction();



		$sizes = array(1,2,3);

		$img = new Image();

		foreach($sizes AS $size) {
			$img = new Image();
			$created = ImageDAL::AddImage($img,array('tmp_name' => $file,'type' => 'image/jpeg'),$size,true,null,null,'avatar');

			$img->setIdImageGroup($id);
			$img->SetPath($created);
			$img->setSize($size);

			ImageDAL::Insert($img);
		}

		Registry::get('db')->CommitTransaction();

		return array($id,$img->getPath());
	}

	public static function PortfolioSave($file) {
		$id = self::GetMaxIdGroup();

		Registry::get('db')->BeginTransaction();



		$sizes = array(4,5);

		$img = new Image();

		foreach($sizes AS $size) {
			$img = new Image();
			$created = ImageDAL::AddImage($img,$file,$size,true,null,null,'portfolio');

			$img->setIdImageGroup($id);
			$img->SetPath($created);
			$img->setSize($size);

			ImageDAL::Insert($img);
		}

		Registry::get('db')->CommitTransaction();

		return $id;
	}

	public function SaveImage($iid, $folder = 'Gallery', $idImageGroup = 0, $arrayDescription = array()) {
		if (!is_dir(PATH_STATIC_CONTENT."upload/".$folder."/".$iid."/")) {
			mkdir(PATH_STATIC_CONTENT."upload/".$folder."/".$iid);
		}
		

		if (SessionProxy::IsSetValue('_ARRAY_PHOTO_')) {

			$arrayFiles = SessionProxy::GetValue('_ARRAY_PHOTO_');
			//Utils::ArrayDisplay($arrayFiles);
			if (isset($arrayFiles)) {
				//OfferDAL::UpdatePhoto($id, $arrayFiles[0]);
				if (count($arrayFiles) > 0 && !$idImageGroup && $idImageGroup == 0) {
					$objImageGroup = new ImageGroup();

					$idImageGroup = ImageGroupDAL::Insert($objImageGroup);
				}
				foreach ($arrayFiles as $key => $files) {

					foreach ($files as $k => $file) {
						$photo['id'] = $iid;
						$photo['kolejnosc'] = $key;
						$photo['nazwa'] = $file;


						$objImage = new Image();
						$objImage->SetPath($file);
						$objImage->setIdImageGroup($idImageGroup);
						if (key_exists($key, $arrayDescription)) {
							$objImage->SetDescription($arrayDescription[$key]);
						}
						
						if ($k == 'th') {
							$objImage->setSize(1);
						} elseif ($k == 'full') {
							$objImage->setSize(3);
						} else {
							$objImage->setSize(2);
						}
						

						$idImage = ImageDAL::Insert($objImage);

						$arrayPhoto[] = $photo;
						
						//Utils::ArrayDisplay(PATH_STATIC_CONTENT."temp/".$file);
						
						rename(PATH_STATIC_CONTENT."temp/".$file,PATH_STATIC_CONTENT."upload/".$folder."/".$iid."/".$file); 
					}

				}

			}
		}
		SessionProxy::ClearValue('_ARRAY_PHOTO_');

		return $idImageGroup;
	}

}
?>