<?php

class themeReservo extends Theme
{

    public $config = null;

    public function __construct()
    {
        // get the plugin config
        include('_theme_config.inc.php');

        // load config into the object
        $this->config = $themeConfig;
    }

    public function getThemeDetails()
    {
        return $this->config;
    }
	
	public function getHomepageBackgroundImageUrl()
	{
		// get database
		$db = Database::getDatabase();
		
		$home_images_selection_type = themeHelper::getConfigValue('home_images_selection_type');
		$home_images_short_url_pool = themeHelper::getConfigValue('home_images_short_url_pool');
		$next_image_change = (int)themeHelper::getConfigValue('next_image_change');
		$last_image_id = (int)themeHelper::getConfigValue('last_image_id');
		$imagesPoolArr = array();
		if(strlen($home_images_short_url_pool))
		{
			$imagesPoolArr = explode(',', $home_images_short_url_pool);
		}

		// should we get a new image
		$changeImage = false;
		switch($home_images_selection_type)
		{
			case 'random_public_weekly':
				if($next_image_change < time())
				{
					$changeImage = true;
					$next_image_change = (time()+(60*60*24*7));
				}
				break;
			case 'random_public_daily':
				if($next_image_change < time())
				{
					$changeImage = true;
					$next_image_change = (time()+(60*60*24));
				}
				break;
			case 'random_public_hourly':
				if($next_image_change < time())
				{
					$changeImage = true;
					$next_image_change = (time()+(60*60));
				}
				break;
			default:
				$changeImage = true;
				break;
		}
		
		// if we have no previous image
		if(!(int)$last_image_id)
		{
			$changeImage = true;
		}
		
		if($changeImage == false)
		{
			$imageId = $last_image_id;
		}
		else
		{
			// select random from pool of images
			if(COUNT($imagesPoolArr))
			{
				$randKey = array_rand($imagesPoolArr, 1);
				$imageUrl = $imagesPoolArr[$randKey];
				$imageId = (int)$db->getValue('SELECT id FROM file WHERE shortUrl = '.$db->quote($imageUrl).' LIMIT 1');
			}
			// select random image from all public images
			else
			{
				//$totalImages = $db->getValue('SELECT COUNT(file.id) AS total FROM file LEFT JOIN file_folder ON file.folderId = file_folder.id WHERE extension IN ('.file::getImageExtStringForSql().') AND statusId = 1 AND file_folder.isPublic > 1');
				$totalImages = $db->getValue('SELECT COUNT(file.id) AS total FROM file LEFT JOIN file_folder ON file.folderId = file_folder.id WHERE statusId = 1 AND file_folder.isPublic > 1');
				$randomImagePosition = mt_rand(0, $totalImages - 1);
				//$imageId = (int)$db->getValue('SELECT file.id FROM file LEFT JOIN file_folder ON file.folderId = file_folder.id WHERE extension IN ('.file::getImageExtStringForSql().') AND statusId = 1 AND file_folder.isPublic > 1 LIMIT '.$randomImagePosition.', 1');
				$imageId = (int)$db->getValue('SELECT file.id FROM file LEFT JOIN file_folder ON file.folderId = file_folder.id WHERE statusId = 1 AND file_folder.isPublic > 1 LIMIT '.$randomImagePosition.', 1');
			}
			
			// store new image
			if($home_images_selection_type != 'random_public_page_load')
			{
				themeHelper::setConfigValue('last_image_id', $imageId);
				themeHelper::setConfigValue('next_image_change', $next_image_change);
			}
		}

		if(!$imageId)
		{
			return $this->getFallbackHomepageBackgroundImageUrl();
		}
		
		// see if the cache exists
		$localCachePath = CACHE_DIRECTORY_ROOT . '/themes/'.$this->config['folder_name'].'/homepage-backgroud-'.(int)$imageId.'.jpg';
		if(file_exists($localCachePath))
		{
			return CACHE_WEB_ROOT . '/themes/'.$this->config['folder_name'].'/homepage-backgroud-'.(int)$imageId.'.jpg';
		}
                
                
		$fileObj = file::loadById($imageId);
                
		return $fileObj->getFileServerPath().'/ajax/_homepage_image.php?f='.$imageId;
	}
	
	public function getHomepageImageSliderUrls()
	{
		// get database
		$db = Database::getDatabase();
		
		$home_images_short_url_pool = themeHelper::getConfigValue('home_images_short_url_pool');
		$imagesPoolArr = array();
		if(strlen($home_images_short_url_pool))
		{
			$imagesPoolArr = explode(',', $home_images_short_url_pool);
		}

		// prepare return array
		$imageIdsArr = array();

		// select random from pool of images
		if(COUNT($imagesPoolArr))
		{
			$randKeys = array_rand($imagesPoolArr, 4);
			foreach($randKeys AS $randKey)
			{
				$imageUrl = $imagesPoolArr[$randKey];
				$imageId = $db->getRow('SELECT * FROM file WHERE shortUrl = '.$db->quote($imageUrl).' LIMIT 1');
				$imageIdsArr[] = $imageId;
			}
			
		}
		// select random image from all public images
		else
		{
			//$imageIds = $db->getRows('SELECT file.* FROM file, (
			//								SELECT file.id AS sid
			//								FROM file 
			//								LEFT JOIN file_folder ON file.folderId = file_folder.id 
			//								WHERE file_folder.isPublic > 1 AND file.extension IN ('.file::getImageExtStringForSql().') AND file.statusId = 1
			//								ORDER BY RAND() 
			//								LIMIT 4
			//								) tmp WHERE file.id = tmp.sid AND extension IN ('.file::getImageExtStringForSql().') AND statusId = 1');
			$imageIds = $db->getRows('SELECT file.* FROM file, (
											SELECT file.id AS sid
											FROM file 
											LEFT JOIN file_folder ON file.folderId = file_folder.id 
											WHERE file_folder.isPublic > 1 AND file.statusId = 1
											ORDER BY RAND() 
											LIMIT 4
											) tmp WHERE file.id = tmp.sid AND statusId = 1');
			foreach($imageIds AS $imageId)
			{
				$imageIdsArr[] = $imageId;
			}
		}

		if(!COUNT($imageIdsArr))
		{
			return false;
		}

		// final urls
		$urls = array();
		foreach($imageIdsArr AS $imageIdsArrItem)
		{
			$fileObj = file::hydrate($imageIdsArrItem);
			$urls[] = array('url'=>$fileObj->getFileServerPath().'/plugins/imageviewer/site/resize_image_inline.php?f='.(int)$fileObj->id.'&w=400&h=300&m=middle', 'path'=>$fileObj->getFullShortUrl());
		}
		
		return $urls;
	}
	
	public function getFallbackHomepageBackgroundImageUrl()
	{
		return coreFunctions::getCoreSitePath().'/themes/'.$this->config['folder_name'].'/frontend_assets/images/reservo/home-bg-1.jpg';
	}
	
	public function getThemeSkin()
	{
		$skin = themeHelper::getConfigValue('site_skin');
		if(strlen($skin))
		{
			return $skin;
		}
		
		return false;
	}
	
	public function getFacebookPageUrl()
	{
		$facebookPage = themeHelper::getConfigValue('facebook_page_url');
		if(strlen($facebookPage))
		{
			return $facebookPage;
		}
		
		return false;
	}
	
	public function getMainLogoUrl()
	{
		// get database
		$db = Database::getDatabase();

		// see if the replaced logo exists
		$localCachePath = CACHE_DIRECTORY_ROOT . '/themes/'.$this->config['folder_name'].'/logo.png';
		if(file_exists($localCachePath))
		{
			return CACHE_WEB_ROOT . '/themes/'.$this->config['folder_name'].'/logo.png';
		}
		
		return $this->getFallbackMainLogoUrl();
	}
	
	public function getTotalSiteImages($formatted = false)
	{
		$stats = file::getTotalActiveFileStats();
		$total = (int)$stats['totalFileCount'];
		if($formatted == true)
		{
			$total = number_format($total, 0);
		}

		return $total;
	}
	
	public function getTotalSiteImageViews($formatted = false)
	{
		$stats = file::getTotalActiveFileStats();
		$total = (int)$stats['totalVisits'];
		if($formatted == true)
		{
			$total = number_format($total, 0);
		}
		
		return $total;
	}
	
	public function getFallbackMainLogoUrl()
	{
		return coreFunctions::getCoreSitePath().'/themes/'.$this->config['folder_name'].'/frontend_assets/images/reservo/logo/main-site-lg.png';
	}
    
    public function getSimilarImages(file $file)
    {
        $similarFiles = array();
        
        // get all other images in the same folder/album, only if this file is in an actual folder
		$clause = '';
        if((int)$file->folderId)
        {
			$clause = 'folderId = ' . (int)$file->folderId;
		}
		elseif($file->folderId == NULL && (int)$file->userId)
		{
			$clause = 'folderId IS NULL AND userId = '.(int)$file->userId;
		}
		
		if(strlen($clause))
		{
            $db = Database::getDatabase(true);
			
			// load orderby from session
			$orderBy = 'originalFilename';
			if(isset($_SESSION['search']['filterOrderBy']))
			{
				$orderBy = $_SESSION['search']['filterOrderBy'];
			}
			
			$similarFiles = $db->getRows('SELECT * FROM file WHERE ' . $clause . ' AND statusId = 1 ORDER BY '.$db->escape($this->convertSortOption($orderBy)));
			if (!is_array($similarFiles))
			{
				return array();
			}
		}


        if(!COUNT($similarFiles))
        {
            return array();            
        }
        
        // set the currently selected on as the first
        $startArr = array();
        $endArr = array();
        $found = false;        
        $rsArr = array();
        foreach($similarFiles AS $similarFile)
        {
			// make sure it's an image
			$file = file::hydrate($similarFile);
			if($file->isImage())
			{
				$rsArr[] = $file;
			}
        }

        return $rsArr;
    }
	
	public function convertSortOption($filterOrderBy)
	{
		$sortColName = 'originalFilename asc';
		switch($filterOrderBy)
		{
			case 'order_by_filename_asc':
				$sortColName = 'originalFilename asc';
				break;
			case 'order_by_filename_desc':
				$sortColName = 'originalFilename desc';
				break;
			case 'order_by_uploaded_date_asc':
			case '':
				$sortColName = 'uploadedDate asc';
				break;
			case 'order_by_uploaded_date_desc':
				$sortColName = 'uploadedDate desc';
				break;
			case 'order_by_downloads_asc':
				$sortColName = 'visits asc';
				break;
			case 'order_by_downloads_desc':
				$sortColName = 'visits desc';
				break;
			case 'order_by_filesize_asc':
				$sortColName = 'fileSize asc';
				break;
			case 'order_by_filesize_desc':
				$sortColName = 'fileSize desc';
				break;
			case 'order_by_last_access_date_asc':
				$sortColName = 'lastAccessed asc';
				break;
			case 'order_by_last_access_date_desc':
				$sortColName = 'lastAccessed desc';
				break;
		}
		
		return $sortColName;
	}
	
	public function outputCustomCSSCode()
	{
		// see if the replaced logo exists
		$localCachePath = CACHE_DIRECTORY_ROOT . '/themes/'.$this->config['folder_name'].'/custom_css.css';
		if(file_exists($localCachePath))
		{
			return "<link href=\"".CACHE_WEB_ROOT . "/themes/".$this->config['folder_name']."/custom_css.css?r=".md5(microtime())."\" rel=\"stylesheet\">\n";
		}
	}
	
	public function getCustomCSSCode()
	{
		return themeHelper::getConfigValue('css_code');
	}

}
