<?php

// This element is a work in progress and is currently fairly identical to the normal example element, aside from
// nesting being enabled and the render function outputting $content in a 4.0 compatible manner.

class RmFeaturesElement extends OxyEl {

    function init() {
        // Do some initial things here.
        $this->enableNesting();
    }

    function afterInit() {
        // Do things after init, like remove apply params button and remove the add button.
        $this->removeApplyParamsButton();
        // $this->removeAddButton();
    }

    function name() {
        return 'RM Features';
    }
    
    function slug() {
        return "rm-features-element";
    }

    function icon() {
        // Path to icon here.
    }

    function button_place() {
        return "other";
    }

    function button_priority() {
        return '';
    }


    function rm_item_has_class($itemV, $classes){
        if(! isset($itemV["options"]) || !isset($itemV["options"]["classes"])  ){
        } 
    }

    function nested_values($array, $path="", $list_of_classes=[], $output_final=[],$level=0){
        $output = array();

        $list_of_classes_keys = array_keys($list_of_classes);
        $list_of_classes_keys = ($list_of_classes_keys) ? : [];

        if(!$array || !is_array($array)){
            return $output_final;
        }
        
        foreach($array as $keyA => $valuex) {
            if( 
                $keyA &&
                $keyA == "classes" && 
                is_array($valuex) && 
                array_intersect(
                    $list_of_classes_keys, 
                    $valuex
                ) 
            ) {
                $intersect = array_intersect($list_of_classes_keys, $valuex);
                $intersect = reset($intersect);

                $path = ["path"=>str_replace("options/", "", $path)];
                
                $output_final[$intersect] = array_merge($list_of_classes[$intersect], $path);
               
            }
            elseif(is_array($valuex)) {
                $output_final = array_merge($output_final, $this->nested_values($valuex, (!empty($path)) ? $path.$keyA."/" : $keyA."/", $list_of_classes, $output_final));
            }

        }
        return $output_final;
    }

    function un_nested_values ($data, $path, $value="", $delimiter = '/'){
        if (!is_array($path)) {
            $pathParts = explode($delimiter, $path);
        }

        $temp = &$data;
        foreach($pathParts as $key) {
            $temp = &$temp[$key];
        }
        $temp = $value;
        unset($temp);

        return $data;
    }

    function render($options, $defaults, $content) {
        // Output here.

        // Data
        $features_list_key  = (isset($options['features_list_key']) && $options['features_list_key']) ? $options['features_list_key'] : 'features_list';
        $target_page_id     = (isset($options['target_page_id']) && $options['target_page_id']) ? $options['target_page_id'] : get_the_id();
        $icon_fontname     = (isset($options['icon_fontname']) && $options['icon_fontname']) ? $options['icon_fontname'] : "rmfe";
        $icon_font_group     = (isset($options['icon_font_group']) && $options['icon_font_group']) ? $options['icon_font_group'] : "";

        $features_type = ($options['features_type']) ? : 'icons';
        $features_list = get_post_meta($target_page_id, $features_list_key, true );

        $img_src_dir = $s_file_name = $features_titles_file = "";


        // Images & json
        $dir_upload 	    = wp_upload_dir();
        $file_dir_upload 	= $dir_upload["basedir"] . '/ds1-elements/features/';
        
        if($features_type == "colorful_icons") {
            $s_file_name        = 'features/icons/%s.png';
        }
        else {
            $s_file_name        = 'features/images/%s.jpg';
        }


        if($features_type == "icons") {
            //echo $this->rm_svg_icons($features_list);
        }
        
        if( file_exists($file_dir_upload ) ){
            //images url
            $img_src_dir = $dir_upload["baseurl"] . "/" . $s_file_name;

            //features titles file
            $features_titles_file = $file_dir_upload . get_locale() . ".json";
        }
        else {
            //images url
            $img_src_dir = plugin_dir_url( __FILE__ ).  $s_file_name;

            //features titles file
            $file_name = (file_exists(plugin_dir_path( __FILE__ ) . '/features/'. get_locale() . ".json")) ? get_locale() . ".json" : "en_US.json";
            $features_titles_file = plugin_dir_path( __FILE__ ) . '/features/'. $file_name;
        }

        //Prepare titles "Names" of features from json file
        $features_titles = file_get_contents($features_titles_file);
        if($features_titles){
            $features_titles = json_decode($features_titles, true);
        }
        
        //Prepare items 
        $map_of_indexs = [
            "item-title"    => ["type"=>"ct_content/localization"],
            "item-image"    => ["type"=>($features_type == "icons") ? "original/icon-id" : "original/src"],
        ];

        if($features_type == "none") {
            unset( $map_of_indexs ["item-image"] );
        }
        $map_of_indexs = $this->nested_values($content, "", $map_of_indexs);
       
        // Loop on selected items
        if($features_list && $content) {
           
            foreach ($features_list as $itemK => $itemV) {
                $content_clone = $content;

                foreach($map_of_indexs as $findThisItem) {
                    if(!isset($findThisItem["path"]) ){
                       continue;
                    }
                    elseif(! $itemV ) {
                        $content_clone = $this->un_nested_values($content_clone, $findThisItem["path"] . "options/classes", ['hide']);
                    }
                    elseif( $findThisItem["type"] == "ct_content") {
                        $content_clone = $this->un_nested_values($content_clone, $findThisItem["path"] . "options/" . $findThisItem["type"], $itemV);
                    }
                    elseif( $findThisItem["type"] == "ct_content/localization") {
                        $itemV_localization = isset($features_titles[$itemV]) ? $features_titles[$itemV] : $itemV;
                        $content_clone = $this->un_nested_values($content_clone, $findThisItem["path"] . "options/ct_content", $itemV_localization);
                    }
                    elseif( $findThisItem["type"] == "original/src") {
                        $content_clone = $this->un_nested_values($content_clone, $findThisItem["path"] . "options/" . $findThisItem["type"], sprintf($img_src_dir, $itemV) );
                    }
                    
                    elseif( $findThisItem["type"] == "original/icon-id") {
                        $content_clone = $this->un_nested_values($content_clone, $findThisItem["path"] . "options/" . $findThisItem["type"], $icon_fontname. "icofe-" . $itemV . $icon_font_group );
                    }
                }
                
                foreach($content_clone as $kkk=>$vvv) {
                    $content_clone[$kkk]['options']['selector'] = $content_clone[$kkk]['options']['selector'] . '-' . $itemK;
                }

                // This conditional allows backward compatibility with versions prior to Oxygen 4.0
                if( function_exists('do_oxygen_elements') ){
                    echo do_oxygen_elements($content_clone);
                }
                else {
                    echo do_shortcode($content_clone);
                }
            }
        }
    }

    function controls() {
        $controlSection =$this;
        $controlSection->addOptionControl(
			array(
                "type" => 'dropdown', // types: textfield, dropdown, checkbox, buttons-list, measurebox, slider-measurebox, colorpicker, icon_finder, mediaurl
				"name" => 'Features type',
				"slug" => 'features_type'
            )
        )->setValue(array( 
            "icons"     => "icons",
            "colorful_icons"     => "Colorful icons", 
            "images"    => "Images" ,
            "no_image"  => 'without image or icon',
        ));

        $controlSection->addOptionControl(
			array(
                "type"      => 'textfield',
                "default"   => 'features_list',
				"name"      => 'Meta key - like ACF Name',
				"slug"      => 'features_list_key'
            )
        );
        $controlSection->addOptionControl(
			array(
                "type"      => 'textfield',
				"name"      => 'Target page id',
				"slug"      => 'target_page_id'
            )
        )->setParam("description", __("Leave blank to fetch from the current page - اتركها فارغة للجلب من الصفحة الحالية"));
        
        $controlSection->addOptionControl(
			array(
                "type"      => 'textfield',
				"name"      => 'Icon Font name',
				"slug"      => 'icon_fontname',
                "default"   => 'rmfe',
                "condition" => 'features_type=icons',
            )
        );

        
        $controlSection->addOptionControl(
			array(
                "type"      => 'textfield',
				"name"      => 'Icon Font group',
				"slug"      => 'icon_font_group',
                "condition" => 'features_type=icons',
            )
        );
    }

    function defaultCSS() {

        //return file_get_contents(__DIR__.'/'.basename(__FILE__, '.php').'.css');
 
    }
    
}

new RmFeaturesElement();
