<?php
namespace Marlev\Component\Tmarlevv2\Administrator\Helper;
/**
 *
 * @extension       T-Marlev
 * @author          Lev Milicenco<support@marlev.it>
 * @link            http://www.marlev.it
 * @copyright       Copyright 2022 marlev.it All Rights Reserved

 * @license         http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
 */

use Joomla\CMS\Factory;
use Joomla\Registry\Registry;
//for_use
defined('_JEXEC') or die;


class posconfig_transfer
{
    public $id;
    public $layout;
    protected $export_type;
    protected $import_layout;
    protected $devices;
    protected $default_keys;

    function __construct($getter, $layout)
    {
        $this->layout = $layout;
        $this->id = (int)$getter->import_to;
        $this->export_type = (string)$getter->export_type;
        $this->posname = $getter->posname;
        $this->parent = $getter->parent;
        $this->position_onblock = $getter->position_onblock;
        $this->position_on_import_block = "nonesiste"; //"true" se nella stessa posizione, N se la posizione diversa, nonesiste - non esiste
        $this->cols = $getter->cols;
        $this->defcollayout = $getter->defcollayout;
        $this->tabcollayout = $getter->tabcollayout;
        $this->mobcollayout = $getter->mobcollayout;

        $this->import_layout = $this->get_exists_layout();


        $this->devices = ["pc", "tablet", "mobile"];
        $this->default_keys = ["", "order", "hide", "offset", "addclear"];

    }

    protected function write_css()
    {
        foreach ($this->devices as $key => $device) {
            $this->import_layout['css'][$device][$this->posname] = $this->layout['css'][$device][$this->posname];
        }
    }

    protected function define_import_position_on_block()
    {
        $get_import_poss = $this->import_layout['positions'][$this->parent];
        $import_positions = explode(",", $get_import_poss);
        foreach ($import_positions as $import_position => $posname) {
            if ($posname == $this->posname && $import_position == $this->position_onblock) {
                $this->position_on_import_block = "true";
                break;
            } else if ($posname == $this->posname) {
                $this->position_on_import_block = $import_position;
                break;
            }
        }
        //se la posizione non esiste, e la posizione e' numerica, cerco di capire su che posizione del blocco mettere la nuova posizione
        if ($this->position_on_import_block == "nonesiste") {
            $explode = explode("-", $this->posname);
            $p_end = end($explode);
            if ($p_end > 0) {
                foreach ($import_positions as $import_position => $posname) {
                    $explode_cur = explode("-", $posname);
                    if (end($explode) < $p_end && !isset($import_positions[$import_position + 1])) {
                        $this->new_import_position = $import_position;
                    } else if (isset($import_positions[$import_position + 1])) {
                        $explode_next = explode("-", $import_positions[$import_position + 1]);
                        if (end($explode_next) > $p_end) {
                            $this->new_import_position = $import_position;
                        }
                    }
                }
            }
        }

    }

    protected function assign_similar($arraykey, $import, $export, $bypos)
    {
        $maps = array();
        foreach ($import as $key => $value) {
            if ($key == $bypos) {
                $maps[] = $export[$this->position_onblock];
            }
            $maps[] = $value;
        }
        $this->import_layout[$arraykey][$this->parent] = implode(",", $maps);
    }

    protected function assign_value_convirgola($arraykey)
    {
        $get_import = $this->import_layout[$arraykey][$this->parent];
        $import = explode(",", $get_import);
        $get_export = $this->layout[$arraykey][$this->parent];
        $export = explode(",", $get_export);

        if ($this->position_on_import_block == "true") {
            $import[$this->position_onblock] = $export[$this->position_onblock];
            $this->import_layout[$arraykey][$this->parent] = implode(",", $import);
            // return true;
        } else if ($this->position_on_import_block != "nonesiste") {
            $import[$this->position_on_import_block] = $export[$this->position_onblock];
            $this->import_layout[$arraykey][$this->parent] = implode(",", $import);
            //return true;
        } else {
            //per le posizioni numerati alla fine
            if (isset($this->new_import_position)) {
                $this->assign_similar($arraykey, $import, $export, $this->new_import_position);
            } //se nel blocco di import le posizioni son in meni
            else if ($this->position_onblock + 1 > count($import)) {
                $import[] = $export[$this->position_onblock];
                $this->import_layout[$arraykey][$this->parent] = implode(",", $import);
            } else {
                //in altri casi mette nella posizione di export
                $this->assign_similar($arraykey, $import, $export, $this->position_onblock);

            }
        }


    }

    protected
    function position_assigner($position, $prefix = "")
    {
        foreach ($this->devices as $key => $device) {
            $device = $prefix . $device;
            if(isset($this->layout[$device][$position])) {
                $this->import_layout[$device][$position] = $this->layout[$device][$position];
            }
        }
    }

    public function assigner()
    {
        $this->write_css();
        if ($this->export_type == "section") {
            $this->import_layout['width'][$this->posname] = $this->layout['width'][$this->posname];
        } else {
            $this->define_import_position_on_block();
            //positions key
            $this->assign_value_convirgola("positions");
            $this->import_layout["positions"][$this->posname] = $this->posname;
            foreach (["mobcollayout", "tabcollayout", "defcollayout"] as $def => $col) {
                $this->assign_value_convirgola($col);
            }
            foreach ($this->default_keys as $pre => $prefix) {
                $this->position_assigner($this->posname, $prefix);
            }
        }
        $registry = new Registry;
        $registry->loadArray($this->import_layout);
        $params = (string)$registry;
        $update = new \stdClass();
        $update->layout = $params;
        $update->tid = $this->id;
        $result = Factory::getDbo()->updateObject('#__tmarlevv2_layout', $update, 'tid');
        if($result){
            echo "<div id='export-done' data-result='done'></div>";
        }
        else {
            echo "<div id='export-done' data-result='fail'></div>";
        }
        return true;
    }


    protected
    function get_exists_layout()
    {
        $db = Factory::getDbo();
        $query = $db->getQuery(true);
        $query->select('layout,id');
        $query->from('#__tmarlevv2_layout');
        $query->where('tid=' . $db->Quote($this->id));
        $db->setQuery($query);
        $get_layout = $db->loadObjectList();
        $getlayout = json_decode($get_layout[0]->layout);
        return $this->array_map_recursive($getlayout);
    }

    protected
    function array_map_recursive($input)
    {
        $output = array();
        $input = (array)$input;
        foreach ($input as $key => $data) {
            if (is_object($data)) {
                $data = (array)$data;
            }
            if (is_array($data)) {
                $output[$key] = $this->array_map_recursive($data);
            } else {
                $output[$key] = $data;
            }
        }
        return $output;
    }
}