<?php


namespace Eventman\Includes\Post;


use Eventman\Admin\LogTrait;
use function Eventman\interevent_get_attachment_data;
use function Eventman\interevent_get_attachment_url;

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="gallery-dynamic-container">
            <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" src="%s" height="55" width="55"/>',
                    interevent_get_attachment_url($gallery_data['image_id'][$i], 'thumbnail'));
//                $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" 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="gallery-main-box-template">
            <div class="gallery-single-row">
                <div class="gallery_area_div image-container">
                    <input class="meta-image-id" value="" type="hidden" name="gallery[image_id][]" />
                </div>
                <div class="gallery_area_div">
                    <span class="button remove" 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="+" 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;
            }

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

            #gallery-dynamic-container input[type=text] {
                width: 300px;
            }

            #gallery-dynamic-container .gallery-single-row {
                float: left;
                display: inline-block;
                width: 100px;
                position: relative;
                margin-right: 8px;
                margin-bottom: 20px;
            }

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

            #gallery-dynamic-container 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>-->
        <?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;
    }

}