<?php


namespace Eventman\Includes\Post;


use Eventman\Admin\LogTrait;

class ImageGallery
{

    /**
     * Generate the gallery input meta box.
     */
    public function imageGallery()
    {
        // add nonce field
        $out = wp_nonce_field(basename(__FILE__), 'sample_nonce', true, false);
        $out .= '<div id="dynamic_cont">
            <div id="img_box_container">';

        global $post;
        $gallery_data = get_post_meta($post->ID, 'gallery_data', true);
        // iterate over gallery data
        if (isset($gallery_data['image_id'])) {
            // add fields for existing gallery data
            for ($i = 0; $i < count($gallery_data['image_id']); $i++) {
                $out .= '<div class="gallery_single_row dolu">
                            <div class="gallery_area_div image_container ">';
                $out .= sprintf('<img class="gallery_img_img" src="%s" height="55" width="55" onclick="open_media_uploader_image_this(this)"/>',
                    wp_get_attachment_thumb_url($gallery_data['image_id'][$i]));
//                $out .= sprintf('<input type="hidden" class="meta_image_url" name="gallery[image_url][]" value="%s"/>', $gallery_data['image_url'][$i]);
                $out .= sprintf('<input type="hidden" class="meta_image_id" name="gallery[image_id][]" value="%s"/>', $gallery_data['image_id'][$i]);
                $out .= '</div>
                            <div class="gallery_area_div">
                                <span class="button remove" onclick="remove_img(this)" title="Remove"/>
                                    <i class="fas fa-trash-alt"></i>
                                </span>
                            </div>
                            <div class="clear" /></div>
                        </div>';
            }
        }

        // generate the main meta box
        $out .= '
        </div></div>
        <div style="display:none" id="main_box">
            <div class="gallery_single_row">
                <div class="gallery_area_div image_container" onclick="open_media_uploader_image(this)">
                    <input class="meta_image_id" value="" type="hidden" name="gallery[image_id][]" />
//                    <input class="meta_image_url" value="" type="hidden" name="gallery[image_url][]" />
                </div>
                <div class="gallery_area_div">
                    <span class="button remove" onclick="remove_img(this)" title="Remove"/><i class="fas fa-trash-alt"></i></span>
                </div>
                <div class="clear"></div>
            </div>
        </div>
        <div id="add_gallery_single_row">
            <input class="button add" type="button" value="+" onclick="open_media_uploader_image_plus();" title="Add image"/>
        </div>';
        echo $out;
    }

    /**
     * Styles and script for the gallery input.
     */
    public function header()
    {
        global $post;
        if ('exhibitors' != $post->post_type) {
            return;
        }
        ?>
        <style type="text/css">
            .gallery_area_div {
                float: right;
            }

            .image_container {
                float: left !important;
                width: 100px;
                background: url('https://i.hizliresim.com/dOJ6qL.png');
                height: 100px;
                background-repeat: no-repeat;
                background-size: cover;
                border-radius: 3px;
                cursor: pointer;
            }

            .image_container img {
                height: 100px;
                width: 100px;
                border-radius: 3px;
            }

            .clear {
                clear: both;
            }

            #dynamic_cont {
                width: 100%;
                height: auto;
                position: relative;
                display: inline-block;
            }

            #dynamic_cont input[type=text] {
                width: 300px;
            }

            #dynamic_cont .gallery_single_row {
                float: left;
                display: inline-block;
                width: 100px;
                position: relative;
                margin-right: 8px;
                margin-bottom: 20px;
            }

            .dolu {
                display: inline-block !important;
            }

            #dynamic_cont label {
                padding: 0 6px;
            }

            .button.remove {
                background: none;
                color: #111111;
                position: absolute;
                border: none;
                top: 4px;
                right: 7px;
                font-size: 1.2em;
                padding: 0px;
                filter: drop-shadow(1px 1px white);
                /*box-shadow: none;*/
            }

            .button.remove:hover {
                background: none;
                color: #fff;
            }

            .button.add {
                background: #c3c2c2;
                color: #ffffff;
                border: none;
                box-shadow: none;
                width: 100px;
                height: 100px;
                font-size: 4em;
            }

            .button.add:hover, .button.add:focus {
                background: #e2e2e2;
                box-shadow: none;
                color: #0f88c1;
                border: none;
            }
        </style>
        <script defer src="https://use.fontawesome.com/releases/v5.0.8/js/solid.js"
                integrity="sha384-+Ga2s7YBbhOD6nie0DzrZpJes+b2K1xkpKxTFFcx59QmVPaSA8c7pycsNaFwUK6l"
                crossorigin="anonymous"></script>
<!--        <link href="https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel="stylesheet">-->
        <script defer src="https://use.fontawesome.com/releases/v5.0.8/js/fontawesome.js"
                integrity="sha384-7ox8Q2yzO/uWircfojVuCQOZl+ZZBg2D2J5nkpLqzH1HY0C1dHlTKIbpRz/LG23c"
                crossorigin="anonymous"></script>
<!--        <script src="https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>-->
        <script type="text/javascript">
            function remove_img(value) {
                var parent = jQuery(value).parent().parent();
                parent.remove();
            }

            var media_uploader = null;

            function open_media_uploader_image(aaa) {
                media_uploader = wp.media({
                    frame: "post",
                    state: "insert",
                    multiple: false
                });
                media_uploader.on("insert", function () {
                    var json = media_uploader.state().get("selection").first().toJSON();
                    var image_url = json.url;
                    var image_id = json.id;
                    var html = '<img class="gallery_img_img" src="' + image_url + '" height="55" width="55" onclick="open_media_uploader_image_this(this)"/>';
                    jQuery(aaa).append(html);
                    // jQuery(aaa).find('.meta_image_url').val(image_url);
                    jQuery(aaa).find('.meta_image_id').val(image_id);
                });
                media_uploader.open();
            }

            function open_media_uploader_image_this(aaa) {
                media_uploader = wp.media({
                    frame: "post",
                    state: "insert",
                    multiple: false
                });
                media_uploader.on("insert", function () {
                    var json = media_uploader.state().get("selection").first().toJSON();
                    var image_url = json.url;
                    var image_id = json.id;
                    jQuery(aaa).attr('src', image_url);
                    // jQuery(aaa).siblings('.meta_image_url').val(image_url);
                    jQuery(aaa).siblings('.meta_image_id').val(image_id);
                });
                media_uploader.open();
            }

            function open_media_uploader_image_plus() {
                media_uploader = wp.media({
                    frame: "post",
                    state: "insert",
                    multiple: true
                });
                media_uploader.on("insert", function () {

                    var length = media_uploader.state().get("selection").length;
                    var images = media_uploader.state().get("selection").models;
                    for (var iii = 0; iii < length; iii++) {
                        var image_id = images[iii].attributes.id;

                        var image_url = images[iii].attributes.url;
                        if ('url' in images[iii].changed) {
                            image_url = images[iii].changed.url;
                        }

                        var box = jQuery('#main_box').html();
                        jQuery(box).appendTo('#img_box_container');
                        var element = jQuery('#img_box_container .gallery_single_row:last-child').find('.image_container');
                        var html = '<img class="gallery_img_img" src="' + image_url + '" height="55" width="55" onclick="open_media_uploader_image_this(this)"/>';
                        element.append(html);
                        // element.find('.meta_image_url').val(image_url);
                        element.find('.meta_image_id').val(image_id);
                    }
                });
                media_uploader.open();
            }

            jQuery(function ($) {
                $("#img_box_container").sortable();
            });
        </script>
        <?php
    }

    use LogTrait {
        log as _log;
    }

    protected function log($msg) {
        $this->_log('Gallery: ' . $msg);
    }

    /**
     * Save gallery callback.
     * @param $postId int post id to save the meta to.
     */
    public function saveProperties($postId)
    {
        global $wp_current_filter;

        $isValidNonce = (isset($_POST['sample_nonce']) && wp_verify_nonce($_POST['sample_nonce'], basename(__FILE__))) ? 'true' : 'false';

        // don't save if the post is autosaving
        if ((defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
            || in_array('wp_ajax_inline-save', $wp_current_filter)
            || wp_is_post_autosave($postId)
            || wp_is_post_revision($postId)
            || !current_user_can('edit_post', $postId)
            || !$isValidNonce
            || (isset($_POST['post_type']) && 'exhibitors' != $_POST['post_type'])
        ) {
            $this->log('Invalid save method, not saving gallery');
            return $postId;
        }

        // check if gallery post data exists
        if (isset($_REQUEST['gallery']) && !empty($_REQUEST['gallery'])) {
            $this->log('Post has gallery, preparing metadata update.');
            // Build array for broadcasting post meta
            $galleryData = ['blog_id' => get_current_blog_id()];

            // iterate over all gallery inputs
            for ($i = 0; $i < count($_REQUEST['gallery']['image_id']); $i++) {
                if ('' != $_REQUEST['gallery']['image_id'][$i]) {
                    // set output data
//                    $galleryData['image_url'][] = $_REQUEST['gallery']['image_url'][$i];
                    $galleryData['image_id'][] = $_REQUEST['gallery']['image_id'][$i];
                }

                // max 6 gallery items
                if (sizeof($galleryData) >= 6) {
                    $this->log('Gallery has more than 6 images, stopping.');
                    break;
                }
            }

            $originalData = get_post_meta($postId, 'gallery_data', true);

            // update gallery or delete if gallery data is empty
            if ($galleryData) {
                if ($galleryData == $originalData) {
                    $this->log('Gallery data is equal, nothing to update, quitting.');
                    return true;
                }
                $this->log('Updating gallery data for post ' . $postId);
                update_post_meta($postId, 'gallery_data', $galleryData);
            } else {
                $this->log('Deleting gallery data for post ' . $postId);
                delete_post_meta($postId, 'gallery_data');
            }
        } // no gallery data received, all fields are empty, delete option
        else {
            $this->log('Gallery empty, deleting data for post ' . $postId);
            delete_post_meta($postId, 'gallery_data');
        }
        return true;
    }

}