<?php

/**
 * Clients for Contao
 *
 * Copyright (c) 2014 Benjamin Roth [http://www.esales-media.de]
 *
 * @package eSM_clients
 * @link    http://www.esales-media.de
 * @license commercial
*/


/**
 * Run in a custom namespace, so the class can be replaced
 */
namespace eSM_clients;


/**
 * Shows a list of clients which have active projects
 *
 * @package   Modules
 * @author    Benjamin Roth <http://www.esales-media.de>
 * @copyright eSales Media 2014
 */
class ModuleClientsShowcase extends \Module
{
    /**
     * Template
     * @var string
     */
    protected $strTemplate = 'mod_clientsShowcase';

    /**
     * URL
     * @var string
     */
    protected $strLink;


    public function generate()
    {
        if (TL_MODE == 'BE')
        {
            $objTemplate = new \BackendTemplate('be_wildcard');

            $objTemplate->wildcard = '### ' . utf8_strtoupper($GLOBALS['TL_LANG']['FMD']['clientsShowcase'][0]) . ' ###';
            $objTemplate->title = $this->headline;
            $objTemplate->id = $this->id;
            $objTemplate->link = $this->name;
            $objTemplate->href = 'contao/main.php?do=themes&amp;table=tl_module&amp;act=edit&amp;id=' . $this->id;

            return $objTemplate->parse();
        }

        $this->strUrl = preg_replace('/\?.*$/', '', \Environment::get('request'));
        $this->strLink = $this->strUrl;

        return parent::generate();
    }

    /**
     * Compile the current element
     */
    protected function compile()
    {
        /** @var \PageModel $objPage */
        global $objPage;

        $limit = null;
        $offset = 0;

        // Maximum number of items
        if ($this->esm_numberOfItems > 0)
        {
            $limit = $this->esm_numberOfItems;
        }

        // Get the total number of items
        $intTotal = EsmClientsModel::countReferenceClients();

        if ($intTotal < 1)
        {
            return;
        }

        $total = $intTotal - $offset;

        // Split the results
        if ($this->perPage > 0 && (!isset($limit) || $this->esm_numberOfItems > $this->perPage))
        {
            // Adjust the overall limit
            if (isset($limit))
            {
                $total = min($limit, $total);
            }

            // Get the current page
            $id = 'page_cs' . $this->id;
            $page = (\Input::get($id) !== null) ? \Input::get($id) : 1;

            // Do not index or cache the page if the page number is outside the range
            if ($page < 1 || $page > max(ceil($total/$this->perPage), 1))
            {
                /** @var \PageError404 $objHandler */
                $objHandler = new $GLOBALS['TL_PTY']['error_404']();
                $objHandler->generate($objPage->id);
            }

            // Set limit and offset
            $limit = $this->perPage;
            $offset += (max($page, 1) - 1) * $this->perPage;

            // Overall limit
            if ($offset + $limit > $total)
            {
                $limit = $total - $offset;
            }

            // Add the pagination menu
            $objPagination = new \Pagination($total, $this->perPage, \Config::get('maxPaginationLinks'), $id);
            $this->Template->pagination = $objPagination->generate("\n  ");
        }

        $Clients = EsmClientsModel::getReferenceClients(($limit ?: 0), $offset);

        $strItems = '';

        foreach ($Clients as $client)
        {
            // Load client template
            $objClientTemplate = new \FrontendTemplate($this->esm_clientsShowcase_template);

            // Set template data
            $objClientTemplate->title = $client->title;
            $objClientTemplate->text = $client->text;
            $objClientTemplate->color = deserialize($client->basecolor);
            $objClientTemplate->branchId = $client->branch;

            // Branche
            $Branch = $client->getRelated('branch');
            if (!is_null($Branch))
            {
                $objClientTemplate->branch = $Branch->title;
            }

            // Neutral logo
            $objNeutralLogo = \FilesModel::findByUuid($client->logo_neutral);

            if (is_file(TL_ROOT . '/' . $objNeutralLogo->path))
            {
                $objFile = new \File($objNeutralLogo->path, true);
                $arrSize = $objFile->imageSize;
                $arrMeta = $this->getMetaData($objNeutralLogo->meta, $objPage->language);
                if (empty($arrMeta))
                {
                    if ($objPage->rootFallbackLanguage !== null)
                    {
                        $arrMeta = $this->getMetaData($objNeutralLogo->meta, $objPage->rootFallbackLanguage);
                    }
                }
                if ($arrMeta['title'] == '')
                {
                    $arrMeta['title'] = specialchars($objFile->basename);
                }
                $objClientTemplate->logo_neutral = array
                (
                    'src'         => $objNeutralLogo->path,
                    'width'       => $arrSize[0],
                    'height'      => $arrSize[1],
                    'attributes'  => $arrSize[3] . ' alt="' . $arrMeta['title'] . '"',
                    'meta'        => $arrMeta
                );

            }

            // Original logo
            $objOriginalLogo = \FilesModel::findByUuid($client->logo_original);

            if (is_file(TL_ROOT . '/' . $objOriginalLogo->path))
            {
                $objFile = new \File($objOriginalLogo->path, true);
                $arrSize = $objFile->imageSize;
                $arrMeta = $this->getMetaData($objOriginalLogo->meta, $objPage->language);
                if (empty($arrMeta))
                {
                    if ($objPage->rootFallbackLanguage !== null)
                    {
                        $arrMeta = $this->getMetaData($objOriginalLogo->meta, $objPage->rootFallbackLanguage);
                    }
                }
                if ($arrMeta['title'] == '')
                {
                    $arrMeta['title'] = specialchars($objFile->basename);
                }
                $objClientTemplate->logo_original = array
                (
                    'src'         => $objOriginalLogo->path,
                    'width'       => $arrSize[0],
                    'height'      => $arrSize[1],
                    'attributes'  => $arrSize[3] . ' alt="' . $arrMeta['title'] . '"',
                    'meta'        => $arrMeta
                );

            }

            // Get client projects
            $Projects = $client->getProjects();

            $arrProjects = array();
            foreach($Projects as $project)
            {

                $arrRow = $project->row();

                if ($this->jumpTo > 0)
                {
                    $objTarget = \PageModel::findByPk($this->jumpTo);

                    if ($objTarget !== null)
                    {
                        $strJumpTo = ampersand($this->generateFrontendUrl($objTarget->row(), ((\Config::get('useAutoItem') && !\Config::get('disableAlias')) ?  '/%s' : '/items/%s')));
                        $strJumpTo = sprintf($strJumpTo,(!\Config::get('disableAlias') && $project->alias != '') ? $project->alias : $project->id);

                        $arrRow['link'] = $strJumpTo;
                    }
                }

                $arrProjects[] = $arrRow;
            }

            $objClientTemplate->projects = $arrProjects;


            // Render Template
            $strItems .= $objClientTemplate->parse();
        }

        $this->Template->items = $strItems;
    }


}