<?php

/**
 *
 * @author Станимир | OTW Design
 * @ver 1.0
 */
class Otw_Shortcode_Gallery extends OTW_Shortcodes {

    private $_gallery_slug = 'otw-gallery-shortcode';

    function __construct() {
        parent::__construct();
        $this->has_custom_options = true;
        add_image_size($this->_gallery_slug, 1024, 1024, true); // (cropped)
    }

    /**
     * Register externel lybs 
     */
    function register_external_libs() {
        $this->add_external_lib('css', 'otw-shortcode-general_foundicons', $this->component_url . 'css/general_foundicons.css', 'all', 10);
        $this->add_external_lib('css', 'otw-shortcode-social_foundicons', $this->component_url . 'css/social_foundicons.css', 'all', 20);
        $this->add_external_lib('css', 'otw-grid', $this->component_url . '../' . 'otw_grid_manager/' . 'css/otw-grid.css', 'all', 30);
        $this->add_external_lib('css', 'otw-shortcode', $this->component_url . 'css/otw_shortcode.css', 'all', 40);
        $this->add_external_lib('css', 'otw-nivo-style', $this->component_url . 'css/nivo-lightbox.css', 'all', 50);
        $this->add_external_lib('css', 'otw-shortcode-nivo', $this->component_url . 'images-shortcodes/nivo-default/default.css', 'all', 60);

        $this->add_external_lib('css', 'otw-shortcode_scrolling', $this->component_url . 'css/scroll_for_preview.css?' . md5(time()), 'all', 70);
        $this->add_external_lib('js', 'otw-anish', $this->component_url . 'js/jquery.animate-shadow-min.js', 'all', 98, array('jquery'));
        $this->add_external_lib('js', 'otw-quicks', $this->component_url . 'js/jquery.quicksand.js', 'all', 99, array('otw-anish'));
        $this->add_external_lib('js', 'otw-nivo-lib', $this->component_url . 'js/nivo-lightbox.min.js', 'all', 10, array('otw-quicks'));
        $this->add_external_lib('js', 'otw-shortcode-core', $this->component_url . 'js/otw_shortcode_core.js', 'all', 129, array('otw-nivo-lib'));
        $this->add_external_lib('js', 'otw-shortcode', $this->component_url . 'js/otw_shortcode.js', 'all', 130, array('otw-shortcode-core'));
        return $this;
    }

    /**
     * Applay all settings to shortcode
     */
    public function apply_settings() {
        $this->_applyNumItems();
        $this->_applyPositions();
        $this->_applyImageAction();
    }

    private function _applyNumItems() {
        $this->settings['num_items'] = $this->_getNumItems();
        $this->settings['default_num_items'] = 2;
    }

    private function _getNumItems() {
        return array(
            '1' => $this->get_label('1 Items'),
            '2' => $this->get_label('2 Items(default)'),
            '3' => $this->get_label('3 Items'),
            '4' => $this->get_label('4 Items'),
            '5' => $this->get_label('5 Items'),
            '6' => $this->get_label('6 Items'),
            '7' => $this->get_label('7 Items'),
            '8' => $this->get_label('8 Items'),
            '9' => $this->get_label('9 Items'),
            '10' => $this->get_label('10 Items')
        );
    }

    private function _getPositions() {
        return array(
            'top' => $this->get_label('Top (default)'),
            'right' => $this->get_label('Right'),
            'bottom' => $this->get_label('Bottom'),
            'left' => $this->get_label('Left'),
        );
    }

    private function _applyPositions() {
        $this->settings['positions'] = $this->_getPositions();
        $this->settings['default_positions'] = 'top';
    }

    private function _getImageAction() {
        return array(
            'otw-b-gallery-content-inner otw-lightbox' => $this->get_label('Lightbox (default)'),
            '' => $this->get_label('No Link'),
            'url' => $this->get_label('URL')
        );
    }

    private function _applyImageAction() {
        $this->settings['actions'] = $this->_getImageAction();
        $this->settings['default_actions'] = 'otw-b-gallery-content-inner otw-lightbox';
    }

    /**
     * 
     * @param type $attributes
     * @return string
     */
    public function build_shortcode_code($attributes) {
        $code = '';
        if (!$this->has_error) {
            $code .= '[otw_shortcode_gallery';
            $code .= $this->format_attribute('num_items', 'num_items', $attributes);
            $code .= $this->format_attribute('positions', 'positions', $attributes);
            $code .= $this->format_attribute('actions', 'actions', $attributes);

            if (trim($this->format_attribute('', 'actions', $attributes)) == 'url') {
                
            }
            $total_elements = $this->format_attribute('', 'num_items', $attributes);

            for ($ni = 1; $ni <= $total_elements; $ni++) {
                $code .= $this->format_attribute('image_' . $ni, 'image_' . $ni, $attributes);
                $code .= $this->format_attribute('url_' . $ni, 'url_' . $ni, $attributes);
            }
            $code .= $this->format_attribute('custom_class', 'custom_class', $attributes);
            $code .= ']';
            $code .= '[/otw_shortcode_gallery]';

            return $code;
        }
    }

    /**
     * Set the additional settings
     * @return string
     */
    public function build_shortcode_editor_custom_options() {
        $html = '';

        $source = array();
        if (isset($_POST['shortcode_object'])) {
            $source = $_POST['shortcode_object'];
        }
        $html .= $this->_generateText('custom_class', 'CSS Class', 'If you\'d like to style this element separately enter a name here. A CSS class with this name will be available for you to style this particular element..', $source);
        return $html;
    }

    /**
     * Generate options as HTML string 
     * @return string
     */
    public function build_shortcode_editor_options() {
        $html = '';

        $source = array();
        if (isset($_POST['shortcode_object'])) {
            $source = $_POST['shortcode_object'];
        }
        //Get default value for items in init time
        $total_elements = $this->settings['default_num_items'];
        //check for set items
        if (isset($source['otw-shortcode-element-num_items'])) {
            $total_elements = $source['otw-shortcode-element-num_items'];
        }
        $html .= $this->_generateSelect('num_items', 'Number of itmes', 'Select number of items.', $source, 'num_items', 'default_num_items', 1); //$this->format_attribute('num_items', 'num_items', $attributes);
        $html .= $this->_generateSelect('positions', 'Thumbs Position', 'Choose thumbs positioning.', $source, 'positions', 'default_positions');
        $html .= $this->_generateSelect('actions', 'Click on Image links to?', 'Choose where a click on the image links to.', $source, 'actions', 'default_actions', 1);

        for ($ni = 1; $ni <= $total_elements; $ni++) {
            $html .= $this->_generateUploader('image_' . $ni, 'Image Upload ', 'Upload an image' . $ni . '.  Please use Full Size image in the media settings.', $source);
            if (isset($source['otw-shortcode-element-actions']) && $source['otw-shortcode-element-actions'] == 'url') {
                $html .= $this->_generateText('url_' . $ni, 'Image ' . $ni . ' Click URL ', 'Enter the URL where a click on the image leads to.', $source);
            }
        }
        return $html;
    }

    /**
     * Export end shortcode
     * @param array $attributes
     * @param string $content
     * @return string
     */
    public function display_shortcode($attributes, $content) {
	$html = '';
	$content_gallery = '';
        $pos = $this->format_attribute('', 'positions', $attributes);
        $image_action = $this->format_attribute('', 'actions', $attributes);
        $class_general = 'clearfix';
        $class_general = $this->append_attribute($class_general, 'otw-b-gallery');
        $class_general = $this->append_attribute($class_general, $this->format_attribute('', 'custom_class', $attributes));
        if (in_array($pos, array('top', 'bottom'))) {
            $class_general = $this->append_attribute($class_general, 'otw-b-gallery-horizontal');
        } else {
            $class_general = $this->append_attribute($class_general, 'otw-row');
        }
        $html .= '';
        $html .= '<div class="' . $class_general . '">';


        $gallery_class = 'otw-b-gallery-thumbs';
        if (in_array($pos, array('left', 'right'))) {
            $gallery_class = $this->append_attribute($gallery_class, 'otw-columns otw-seven');
        }
        $gallery = '';
        $gallery .= '<ul class="' . $gallery_class . '">';
        //Get default value for items in init time
        $total_elements = $this->format_attribute('', 'num_items', $attributes);
        for ($ni = 1; $ni <= $total_elements; $ni++) {
            $image = $this->format_attribute('', 'image_' . $ni, $attributes);
            if (!empty($image)):
                $thumb_image = wp_get_attachment_thumb_url($this->attachment_id_from_url($image));
                if ($thumb_image == false || @file_get_contents($thumb_image) == false) {
                    $thumb_image = $image;
                }
                $otw_gallery_image = wp_get_attachment_image_src($this->attachment_id_from_url($image), $this->_gallery_slug);
                if (@file_get_contents($otw_gallery_image[0]) == false) {
                    $image_href = $image;
                } else {
                    $image_href = $otw_gallery_image[0];
                }
                if (!empty($image_action)) {
                    if (trim($image_action) == 'url' && strlen($this->format_attribute('', 'url_' . $ni, $attributes)) > 0) {
                        $image_href = $this->format_attribute('', 'url_' . $ni, $attributes);
                    }
                }

                $gallery .= '<li>'
                        . '<a href="' .$image_href  . '" '
                        . 'data-href="' . $image . '">'
                        . '<img src="' . $thumb_image . '" alt="">'
                        . '</a>'
                        . '</li>';
            endif;
        }
        $gallery .= '</ul>';


        $gallery_content = 'otw-b-gallery-content';
        if (in_array($pos, array('left', 'right'))) {
            $gallery_content = $this->append_attribute($gallery_content, 'otw-columns otw-seventeen');
        }
        $content_gallery .= '<div class="' . $gallery_content . '">';
        $image_1 = $this->format_attribute('', 'image_1', $attributes);

        $link_modal_class = 'otw-b-gallery-content-inner otw-b-calculated';
        $link_modal_class = $this->append_attribute($link_modal_class, 'otw-lightbox');

        if (!empty($image_action)) {
            if (trim($image_action) == 'url' && strlen($this->format_attribute('', 'url_1', $attributes)) > 0) {
                $content_gallery .= '<a href="' . $this->format_attribute('', 'url_1', $attributes) . '" class="' . $link_modal_class . ' otw-external">';
            } else {
                 $content_gallery .= '<a href="' . $image_1. '" class="' . $link_modal_class . '">';
            }
        }
        if (!empty($image_1) && file_get_contents($image_1) != false) {
            $otw_first_image = wp_get_attachment_image_src($this->attachment_id_from_url($image_1), $this->_gallery_slug);
            if( $otw_first_image && isset( $otw_first_image[0] ) ){
        	    $content_gallery .= '<img src="'.$otw_first_image[0].'" alt="" />';
            }else{
        	    $content_gallery .= '<img src="'.$image_1.'" alt="" />';
            }
        }
        if (!empty($image_action)) {
            $content_gallery .= '</a>';
        }


        $content_gallery .= '</div>';
        if (in_array($pos, array('left', 'top'))) {
            $html .= $gallery;
            $html .= $content_gallery;
        } else {
            $html .= $content_gallery;
            $html .= $gallery;
        }
        $html .= '</div>';

        return $this->format_shortcode_output($html);
    }

    /**
     * Return ID of attachment Id
     * @global type $wpdb
     * @param string $attachment_url
     * @return int
     */
    function attachment_id_from_url($attachment_url = '') {
        global $wpdb;
        $attachment_id = false;
        // If there is no url, return.
        if ('' == $attachment_url)
            return;
        // Get the upload directory paths
        $upload_dir_paths = wp_upload_dir();
        // Make sure the upload path base directory exists in the attachment URL, to verify that we're working with a media library image
        if (false !== strpos($attachment_url, $upload_dir_paths['baseurl'])) {
            // If this is the URL of an auto-generated thumbnail, get the URL of the original image
            $attachment_url = preg_replace('/(?=\.(jpg|jpeg|png|gif)$)/i', '', $attachment_url);
            // Remove the upload path base directory from the attachment URL
            $attachment_url = str_replace($upload_dir_paths['baseurl'] . '/', '', $attachment_url);
            // Finally, run a custom database query to get the attachment ID from the modified attachment URL
            $attachment_id = $wpdb->get_var($wpdb->prepare("SELECT wposts.ID FROM $wpdb->posts wposts, $wpdb->postmeta wpostmeta WHERE wposts.ID = wpostmeta.post_id AND wpostmeta.meta_key = '_wp_attached_file' AND wpostmeta.meta_value = '%s' AND wposts.post_type = 'attachment'", $attachment_url));
        }
        return (int) $attachment_id;
    }

}
