<?php
function magictoolbox_WordPress_MagicSlideshow_set_global_variable() {
    global $magictoolbox_MagicSlideshow_page_has_shortcode;
    $magictoolbox_MagicSlideshow_page_has_shortcode = true;
}
function magictoolbox_WordPress_MagicSlideshow_widget_shortcode($widget_content) {
    $widget_content = preg_replace_callback('/\[\s*magicslideshow\s+name\s*=\s*"([\w]+)"\s*\]/is', function($slideshow) {
        return magicslideshow_shortcode(array('name' => $slideshow[1]));
    }, $widget_content);

    return $widget_content;
}

function magictoolbox_WordPress_MagicSlideshow_shortcode($atts) {
    magictoolbox_WordPress_MagicSlideshow_set_global_variable();

    if (preg_match('/^[0-9]/', trim($atts['id']))) {
        $ss = magictoolbox_WordPress_MagicSlideshow_get_saved_data(trim($atts['id']), false);
    } else {
        $ss = magictoolbox_WordPress_MagicSlideshow_get_saved_data(trim($atts['id']), true);
    }

    if (0 == count($ss)) {
        return '';
    } else {
        $html = $ss[0]->html;

        if (magictoolbox_WordPress_MagicSlideshow_is_simple($html)) {
            $html = str_replace("simple,", "", $html);
            $html = json_decode($html);

            $allToolOptions = magictoolbox_WordPress_MagicSlideshow_parse_saved_options($ss[0]->saved_data);

            $result = '';
            $result .= '<div class="MagicSlideshow"';
            $result .= ' data-options="'.$allToolOptions['options'].'"';
            $result .= ' data-mobile-options="'.$allToolOptions['mobileOptions'].'"';
            $result .= '>';
            
            $url = site_url();
            $shop_dir = ABSPATH;
            $image_dir = 'wp-content/uploads/';
            if (isset($GLOBALS['magictoolbox']['WordPressMagicSlideshow'])) {
                $plugin = $GLOBALS['magictoolbox']['WordPressMagicSlideshow'];
            }
            
            //require_once(preg_replace('/\\'.DIRECTORY_SEPARATOR.'magicslideshow\/constructor/is', '/magicslideshow', dirname(__FILE__)) . DIRECTORY_SEPARATOR.'core'.DIRECTORY_SEPARATOR.'magictoolbox.imagehelper.class.php'); 

            require_once(dirname(__FILE__) . '/../core/magictoolbox.imagehelper.class.php');

            $imagehelper = new MagicToolboxImageHelperClass($shop_dir, $image_dir.'magictoolbox_cache', $plugin->params, null, $url);

            foreach ($html as $slide) {
                if ($slide->type == 'image') {
                
                    $meta = wp_get_attachment_metadata($slide->id);
                    $url = '/'.$image_dir.$meta['file'];
                    $result_imgs = array();
                    $img = array();
                    foreach ($meta['sizes'] as $key => $size) {
                        if (false && is_array($size)) {
                            $tmp = $imagehelper->create($url, array($size['width'],$size['height']));
                            //$tmp2x = $imagehelper->create($url, array($size['width']*2,$size['height']*2));
                            $tmp2x = $imagehelper->create($url, array((int)$size['width']*2,(int)$size['height']*2));
                        } else {
                            $tmp = wp_get_attachment_image_url($slide->id,$key);
                        }
                        $img[$key] = $tmp;
                        if (!empty($tmp2x)) {
                            $img[$key.'2x'] = $tmp2x;
                        } else {
                            $img[$key.'2x'] = '';                            
                        }
                        $result_imgs['sizes'] = $img;
                    }
                    
                    if (empty($result_imgs['sizes']['large'])) {
                        $result_imgs['sizes']['large'] = wp_get_attachment_image_url($slide->id,'full');
                        $result_imgs['sizes']['large2x'] = '';
                    }

                
                    $imageData = wp_prepare_attachment_for_js($slide->id);

                    $img = '<img';
                    //$img .= ' src="'.$imageData['url'].'"';
                    $img .= ' src="'.$result_imgs['sizes']['large'].'"';
                    
                    $img .= ' srcset="'.$result_imgs['sizes']['large2x'].'"';

                    if (trim($imageData['alt']) !== '') {
                        $img .= ' alt="'.$imageData['alt'].'"';
                    }

                    if (filter_var($slide->title->use, FILTER_VALIDATE_BOOLEAN) && trim($slide->title->value) != '') {
                        $img .= ' title="'.$slide->title->value.'"';
                    }

                    if (filter_var($slide->caption->use, FILTER_VALIDATE_BOOLEAN) && trim($slide->caption->value) != '') {
                        $img .= ' data-caption="'.$slide->caption->value.'"';
                    }

                    //if (isset($imageData['sizes']) && isset($imageData['sizes']['thumbnail']) && isset($imageData['sizes']['thumbnail']['url'])) {
                    if (isset($result_imgs['sizes']) && isset($result_imgs['sizes']['thumbnail'])) {
                        $img .= ' data-thumb-image="'.$result_imgs['sizes']['thumbnail'].'"';
                        //$img .= ' data-thumb-image="'.$imageData['sizes']['thumbnail']['url'].'"';
                    }

                    $img .= ' />';

                    if (filter_var($slide->link->use, FILTER_VALIDATE_BOOLEAN) && trim($slide->link->url) != '') {
                        $result .= '<a';
                        $result .= ' href="'.$slide->link->url.'"';

                        if ($slide->link->newWindow) {
                            $result .= ' target="_blank"';
                        }

                        $result .= '>';
                        $result .= $img;
                        $result .= '</a>';
                    } else {
                        $result .= $img;
                    }
                } else {
                    // TODO video slide
                }
            }

            $result .= '</div>';

            return $result;
        } else {
            $html = preg_replace_callback('/<\!\[magicslideshow\[([0-9]+)\]\]>/', function($m) {
                //return wp_get_attachment_url($m[1]);
                return magictoolbox_WordPress_MagicSlideshow_add_srcset($m[1]);
            }, $html);
            return stripcslashes($html);
        } 
    }
}

function magictoolbox_WordPress_MagicSlideshow_add_srcset ($id) {

    $url = site_url();
    $shop_dir = ABSPATH;
    $image_dir = 'wp-content/uploads/';
    if (isset($GLOBALS['magictoolbox']['WordPressMagicSlideshow'])) {
        $plugin = $GLOBALS['magictoolbox']['WordPressMagicSlideshow'];
    }
    if (!isset($GLOBALS['imagehelper'])) {
        //require_once(preg_replace('/\\'.DIRECTORY_SEPARATOR.'magicslideshow\/constructor/is', '/magicslideshow', dirname(__FILE__)) . DIRECTORY_SEPARATOR.'core'.DIRECTORY_SEPARATOR.'magictoolbox.imagehelper.class.php'); 

        require_once(dirname(__FILE__) . '/../core/magictoolbox.imagehelper.class.php');

        $GLOBALS['imagehelper'] = new MagicToolboxImageHelperClass($shop_dir, $image_dir.'magictoolbox_cache', $plugin->params, null, $url);
    }
    $imagehelper = $GLOBALS['imagehelper'];
    
    $meta = wp_get_attachment_metadata($id);
    $url = '/'.$image_dir.$meta['file'];
    
    $result_imgs = array();
    $img = array();
    
    foreach ($meta['sizes'] as $key => $size) {
        if (false && is_array($size)) {
            $tmp = $imagehelper->create($url, array($size['width'],$size['height']));
            //$tmp2x = $imagehelper->create($url, array($size['width']*2,$size['height']*2));
            $tmp2x = $imagehelper->create($url, array((int)$size['width']*2,(int)$size['height']*2));
        } else {
            $tmp = wp_get_attachment_image_url($id,$key);
            
        }
        $img[$key] = $tmp;
        if (!empty($tmp2x)) {
            $img[$key.'2x'] = $tmp2x;
        } else {
            $img[$key.'2x'] = '';            
        }
        
        $result_imgs['sizes'] = $img;
    }
    
    if (empty($result_imgs['sizes']['large'])) {
        $result_imgs = [
            'sizes' => [
                'large' => wp_get_attachment_image_url($id,'full'),
                'large2x' => ''
            ]
        ];
    }
   
    return $result_imgs['sizes']['large'].'" srcset="'.$result_imgs['sizes']['large2x'].'"';
    
}


// "key: value; key: value; ..."
function magictoolbox_WordPress_MagicSlideshow_parse_option_from_string($options) {
    $opt = array();

    $options = explode(";", $options);
    array_pop($options);

    foreach ($options as $value) {
        $value = trim($value);
        if (!empty($value)) {
            $value = explode(":", $value);
            // $opt[$value[0]] = trim($value[1]);
            $k = array_shift($value);
            $v = join(":",$value);
            $opt[$k] = trim($v);
        }
    }
    return $opt;
}

function magictoolbox_WordPress_MagicSlideshow_parse_saved_options($opt) {
    $result = array();

    if ($opt) {
        $opt = explode('|', $opt);

        foreach ($opt as $value) {
            $typeOptions = explode('=', $value);
            $result[$typeOptions[0]] = empty($typeOptions[1]) ? null : $typeOptions[1];
        }
    }

    return $result;
}

function magictoolbox_WordPress_MagicSlideshow_is_simple($value) {
    return (bool)preg_match('/^simple/', $value);
}

function magictoolbox_WordPress_MagicSlideshow_get_tiny_mce_data() {
    if(!(is_array($_POST) && defined('DOING_AJAX') && DOING_AJAX)){
        return;
    }

    $nonce = $_POST['nonce'];
    $result = '{"error": "error"}';

    if ( !wp_verify_nonce( $nonce, 'magic-everywhere' ) ) {
        $result = '{"error": "verification failed"}';
    } else {
        $table_data = magictoolbox_WordPress_MagicSlideshow_get_saved_data();
        if ($table_data && count($table_data) > 0) {
            $result = '[';
            foreach($table_data as $value) {
                $result .= '{';
                $result .= '"id":"'.$value->id.'",';
                $result .= '"name":"'.$value->name.'"';
                $result .= '},';
            }
            $result = preg_replace('/,$/is', '', $result);
            $result .= ']';
        } else {
            $result = '{"error": "empty"}';
        }
    }
    echo $result;
    wp_die();
}

function magictoolbox_WordPress_MagicSlideshow_add_my_tc_button() {
    global $typenow;
    // check user permissions
    if ( !current_user_can('edit_posts') && !current_user_can('edit_pages') ) {
        return;
    }
    // verify the post type
    if( ! in_array( $typenow, array( 'post', 'page' ) ) ) {
        return;
    }

    // check if WYSIWYG is enabled
    if ( get_user_option('rich_editing') == 'true') {
        add_filter("mce_external_plugins", "magictoolbox_WordPress_MagicSlideshow_add_tinymce_plugin");
        add_filter('mce_buttons', 'magictoolbox_WordPress_MagicSlideshow_register_tinymce_button');
        echo '<script>'.
            'var magictoolbox_WordPress_MagicSlideshow_admin_modal_object = {'.
                'ajax: "'.(get_site_url().'/wp-admin/admin-ajax.php').'",'.
                'nonce: "'.wp_create_nonce('magic-everywhere'). '"'.
            '};'.
        '</script>';
    }
}

function magictoolbox_WordPress_MagicSlideshow_add_tinymce_plugin($plugin_array) {
    $plugin_array["magictoolbox_WordPress_MagicSlideshow_shortcode"] = plugins_url( 'magicslideshow_tiny_mce_button.js', __FILE__ );
    return $plugin_array;
}

function magictoolbox_WordPress_MagicSlideshow_register_tinymce_button($buttons) {
   array_push($buttons, "magictoolbox_WordPress_MagicSlideshow_shortcode");
   return $buttons;
}

function magictoolbox_WordPress_MagicSlideshow_button_css() {
    $screen = get_current_screen();

    if ( $screen->id == 'page' || $screen->id == 'post' || $screen->id == 'product' || $screen->id == 'wpsc-product' || $screen->id == 'tcp_product') {
        wp_register_style('magictoolbox_WordPress_MagicSlideshow_tinymce_button_css', plugin_dir_url( __FILE__ ).('magicslideshow_tiny_mce_button.css'), array());
        wp_enqueue_style('magictoolbox_WordPress_MagicSlideshow_tinymce_button_css');
    }
}
?>
