<?php

/**
 *
 * PHP Pro Bid $Id$ jPnUxif+Zc8mhcDmJbY3ccffmXfzsD6JCiGMA+7vfRI=
 *
 * @link        http://www.phpprobid.com
 * @copyright   Copyright (c) 2017 Online Ventures Software & CodeCube SRL
 * @license     http://www.phpprobid.com/license Commercial License
 *
 * @version     7.9 [rev.7.9.01]
 */
/**
 * language selector widget view helper class
 * - the url will never change, just that we will add a param (lang = code) which will
 *   then trigger the language change plugin
 */

namespace Ppb\View\Helper;

use Cube\View\Helper\AbstractHelper,
    Cube\Controller\Front;

class Language extends AbstractHelper
{

    /**
     *
     * create and output language selector widget
     *
     * @return string|null
     */
    public function language()
    {
        $output = null;

        $frontController = Front::getInstance();
        $settings = $frontController->getBootstrap()->getResource('settings');

        if ($settings['user_languages']) {
            $activeLangImg = null;
            $activeLocale = $this->getTranslate()->getLocale();

            $translateOption = $frontController->getOption('translate');
            if (array_key_exists('translations', $translateOption)) {
                $languages = $translateOption['translations'];
                $nbLanguages = count($languages);

                $view = $this->getView();

                $flagPath = $view->baseUrl . \Ppb\Utility::URI_DELIMITER . \Ppb\Utility::getFolder('img') . \Ppb\Utility::URI_DELIMITER;
                foreach ($languages as $language) {
                    $img = '<img src="' . $flagPath . $language['img'] . '"  alt="' . $language['desc'] . '">';

                    if ($language['locale'] == $activeLocale) {
                        $activeLangImg = $img;
                    }

                    $output[] = '<li>'
                        . '<a href="' . $view->url(array('lang' => $language['locale']), null, true, null, true, false) . '">'
                        . $img . ' <span>' . $language['desc'] . '</span>'
                        . '</a>'
                        . '</li>';
                }

                if ($nbLanguages > 0) {
                    $output = '<div class="dropdown language-dropdown">'
                        . '<button class="btn btn-link dropdown-toggle" type="button" id="languageDropdown" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">'
                        . $activeLangImg
                        . (($nbLanguages > 1) ? '<span class="caret"></span>' : '')
                        . '</button>'
                        . (($nbLanguages > 1) ? '<ul class="dropdown-menu" aria-labelledby="dropdownMenu1">' . implode(' ', $output) . '</ul>' : '')
                        . '</div>';

                }
            }
        }

        return $output;
    }

}

