<?php
defined('PRODUCT_NAME') or die;
class Gallery extends ModuleInstance
{
	function __construct()
	{
		parent::__construct();
		$this->cache_config->query_string = true;
	}

	// Using load() instead of __construct() allows us to access module settings.
	// Potential reprocucssions of this are still unknown.
	function load($id)
	{
		parent::load($id);

		$theme = $this->setting("theme");
		$this->scripts = array("<link rel=\"stylesheet\" href=\"/modules/gallery/" . $theme . "/colorbox.css\" />",
								"<script async src=\"/modules/gallery/jquery.colorbox-min.js\"></script>"
								);
		$this->enable_jquery = true;
	}

	function render($files = null)
	{
		$this->load->view("modules/gallery/module",
		                  array("module_instance_id" 	=> $this->module_instance_id,
								"title" 				=> $this->setting("title"),
								"title_heading_level" 	=> $this->setting("title_heading_level"),
		                        "module_class" 			=> $this->setting("module_class"),
		                        "files"					=> $files,
								"base"					=> $this->setting("directory"),
								"show_images"			=> $this->setting("show_images"),
								"show_videos"			=> $this->setting("show_videos"),
								"style"					=> $this->setting("style"),
								"ordering"				=> $this->setting("ordering"),
								"breakpoint_sm"			=> $this->setting("breakpoint_sm"),
								"breakpoint_md"			=> $this->setting("breakpoint_md"),
								"breakpoint_lg"			=> $this->setting("breakpoint_lg"),
								"breakpoint_xl"			=> $this->setting("breakpoint_xl"),
								"per_row_sm"			=> $this->setting("per_row_sm"),
								"per_row_md"			=> $this->setting("per_row_md"),
								"per_row_lg"			=> $this->setting("per_row_lg"),
								"per_row_xl"			=> $this->setting("per_row_xl"),
								"album_per_row_sm"		=> $this->setting("album_per_row_sm"),
								"album_per_row_md"		=> $this->setting("album_per_row_md"),
								"album_per_row_lg"		=> $this->setting("album_per_row_lg"),
								"album_per_row_xl"		=> $this->setting("album_per_row_xl"),
								"aspect_ratio"			=> $this->setting("aspect_ratio"),
								"theme"					=> $this->setting("theme"),
								"lightbox_width"		=> $this->setting("lightbox_width"),
								"lightbox_height"		=> $this->setting("lightbox_height"),
								"module"				=> $this));
	}

	function nice_alt($file)
	{
		// Create a cleaned up version of the file name as a default alt/title.
		$nice_alt = str_replace("%20", " ", basename($file));
		//remove file extension
		$nice_alt = str_ireplace(array(".jpg", ".jpeg", ".gif", ".png", ".bmp", ".tiff", "/thumbnails/"), "", $nice_alt);
		//put a space before all capital letters (camel case)
		$nice_alt = preg_replace('/([A-Z][a-z0-9])/', ' $1', $nice_alt);
		//remove any thumbnail resizing (100x50) from the end of the filename
		$nice_alt = preg_replace('/(_thumb)?_?(\d+)x(\d+)/', '', $nice_alt);
		//remove @2x from the end of the filename
		$nice_alt = preg_replace('/@2x/', '', $nice_alt);
		//replace remaining underscores, dashes, and slashes with spaces
		$nice_alt = str_replace(array("_", "/", "\\"), " ", $nice_alt);

		return trim($nice_alt);
	}

	function image($file, $directory, $max_width, $max_height, $css_class)
	{
		$file 		= str_replace("//", "/", $file);
		// $thumbnail 	= Mainframe::thumbnail($file, $max_width, $max_height, false, (strpos($this->setting("aspect_ratio"), ":") !== false ? $this->setting("aspect_ratio") : false), Mainframe::site()->webp ? IMAGETYPE_WEBP : null);
		// $size 		= @getimagesize(ABSOLUTE_PATH . $thumbnail);
		// $width 		= $size[0];
		// $height 	= $size[1];
		// Ensure that the full size image isn't astronomically huge.
		// $file 		= Mainframe::thumbnail($file, 1280, 1024, false, Mainframe::site()->webp ? IMAGETYPE_WEBP : null);
		$file 		= str_replace("%2F", "/", rawurlencode(str_ireplace(ABSOLUTE_PATH, "", $file)));
		// $thumbnail 	= str_replace("%2F", "/", rawurlencode($thumbnail));
		$nice_alt 	= $this->nice_alt($file);
		?>
		<div class="<?php echo($css_class); ?>">
			<div class="gallery-image">
				<a href="/img/1280/1024/0?src=<?php echo($file); ?>" class="lightbox" rel="gallery_<?php echo($this->module_instance_id); ?>" title="<?php echo($nice_alt); ?>"><img src="/img/<?php echo($max_width); ?>/<?php echo($max_height); ?>/<?php echo($max_width); ?>:<?php echo($max_height); ?>?src=<?php echo($file); ?>" width="<?php echo($max_width); ?>" height="<?php echo($max_height); ?>" alt="<?php echo($nice_alt); ?>" title="<?php echo($nice_alt); ?>" class="lazy" onload="this.style.opacity=1" /></a>
			</div>
		</div>
		<?php
	}

	function album_image($dirname, $file, $directory, $max_width, $max_height, $css_class, $display_type="")
	{
		$base		= $this->setting("directory");
		$file 		= str_replace("//", "/", $file);
		// $thumbnail 	= Mainframe::thumbnail($file, $max_width, $max_height, (strpos($this->setting("aspect_ratio"), ":") !== false ? $this->setting("aspect_ratio") : false), Mainframe::site()->webp ? IMAGETYPE_WEBP : null);
		// $size 		= @getimagesize(ABSOLUTE_PATH . $thumbnail);
		// $resized 	= true;
		// $width 		= $size[0];
		// $height 	= $size[1];
		// Ensure that the full size image isn't astronomically huge.
		// $file 		= Mainframe::thumbnail($file, 1280, 1024, false, Mainframe::site()->webp ? IMAGETYPE_WEBP : null);
		$file 		= str_replace("%2F", "/", rawurlencode(str_ireplace(ABSOLUTE_PATH, "", $file)));
		// $thumbnail 	= str_replace("%2F", "/", rawurlencode($thumbnail));
		$slash 		= strripos($dirname, "/");
		$nice_alt 	= $this->nice_alt($file);

		if($slash == false)
		{
			$clean_dirname = $dirname;
		}
		else
		{
			$clean_dirname = substr($dirname, $slash+1);
		}

		if(stripos($this->input->server("REQUEST_URI"), "?") === false)
		{
			$link = $this->input->server("REQUEST_URI") . "?dir=" . rawurlencode($dirname);
		}
		else
		{
			$link = substr($this->input->server("REQUEST_URI"), 0, stripos($this->input->server("REQUEST_URI"), "?")) . "?dir=" . rawurlencode($dirname);
		}
		?>
		<div class="<?php echo($css_class); ?>">
			<div class="gallery-image gallery-album">
				<?php
				$sub_files = scandir($directory . "/" . $base . "/" . $dirname);
				$has_images = false;

				foreach($sub_files as $sub_file)
				{
					$full_path = $directory . "/" . $base . "/" . $dirname . "/" . $sub_file;

					if(is_file($full_path) && @getimagesize($full_path))
					{
						$has_images = true;
						break;
					}
				}

				if($display_type == "lightbox" && $has_images)
				{
					$rel = "prettyPhoto[gallery_" . $this->module_instance_id . "_" . str_replace(array("(", ")", " ", "-"), "", $clean_dirname) . "]";

					//scan for subdirectory images to put in lightbox
					?>
					<div class="gallery-title"><a title="<?php echo($file); ?>" title="<?php echo($nice_alt); ?>"><?php echo($clean_dirname); ?></a></div>

					<a rel="<?php echo($rel); ?>" href="/img/1280/1024/0?src=<?php echo($file); ?>" title="<?php echo($nice_alt); ?>"><img src="/img/<?php echo($max_width); ?>/<?php echo($max_height); ?>/<?php echo($max_width); ?>:<?php echo($max_height); ?>?src=<?php echo($file); ?>&nocache=<?php echo(time()); ?>" width="<?php echo($width); ?>" height="<?php echo($height); ?>" alt="<?php echo($nice_alt); ?>" title="<?php echo($nice_alt); ?>" class="lazy" onload="this.style.opacity=1" /></a>

					<?php
					$count = 0;
					foreach($sub_files as $sub_file)
					{
						$full_path = $directory . "/" . $base . "/" . $dirname . "/" . $sub_file;

						if(is_file($full_path) && @getimagesize($full_path))
						{
							$count++;

							//skip first one since its above
							if($count == 1)
							{
								continue;
							}

							$public_url = $base . "/" . $dirname . "/" . $sub_file;// . "&nocache=" . time();
							?><a rel="<?php echo($rel); ?>" style="display: none;" href="<?php echo($public_url); ?>" title="<?php echo(htmlentities($clean_dirname)); ?>"><img src="<?php echo($public_url); ?>" width="<?php echo($max_width); ?>" height="<?php echo($max_height); ?>" alt="<?php echo(htmlentities($clean_dirname)); ?>" title="<?php echo(htmlentities($clean_dirname)); ?>" class="lazy" onload="this.style.opacity=1" /></a><?php
						}
					}
				}
				else
				{
					?>
					<div class="gallery-title"><a href="<?php echo($link); ?>" title="<?php echo($file); ?>"><?php echo($clean_dirname); ?></a></div>
					<a href="<?php echo($link); ?>" title="<?php echo(htmlentities($clean_dirname)); ?>"><img src="/img/<?php echo($max_width); ?>/<?php echo($max_height); ?>/<?php echo($max_width); ?>:<?php echo($max_height); ?>?src=<?php echo($file); ?>&nocache=<?php echo(time()); ?>" width="<?php echo($max_width); ?>" height="<?php echo($max_height); ?>" alt="<?php echo(htmlentities($dirname)); ?>" title="<?php echo(htmlentities($dirname)); ?>" class="lazy" onload="this.style.opacity=1" /></a>
					<?php
				}
				?>
			</div>
		</div>
		<?php
	}
}

if(!function_exists("ratio_sort"))
{
	function ratio_sort($a, $b)
	{
	    if($a["ratio"] == $b["ratio"])
	    {
	    	// Ratios are the same, sort by filename.
	        $a["path"] = basename($a["path"]);
			$b["path"] = basename($b["path"]);

			if($a["path"] == $b["path"])
		    {
		        return 0;
		    }
		    return ($a["path"] > $b["path"]) ? -1 : 1;
	    }

	    // Ratios differ, sort by ratio.
	    return ($a["ratio"] > $b["ratio"]) ? -1 : 1;
	}
}

if(!function_exists("date_sort"))
{
	function date_sort($a, $b)
	{
	    if($a["modified"] == $b["modified"])
	    {
	    	// Modified dates are the same, sort by filename.
	        $a["path"] = basename($a["path"]);
			$b["path"] = basename($b["path"]);

			if($a["path"] == $b["path"])
		    {
		        return 0;
		    }
		    return ($a["path"] > $b["path"]) ? -1 : 1;
	    }

	    // Modified dates differ, sort by modified.
	    return ($a["modified"] > $b["modified"]) ? -1 : 1;
	}
}
