<?php

function magictoolbox_WordPress_MagicSlideshow_create_teble() {
    global $wpdb;

    $table_name = $wpdb->prefix . 'magicslideshow_store';
    if($wpdb->get_var("SHOW TABLES LIKE '$table_name'") != $table_name) {
        $sql = "CREATE TABLE $table_name (
          id int unsigned NOT NULL auto_increment,
          name varchar(20) DEFAULT NULL,
          html mediumtext DEFAULT NULL,
          saved_data longtext DEFAULT NULL,
          UNIQUE KEY id (id));";

        require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
        dbDelta( $sql );
        magictoolbox_WordPress_MagicSlideshow_create_example_chortcode();
    }
}

function magictoolbox_WordPress_MagicSlideshow_replace_shortcode($arr, $on, $nn, $r) {
    if ($arr && count($arr) > 0) {
        foreach($arr as $value) {
            if (!$r) {
                $value->post_content = preg_replace('/(\[\s*magicslideshow\s*name\s*=\s*")\s*'.$on.'\s*("\s*\])/is', '$1'.$nn.'$2', $value->post_content);
            } else {
                $value->post_content = preg_replace('/\[\s*magicslideshow\s*name\s*=\s*"\s*'.$on.'\s*"\s*\]/is', '', $value->post_content);
            }
            wp_update_post(array('ID' => $value->ID, 'post_content' => $value->post_content));
        }
    }
}

function magictoolbox_WordPress_MagicSlideshow_edit_posts_and_pages($oldname = 'empty', $newname = 'empty', $remove_short_code = false) {
    $args = array( 'numberposts' => -1 );
    magictoolbox_WordPress_MagicSlideshow_replace_shortcode(get_posts( $args ), $oldname, $newname, $remove_short_code);

    $args = array( 'number' => '' );
    magictoolbox_WordPress_MagicSlideshow_replace_shortcode(get_pages( $args ), $oldname, $newname, $remove_short_code);
}

function magictoolbox_WordPress_MagicSlideshow_remove_teble() {
    global $wpdb;
    $table_name = $wpdb->prefix . 'magicslideshow_store';

    if($wpdb->get_var("SHOW TABLES LIKE '$table_name'") == $table_name) {
        $wpdb->query("DROP TABLE IF EXISTS ".$table_name);
    }
}

function magictoolbox_WordPress_MagicSlideshow_save_data() {
    global $wpdb;

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

    $nonce = $_POST['nonce'];
    if ($_POST['id'] == 'null') {
        $id = $_POST['id'];
    } else {
        $id = (int)$_POST['id'];
    }

    $result = 'ok';

    if ( !wp_verify_nonce( $nonce, 'magic-everywhere' ) ) {
        $result = 'verification failed';
    } else {
        if (empty($_POST['html'])) {
            $images = $_POST['images'];
            $options = $_POST['options'];
            $mobileOptions = $_POST['mobileOptions'];
            $additionalOptions = $_POST['additionalOptions'];

            $images = json_encode($images);

            $data = 'options='.$options.'|'.'mobileOptions='.$mobileOptions.'|'.'additionalOptions='.$additionalOptions;
            $html = 'simple,'.$images;
            $name = null;

            if ($_POST['shortcode'] !== null) {
                $name = $_POST['shortcode'];

                $shortcodes = magictoolbox_WordPress_MagicSlideshow_get_saved_data();

                foreach ($shortcodes as $slideshow) {
                    if ($slideshow->name == $name && $slideshow->id != $id) {
                        $result = "notunique";
                        break;
                    }
                }
            }

            if ($result == 'ok') {
                if ($id == 'null' || empty($id)) {
                    $id = magictoolbox_WordPress_MagicSlideshow_add_data($html, $data, $name);
                } else {
                    $table_name = $wpdb->prefix . 'magicslideshow_store';

                    if (empty($name)) { $name = 'magicslideshow-'.$id; }

                    $res = $wpdb->update($table_name, array('name' => $name, 'html' => $html, 'saved_data' => $data), array('id' => $id), array( '%s', '%s', '%s' ), array( '%d' ));

                    if (!$res) {
                        $result = 'error';
                    }
                }
            }

            $url = 'url';
        } else {
            $html = $_POST['html'];
            $data = $_POST['data'];

            if ($id == 'null' || empty($id)) {
                $id = magictoolbox_WordPress_MagicSlideshow_add_data($html, $data, null);
            } else {
                $table_name = $wpdb->prefix . 'magicslideshow_store';
                $res = $wpdb->update($table_name, array('html' => $html, 'saved_data' => $data), array('id' => $id), array( '%s', '%s' ), array( '%d' ));

                if (!$res) {
                    $result = 'error';
                }
            }

            preg_match('/<\!\[magicslideshow\[([0-9]+)\]\]>/', $html, $url);
            $url = wp_get_attachment_url($url[1]);
        }    
    }

    ob_end_clean();
    echo "{\"id\":".$id.", \"url\":\"".$url."\", \"error\":\"".$result."\"}";
    wp_die();
}

function magictoolbox_WordPress_MagicSlideshow_add_data($html, $data, $new_name) {
    global $wpdb;
    $table_name = $wpdb->prefix . 'magicslideshow_store';

    $wpdb->insert($table_name, array('html' => $html, 'saved_data' => $data));

    $id = $wpdb->insert_id;
    $wpdb->update($table_name, array('name' => $new_name ? $new_name : 'magicslideshow-'.$id), array('id' => $id), array( '%s' ), array( '%d' ));

    return $id;
    // wp_die();
}

function magictoolbox_WordPress_MagicSlideshow_load_data() {
    global $wpdb;

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

    $id = (int)$_POST['id'];
    $nonce = $_POST['nonce'];
    $result = 'ok';

    if ( !wp_verify_nonce( $nonce, 'magic-everywhere' ) ) {
        $result = 'verification failed';
    } else {
        $result = magictoolbox_WordPress_MagicSlideshow_get_saved_data($id);
        if (0 == count($result)) {
            $result = 'error';
        } else {
            $result = $result[0]->saved_data;
        }
    }

    ob_end_clean();
    echo $result;
    wp_die();
}

function magictoolbox_WordPress_MagicSlideshow_get_images_by_id() {
    $result = array('error' => null, 'images' => array());

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

    if (!wp_verify_nonce($_POST['nonce'], 'magic-everywhere')) {
        $result['error'] = 'verification failed';
    } else {
        $images = $_POST['images'];
        if ($images && !empty($images) && $images !== 'null') {
            $images = explode(",", $images);

            foreach ($images as $imgid) {
                $imgid = trim($imgid);
                $result['images'][] = wp_prepare_attachment_for_js($imgid);
            }
        }
    }

    ob_end_clean();
    echo wp_json_encode($result);
    wp_die();
}

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

    $imgid = $_POST['imgid'];
    $nonce = $_POST['nonce'];
    $result = 'error';

    if ( !wp_verify_nonce( $nonce, 'magic-everywhere' ) ) {
        $result = 'verification failed';
    } else {
        if ('' != $imgid && 'null' != $imgid) {
            $result = wp_get_attachment_url($imgid);
        }
    }

    ob_end_clean();
    echo $result;
    wp_die();
}

function magictoolbox_WordPress_MagicSlideshow_rename_name() {
    global $wpdb;

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

    $nonce = $_POST['nonce'];
    $id = (int)$_POST['id'];
    $name = $_POST['name'];
    $result = 'ok';

    if ( !wp_verify_nonce( $nonce, 'magic-everywhere' ) ) {
        $result = 'verification failed';
    } else {
        $table_name = $wpdb->prefix . 'magicslideshow_store';
        $oldname = magictoolbox_WordPress_MagicSlideshow_get_saved_data($id);
        $res = $wpdb->update($table_name, array('name' => $name), array('id' => $id), array( '%s' ), array( '%d' ));

        if (!$res) {
            $result = 'error';
        }
    }

    ob_end_clean();
    echo $result;
    wp_die();
}

function magictoolbox_WordPress_MagicSlideshow_delete() {
    global $wpdb;

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

    $nonce = $_POST['nonce'];
    $id = (int)$_POST['id'];
    $result = 'ok';

    if ( !wp_verify_nonce( $nonce, 'magic-everywhere' ) ) {
        $result = 'verification failed';
    } else {
        $table_name = $wpdb->prefix . 'magicslideshow_store';

        $tool = magictoolbox_WordPress_MagicSlideshow_get_saved_data($id);
        $res = $wpdb->delete( $table_name, array( 'id' => $id ) );

        if (!$res) {
            $result = 'error';
        }
    }

    echo $result;
    wp_die();
}

function magictoolbox_WordPress_MagicSlideshow_get_saved_data($value = 'empty', $name = false) {
    global $wpdb;
    $table_name = $wpdb->prefix . 'magicslideshow_store';

    $field = "id";
    if ($name) {
        $field = "name";
        $value = '"'.$value.'"';
    }

    if ('empty' == $value) {
        return $wpdb->get_results("SELECT * FROM ".$table_name);
    } else {
        return $wpdb->get_results("SELECT * FROM ".$table_name." WHERE ".$field." = ".$value);
    }
}

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

    $nonce = $_POST['nonce'];
    $id = (int)$_POST['id'];
    $result = 'error';


    if ( !wp_verify_nonce( $nonce, 'magic-everywhere' ) ) {
        $result = 'verification failed';
    } else {
        $res = magictoolbox_WordPress_MagicSlideshow_get_saved_data($id);
        if ($res) {
            $result = magictoolbox_WordPress_MagicSlideshow_add_data($res[0]->html, $res[0]->saved_data, null);
        }
    }

    ob_end_clean();
    echo $result;
    wp_die();
}

function magictoolbox_WordPress_MagicSlideshow_get_content($file_name) {
    $file_data = file_get_contents(trailingslashit(dirname(__FILE__)).$file_name);
    return $file_data;
}

function magictoolbox_WordPress_MagicSlideshow_add_image_to_media($image_url, $name, $title=null, $description=null) {
    $image_url        = esc_url($image_url);
    $image_name       = $name;
    $upload_dir       = wp_upload_dir();
    $image_data       = file_get_contents($image_url);
    $unique_file_name = wp_unique_filename( $upload_dir['path'], $image_name );
    $filename         = basename( $unique_file_name );

    if( wp_mkdir_p( $upload_dir['path'] ) ) {
        $file = $upload_dir['path'] . '/' . $filename;
    } else {
        $file = $upload_dir['basedir'] . '/' . $filename;
    }

    file_put_contents( $file, $image_data );
    $wp_filetype = wp_check_filetype( $filename, null );

    if (null == $title) {
        $title = sanitize_file_name( $filename );
    }
    if (null == $description) {
        $description = '';
    }
    $attachment = array(
        'guid' => $upload_dir['url'] . '/' . basename( $file ),
        'post_mime_type' => $wp_filetype['type'],
        'post_title'     => $title,
        'post_content'   => $description,
        'post_status'    => 'inherit'
    );

    if( file_exists( ABSPATH . 'wp-admin/includes/image.php') && file_exists( ABSPATH . 'wp-admin/includes/media.php') ) {
        require_once( ABSPATH . 'wp-admin/includes/image.php' );
        require_once( ABSPATH . 'wp-admin/includes/media.php' );

        $attach_id = wp_insert_attachment( $attachment, $file);

        if (!is_wp_error( $attach_id )) {
            $attach_data = wp_generate_attachment_metadata( $attach_id, $file );
            wp_update_attachment_metadata( $attach_id, $attach_data );
            return $attach_id;
        } else {
            return false;
        }
    } else {
        return false;
    }
}

function magictoolbox_WordPress_MagicSlideshow_get_images_from_media_library() {
    $args = array(
        'post_type' => 'attachment',
        'post_mime_type' =>'image',
        'post_status' => 'inherit',
        'posts_per_page' => -1,
        'orderby' => 'rand'
    );
    return new WP_Query( $args );
}

function magictoolbox_WordPress_MagicSlideshow_get_image_name($url) {
    $name = explode("/", $url);
    $name = $name[count($name) - 1];
    return $name;
}

function magictoolbox_WordPress_MagicSlideshow_create_example_chortcode() {
    $ids = array();
    $images = array(
        'models-01.jpg',
        'models-02.jpg',
        'models-03.jpg',
        'models-04.jpg',
        'models-05.jpg',
        'models-06.jpg',
        'models-07.jpg',
        'models-08.jpg',
        'models-09.jpg'
    );
    $imageUrl = 'https://magictoolbox.sirv.com/images/magicslideshow/model-s/';

    $html = magictoolbox_WordPress_MagicSlideshow_get_content('exhtml.txt');
    $data = magictoolbox_WordPress_MagicSlideshow_get_content('exdata.txt');

    if (!$html || !$data) { return; }

    $ml_images = magictoolbox_WordPress_MagicSlideshow_get_images_from_media_library();

    foreach ($images as $value) {
        $tmp = false;
        foreach ($ml_images->posts as $img) {
            if (magictoolbox_WordPress_MagicSlideshow_get_image_name($img->guid) == $value) {
                $tmp = $img->ID;
                break;
            }
        }

        if (false == $tmp) {
            $tmp = magictoolbox_WordPress_MagicSlideshow_add_image_to_media($imageUrl.$value.'?canvas.width=2400', $value, 'MagicSlideshow-example');
        }

        if (false != $tmp) {
            $ids[] = $tmp;
        }
    }

    if (count($ids)) {
        magictoolbox_WordPress_MagicSlideshow_add_example_data($ids, $html, $data);
        magictoolbox_WordPress_MagicSlideshow_add_simple_example_data($ids);
    }
}

function magictoolbox_WordPress_MagicSlideshow_replace_option($pattern, $callback, $data) {
    return preg_replace_callback($pattern, function($m) use ($callback) {
        static $count_of_times = -1;
        static $last_value = "";
        if ($m && $m[1] && $last_value != $m[1]) {
            $last_value = $m[1];
            $count_of_times += 1;
        }
        return $callback($count_of_times);
    }, $data);
};

function magictoolbox_WordPress_MagicSlideshow_add_example_data($ids, $html, $data) {
    $images = $ids;

    // ini_set("pcre.recursion_limit","1000000000");
    ini_set("pcre.backtrack_limit","1000000000");

    $html = preg_replace_callback('/<\!\[magicslideshow\[([0-9]+)\]\]>/im', function($m) use ($images) {
        static $count_of_times = -1;
        $count_of_times += 1;
        return '<![magicslideshow['.$images[$count_of_times].']]>';
    }, $html);

    $data = magictoolbox_WordPress_MagicSlideshow_replace_option('/\\\"imgName\\\"\:\\\"(.*?)\\\"/ims', function($index) use ($images) {
        return '\"imgName\":\"'.magictoolbox_WordPress_MagicSlideshow_get_image_name(wp_get_attachment_url($images[$index])).'\"';
    }, $data);

    $data = magictoolbox_WordPress_MagicSlideshow_replace_option('/\\\"url\\\"\:\\\"([^,]+)\\\"/ims', function($index) use ($images) {
        return '\"url\":\"'.wp_get_attachment_url($images[$index]).'\"';
    }, $data);

    $data = magictoolbox_WordPress_MagicSlideshow_replace_option('/\\\"imgId\\\"\:(\d+)/ims', function($index) use ($images) {
        return '\"imgId\":'.$images[$index];
    }, $data);

    magictoolbox_WordPress_MagicSlideshow_add_data($html, $data, null);
}

function magictoolbox_WordPress_MagicSlideshow_add_simple_example_data($ids) {
    $data = 'options=|mobileOptions=|additionalOptions=firstImage:'.$ids[0].';';

    $html = 'simple,[';

    foreach ($ids as $value) {
        $imageData = wp_prepare_attachment_for_js($value);
        $html .= '{';
        $html .= '"type":"image",';
        $html .= '"id":"'.$value.'",';
        $html .= '"title":{"use":"false","value":"'.$imageData['title'].'"},';
        $html .= '"caption":{"use":"false","value":""},';
        $html .= '"link":{"use":"false","url":"","newWindow":"false"}';
        $html .= '},';
    }

    $html .= ']';

    magictoolbox_WordPress_MagicSlideshow_add_data($html, $data, null);
}
?>
