<?php
/**
 * @extension       Marlev Templates
 * @author          Lev Milicenco <support@marlev.it>
 * @link            http://www.marlev.it
 * @copyright       Copyright 2015 marlev.it All Rights Reserved
 * @license         http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
 *
 */
defined('_JEXEC') or die;
include JPATH_ADMINISTRATOR .'/components/com_tmarlevv2/controllers/layout.php';
class ml_template_helper {
    /*
     * 
     * 
     * 
     * 
     * 
     * Modules functions
     */

    static function get_Modules($ids) {
        if (empty($ids)) {
            return;
        }
        $id_s = implode(',', $ids);
        $groups = implode(',', \JFactory::getUser()->getAuthorisedViewLevels());
        $lang = \JFactory::getLanguage()->getTag();
        $db = JFactory::getDbo();
        $date = \JFactory::getDate();
        $now = $date->toSql();
        $nullDate = $db->getNullDate();

        $query = $db->getQuery(true);
        $query->select('id, title, module, position, content,showtitle, params,showtitle');
        $query->from('#__modules');
        $query->where('(publish_up = ' . $db->quote($nullDate) . ' OR publish_up <= ' . $db->quote($now) . ')')
                ->where('(publish_down = ' . $db->quote($nullDate) . ' OR publish_down >= ' . $db->quote($now) . ')')
                ->where('access IN (' . $groups . ')')
                ->where('id IN (' . $id_s . ')')
                ->where('client_id = 0')->where('published=1');

        $query->order($db->quoteName('ordering'));
        $db->setQuery($query);
        $modules = $db->loadObjectList();
        return $modules;
    }

    static function prepare_module_error_helper($stringarray, $defpositions) {
        $registry = new JRegistry;
        $registry->loadString($stringarray);
        $array = $registry->toArray();
        if (empty($array) && !empty($stringarray)) {
            $array = $stringarray;
        }

        function run_error_helper($return, $module) {
            $mod_id_pos = explode("[|]", $module);
            $return->positions[$mod_id_pos[0]] = $mod_id_pos[1];
            $return->ids[$mod_id_pos[1]] = $mod_id_pos[0];
            return $return;
        }

        $return = new stdClass();
        $return->positions = $defpositions;
        $return->ids = array();

        if (is_array($array)) {

            foreach ($array as $key => $module) {
                $return = run_error_helper($return, $module);
            }
        } elseif (!empty($array)) {

            $return = run_error_helper($return, $array);
        }
        return $return;
    }

    static function smista_modules($modules, $defpositions) {
        $return = new stdClass();
        $return->positions = $defpositions;
        $return->modules = array();
        foreach ($modules as $module) {
            $return->positions[] = $module->position;
            $return->modules[$module->position][] = $module;
        }

        return $return;
    }

    static function smista_modules_error($modules, $positions) {
        $return = array();
        if (!$modules) {
            return $return;
        }

        foreach ($positions as $null => $position) {
            foreach ($modules as $module) {
                if ($position == $module->position) {
                    $return[$position][] = $module;
                }
            }
        }
        return $return;
    }

    /*
     * 
     * 
     * 
     * 
     * 
     * Cookie functions
     */

    static function show_cookie($params, $cookie_position, $position) {
        if ($cookie_position === false || $cookie_position !== $position) {
            return true;
        }
        $lang = JFactory::getLanguage();
        $curlang = $lang->getTag();
        $finder = array(
            "cookie_title" => "Cookie Policy",
            "cookie_desc" => "Please note this website requires cookies, by continuing to browse our website you are agreeing to accept our cookie policy.",
            "cookie_accept" => "I accept",
            "cookie_more" => False,
            "cookie_link" => false,
        );
        $content = new stdClass();
        $deflang = $params->get('cookie_deflang', "");
        $style = $params->get('cookie_style', "cookie-black-trasparent");
        foreach ($finder as $key => $value) {
            $content->$key = $params->get($key . '_' . $curlang, false);
            if ($content->$key === false) {
                $content->$key = $params->get($key . '_' . $deflang, $finder[$key]);
            }
        }
        return self::cookie_html($cookie_position, $content, $style);
    }

    static function cookie_helper($params, $template) {
        $return = new stdClass();
        $cooke_enabled = $params->get('cookie_enable', 0);
        if ($cooke_enabled == 0) {
            return false;
        } elseif (isset($_COOKIE['cookie-consentiti-' . $template])) {
            return false;
        }

        $input = JFactory::getApplication()->input;
        $accepted = $input->getSting("accettocookie", "false");
        if ($accepted === "accettocookie") {
            $domain = ($_SERVER['HTTP_HOST'] != 'localhost') ? $_SERVER['HTTP_HOST'] : false;
            setcookie('cookie-consentiti-' . $template, "accept", time() + (10 * 365 * 24 * 60 * 60), '/', $domain, false);
            return false;
        }
        return $params->get('cookie_position', "bottom");
    }

    static function cookie_html($cookieposition, $content, $style) {
        //cookie-black
        //cookie-black-trasparent
        //cookie-white
        //cookie-blue
        //cookie-green
        //cookie-red
        //cookie-gray
        ?>
        <div class="row-fluid cookie-block <?php echo $cookieposition . " " . $style; ?>" >

            <div class="container">
                <div class="col-lg-12 col-md-12 col-sm-12">
                    <h4><?php echo $content->cookie_title; ?></h4>
                    <span>
                        <?php echo str_replace("|new|", "</br>", $content->cookie_desc); ?></br>

                    </span>
                </div> </div>
            <div class="container">
                <div class="col-lg-12 col-md-12 col-sm-12">
                    <div class="btncooki">

                        <a class="cookieaction button-cookie-accept" href="#"><?php echo $content->cookie_accept; ?></a>
                        <?php if ($content->cookie_link !== false && $content->cookie_more !== false) { ?>
                            <a class="readmore" href="<?php echo $content->cookie_link; ?>" ><?php echo $content->cookie_more; ?></a>
                        <?php } ?>
                    </div>

                </div>
            </div>


            <div class="clearfix"></div>
        </div>
        <?php
    }

    /* End Cookie functions
     * 
     * 
     * 
     * 
     * 
     * 
     */


    /* Timer
     * 
     * 
     * 
     * 
     * 
     * 
     */

    static protected function seconds_to_times($seconds) {


        $times = array();
        $count_zero = false;
        $periods = array(60, 3600, 86400, 604800, 31536000);
        for ($i = 4; $i >= 0; $i--) {
            $period = floor($seconds / $periods[$i]);
            if (($period > 0) || ($period == 0 && $count_zero)) {
                $times[$i + 1] = $period;
                $seconds -= $period * $periods[$i];

                $count_zero = true;
            }
        }

        $times[0] = $seconds;
        return $times;
    }

    static protected function prepare_counter_html($int, $type) {
        $return = array();
        //fix max allowed years
        if ($type == "years" && $int > 99) {
            $int = 99;
        }
        $allow_one = array("years", "days");
        if (strlen($int) == 1 && !in_array($type, $allow_one)) {
            $num = 0 . $int;
        } else {
            $num = $int;
        }
        $return = '<div class="time-block ' . $type . '" data-time="' . $int . '">';
        
        $return .= '<div class="time-boxes">';
        foreach (str_split($num) as $index => $value) {
            //if year or day and one number, addiing hidding div
            if (strlen($num) == 1) {
                $return .= '<div class="' . $type . '-0 ' . $type . '-period time-box box-0" style="display:none;">0</div>';
                $index++;
            }
            $return .= '<div class="' . $type . '-' . $index . ' box-'.$index.' time-box">' . $value . '</div>';
        }
        $return .= '<div class="clearfix"></div></div>';
        $return .= '<div class="period-name">' . JText::_("COUNTER_" . strtoupper($type)) . '</div>';
         $return .= '</div>';
        return $return;
    }

    static protected function preapare_counter_out($array) {
        $define = array(5 => "years", 4 => "weeks", 3 => "days", 2 => "hours", 1 => "min", 0 => "sec");
        $return = '';

        foreach ($define as $key => $value) {
            //$default = 0;
            if (isset($array[$key])) {
                $return .= self::prepare_counter_html((int) $array[$key], $value);
                // $default = (int) $array[$key];
            }
        }
        return $return;
    }

    static function inizializze_counter($params) {
        $result = '';
      
        $get_online = $params->get("offline_online", false);
        if ($get_online !== false) {

            $get_curdate = JFactory::getDate()->format('Y-m-d H:i:s');
            $seconds = strtotime($get_online) - strtotime($get_curdate);

            if ($seconds > 0) {
             // self::counter_load_language($params);
                $result .= '<div id="ml-counter" class="first-counter" data-seconds="' . $seconds . '">';
                $get_result = self::seconds_to_times($seconds);
                $result .= self::preapare_counter_out($get_result);
                $result .= '</div>';
            }
        }
        return $result;
    }

    function offline_text($params,$app){
       
        $lang = JFactory::getLanguage();
        $lang_tag = $lang->getTag();
        $deflang = $params->get('offlinepage_deflang', "en-GB");
        $lang_text = $params->get("offlinetext_".$lang_tag,"");
        $default_text = $params->get("offlinetext_".$deflang,"");
        if(!empty($lang_text)){
            return '<div class="offline-content">'.$lang_text.'</div>';
        }
        else if(!empty($default_text)){
            return '<div class="offline-content">'.$default_text.'</div>';
        }
        else if ($app->get('display_offline_message', 1) == 1 && str_replace(' ', '', $app->get('offline_message')) != ''){
            return '<div class="offline-content">'.$app->get('offline_message').'</div>';
        }
       elseif ($app->get('display_offline_message', 1) == 2){
           return '<div class="offline-content">'.JText::_('JOFFLINE_MESSAGE').'</div>';
       }
        return '';
    }
  
    function offline_copyright($params){
         if ($params->get('brand') == 0) {
                return '<div class="biged"><a href="' . $params->get('linkcopy', "https://marlev.it/") . '" target="_blank">' . $params->get('copy', "Designed by Marlev.it") . '</a></div>';
            }
    }

}
