<?php

/**
 * Pageimage for Contao
 *
 * Copyright (c) 2015 Benjamin Roth
 *
 * @license LGPL-3.0+
 */

namespace eSM_pageimage;

 
class Pageimage extends \Frontend
{

    public static function getImages()
    {
        global $objPage;
        $arrImages = array();

        // Image settings
        $sb_imageUrl = deserialize($objPage->sb_imageUrl);
        $sb_imageOrder = deserialize($objPage->sb_imageOrder);
        $sb_imageSize = $objPage->sb_imageSize;

        // Inherit images if current page has none
        if ((!count($sb_imageUrl) || (count($sb_imageUrl) == 1 && !$sb_imageUrl[0])) && !$objPage->sb_imageIgnore)
        {
            $pid = $objPage->id;
            // Inherit settings
            do
            {
                $objParentPage = \Database::getInstance()->prepare("SELECT * FROM tl_page WHERE id=?")
                    ->limit(1)
                    ->execute($pid);
                if ($objParentPage->numRows < 1)
                {
                    break;
                }

                $pid = $objParentPage->pid;
                $type = $objParentPage->type;

                $arrParentImageUrl = deserialize($objParentPage->sb_imageUrl);

                if ((!is_array($sb_imageUrl) || !count($sb_imageUrl) || !$sb_imageUrl[0]) && (is_array($arrParentImageUrl) && count($arrParentImageUrl) && $arrParentImageUrl[0]))
                {

                    $sb_imageUrl = deserialize($objParentPage->sb_imageUrl);
                    $sb_imageSize = $objParentPage->sb_imageSize;
                    $sb_imageOrder = deserialize($objParentPage->sb_imageOrder);
                    break;
                }
            }
            while ($pid > 0 && $type != 'root');
        }

        // Order images
        if ($sb_imageOrder != '' && (!count($sb_imageUrl) || (count($sb_imageUrl) == 1 && !$sb_imageUrl[0])))
        {
            $tmp = $sb_imageOrder;

            if (!empty($tmp) && is_array($tmp))
            {
                // Remove all values
                $arrOrder = array_map(function(){}, array_flip($tmp));

                // Move the matching elements to their position in $arrOrder
                foreach ($sb_imageUrl as $k=>$v)
                {
                    if (array_key_exists($v, $arrOrder))
                    {
                        $arrOrder[$v] = $v;
                        unset($sb_imageUrl[$k]);
                    }
                }

                // Append the left-over images at the end
                if (!empty($sb_imageUrl))
                {
                    $arrOrder = array_merge($arrOrder, array_values($sb_imageUrl));
                }

                // Remove empty (unreplaced) entries
                $sb_imageUrl = array_values(array_filter($arrOrder));
                unset($arrOrder);
            }
        }

        if (count($sb_imageUrl) && $sb_imageUrl[0])
        {

            // Get all images
            $multiSRC = array_values($sb_imageUrl);
            $objFiles = \FilesModel::findMultipleByIds($multiSRC);

            while ($objFiles->next()) {
                // Continue if the files has been processed or does not exist
                if (isset($arrImages[$objFiles->path]) || !file_exists(TL_ROOT.'/'.$objFiles->path)) {
                    continue;
                }

                // Single files
                $objFile = new \File($objFiles->path, true);

                if (!$objFile->isImage) {
                    continue;
                }

                $arrMeta = static::getMetaData($objFiles->meta, $objPage->language);

                if (empty($arrMeta)) {
                    if ($objPage->rootFallbackLanguage !== null) {
                        $arrMeta = static::getMetaData($objFiles->meta, $objPage->rootFallbackLanguage);
                    }
                }

                // Use the file name as title if none is given
                if ($arrMeta['title'] == '') {
                    $arrMeta['title'] = specialchars($objFile->basename);
                }

                // Add the image
                $arrImages[$objFiles->path] = array
                (
                    'id' => $objFiles->id,
                    'uuid' => $objFiles->uuid,
                    'name' => $objFile->basename,
                    'singleSRC' => $objFiles->path,
                    'alt' => $arrMeta['title'],
                    'imageUrl' => $arrMeta['link'],
                    'caption' => $arrMeta['caption'],
                    'size' => $sb_imageSize
                );
            }
            $arrImages = array_values($arrImages);
            unset($objFiles);
            unset($multiSRC);
        }

        return $arrImages;

    }

    public static function getPageImage($strType='images')
    {
        $Hook = new HookPageimage();
        return $Hook->piReplaceInsertTags('sb_'.$strType);
    }
}