<?php

// some initial headers
header("HTTP/1.0 200 OK");
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Pragma: no-cache");

// per page options
$defaultPerPage = 12;

// setup initial params
if(!isset($_SESSION['album']['perPage']) || (int)$_SESSION['album']['perPage'] == 0)
{
	$_SESSION['album']['perPage'] = $defaultPerPage;
}
$pageStart = (int)$_REQUEST['pageStart'];
$perPage = (int)$_REQUEST['perPage']>0?(int)$_REQUEST['perPage']:$_SESSION['album']['perPage'];

// setup initial params
$userId = (int)$_REQUEST['userId'];

$db = Database::getDatabase();

// image extensions
$imageExtArr = file::getImageExtStringForSql();

// save session params
$_SESSION['album']['perPage'] = $perPage;

// get total
$totalFolders = (int)$db->getValue('SELECT COUNT(file_folder.id) FROM file_folder WHERE userId = '.(int)$userId.' AND file_folder.isPublic = 2 AND file_folder.accessPassword IS NULL AND (SELECT COUNT(file.id) FROM file WHERE file.folderId = file_folder.id AND isPublic != 0) > 0');

// load limited page filtered
$folders = $db->getRows('SELECT file_folder.id, file_folder.userId, file_folder.parentId, file_folder.folderName, file_folder.accessPassword, file_folder.coverImageId, (SELECT COUNT(file.id) FROM file WHERE file.folderId = file_folder.id AND file.statusId = 1) AS total_images, (SELECT file.id FROM file WHERE file.folderId = file_folder.id AND file_folder.isPublic = 2 AND file.statusId = 1 AND extension IN('.$imageExtArr.') LIMIT 1) AS coverImageIdBackup FROM file_folder WHERE userId = '.(int)$userId.' AND file_folder.isPublic = 2 AND file_folder.accessPassword IS NULL AND (SELECT COUNT(file.id) FROM file WHERE file.folderId = file_folder.id AND isPublic != 0) > 0 ORDER BY date_added DESC, folderName ASC LIMIT '.(($pageStart - 1) * (int)$_SESSION['album']['perPage']) .','.$_SESSION['album']['perPage']);

$returnJson['html'] = '';
if ($folders)
{
	$returnJson['html'] .= '<div class="gallery-env"><div class="row">';
	
    // output albums
    foreach ($folders AS $folder)
    {
        $folderObj = fileFolder::hydrate($folder);
		
		// prepare cover image
		$coverData = $folderObj->getCoverData();
		$coverId = (int)$coverData['file_id'];
		$coverUniqueHash = $coverData['unique_hash'];
		
		// get sub images
		$subImageArr = array(0 => 0, 1=> 0);
		$sQL = 'SELECT file.id FROM file WHERE file.folderId = '.(int)$folder['id'].' AND file.statusId = 1 AND file.id != '.(int)$coverId.' ORDER BY uploadedDate DESC LIMIT 2';
		$childImages = $db->getRows($sQL);
		if($childImages)
		{
			foreach($childImages AS $k=>$childImage)
			{
				// make sure we have the file hash
				$uniqueHash = $childImage['unique_hash'];
				if(strlen($uniqueHash) == 0)
				{
					$uniqueHash = file::createUniqueFileHash($childImage['id']);
				}
				
				$subImageArr[$k] = array('file_id'=>$childImage['id'], 'unique_hash'=>$uniqueHash);
			}
		}
		
        $returnJson['html'] .= '<div class="col-sm-4">';
		$returnJson['html'] .= '<article class="album">';
		$returnJson['html'] .= '<header class="images">';
		$returnJson['html'] .= '<a href="#" onClick="loadImages('.(int)$folder['id'].'); return false;" class="image-1"><img src="'.CACHE_WEB_ROOT.'/plugins/imageviewer/'.(int)$coverId.'/'.$coverUniqueHash.'/300x206_middle.jpg"></a>';
		$returnJson['html'] .= '<div class="sub-images">';
		$returnJson['html'] .= '	<a href="#" onClick="showImage('.(int)$subImageArr[0].'); return false;" class="image-2"><img src="'.CACHE_WEB_ROOT.'/plugins/imageviewer/'.(int)$subImageArr[0]['file_id'].'/'.$subImageArr[0]['unique_hash'].'/100x100_middle.jpg" title="'.$folder['sub_images'].'"></a>';
		$returnJson['html'] .= '	<a href="#" onClick="showImage('.(int)$subImageArr[1].'); return false;" class="image-3"><img src="'.CACHE_WEB_ROOT.'/plugins/imageviewer/'.(int)$subImageArr[1]['file_id'].'/'.$subImageArr[1]['unique_hash'].'/100x100_middle.jpg"></a>';
		$returnJson['html'] .= '</div>';
		$returnJson['html'] .= '<div class="clear"></div>';
		$returnJson['html'] .= '</header>';
		$returnJson['html'] .= '<section class="album-info"> <h3><a href="#" onClick="loadImages('.(int)$folder['id'].'); return false;">'.str_replace(' ', '&nbsp;', validation::safeOutputToScreen($folder['folderName'])).'<div class="album-images-count"> <i class="entypo-picture"></i>'.validation::safeOutputToScreen($folder['total_images']).'</div></a></h3></section>';
		$returnJson['html'] .= '</article>';
		$returnJson['html'] .= '</div>';
    }
	
	$returnJson['html'] .= '</div>';
	
	$currentPage = $pageStart;
	$totalPages = ceil((int)$totalFolders/(int)$_SESSION['album']['perPage']);
	$pagingHtml .= '<div class="paginationRow row">';
	$pagingHtml .= '	<div id="pagination" class="paginationWrapper col-md-12 responsiveAlign">';
	$pagingHtml .= '		<ul class="pagination">';
	$pagingHtml .= '			<li class="'.($currentPage==1?'disabled':'').'"><a href="#" onClick="'.($currentPage>1?'loadAlbumsByUserId(\''.$userId.'\');':'').' return false;"><i class="entypo-to-start"></i> <span>'.UCWords(t('first', 'first')).'</span></a></li>';
	$pagingHtml .= '			<li class="'.($currentPage==1?'disabled':'').'"><a href="#" onClick="'.($currentPage>1?'loadAlbumsByUserId(\''.$userId.'\', '.((int)$currentPage-1).');':'').' return false;"><i class="entypo-left-dir"></i> <span>'.UCWords(t('previous', 'previous')).'</span></a></li>';
	
	// calculate numbers before and after
	$startPager = $currentPage - 3;
	if($startPager < 1)
	{
		$startPager = 1;
	}
	
	for($i=0; $i<=6; $i++)
	{
		$currentPager = $startPager + $i;
		if($currentPager > $totalPages)
		{
			continue;
		}
		$pagingHtml .= '		<li class="'.(($currentPager == $currentPage)?'active':'').'"><a href="#" onclick="loadAlbumsByUserId(\''.$userId.'\', '.(int)$currentPager.'); return false;">'.(int)$currentPager.'</a></li>';
	}

	$pagingHtml .= '			<li class="'.($currentPage==$totalPages?'disabled':'').'"><a href="#" onClick="'.($currentPage!=$totalPages?'loadAlbumsByUserId(\''.$userId.'\', '.((int)$currentPage+1).');':'').' return false;"><span>'.UCWords(t('next', 'next')).'</span> <i class="entypo-right-dir"></i></a></li>';
	$pagingHtml .= '			<li class="'.($currentPage==$totalPages?'disabled':'').'"><a href="#" onClick="'.($currentPage!=$totalPages?'loadAlbumsByUserId(\''.$userId.'\', '.((int)$totalPages).');':'').' return false;"><span>'.UCWords(t('last', 'last')).'</span> <i class="entypo-to-end"></i></a></li>';
	$pagingHtml .= '		</ul>';
	$pagingHtml .= '	</div>';
	
	$pagingHtml .= '</div>';
	
	$returnJson['html'] .= $pagingHtml;
	
	$returnJson['html'] .= '</div>';
}
else
{
    $returnJson['html'] .= '<h2>'.t('this_user_has_not_set_any_albums_public', 'This user has not publicly shared any albums.').'</h2>';
}

// output response
echo json_encode($returnJson);
