<?php

/**
 * Class LEAPIN_Custom_Header
 *
 * @author LeapIn Corp.
 * @since 1.1.0
 */
class LEAPIN_Custom_Header
{

    public function __construct()
    {

        $this->registerActionHooks();

        return $this;
    }

    /**
     * [registerActionHooks description]
     * @return [type] [description]
     */
    public function registerActionHooks()
    {

        add_action('customize_register', array($this, 'customizer'));

        return $this;
    }

    /**
     * [customiser description]
     * @return [type] [description]
     */
    public function customizer($wp_customize)
    {

        $this->registerCustomizerSettings('custom-header', $wp_customize);

        return;
    }

    public function registerCustomizerSettings($file_handle = '', $wp_customize)
    {

        require_once get_template_directory() . '/inc/custom-header/customizer/' . sanitize_title($file_handle) . '.php';

        return $this;
    }


    public static function getContainerBeforeTag()
    {
        $html = '<div id="wp-custom-header" class="card__cn swiper_ver1" data-layout_type="swiper_ver1">';
        $html .= '<div class="card__w opacity-1">';
        $html .= '<ul class="card__ul swiper-wrapper">';
        return $html;
    }

    public static function getContainerAfterTag()
    {
        $html = '</ul>';
        $html .= '</div>';
        $html .= '</div>';
        return $html;
    }

    public static function getMedia()
    {

        /**
         * register_default_headers default header images variables
         * @type Array
         */
        global $_wp_default_headers;

        $headers = array();
        $html = '';
        $css = '';

        /**
         * 'random-default-image'
         * 'random-uploaded-image'
         * 'remove-header'
         * 'http....' only one image
         */
        $header_image_mod = get_theme_mod('header_image', '');

        if (empty($header_image_mod) && !(is_home() || is_front_page())) return '';

        // video active
        if (self::isVideoActive()) {
            // @todo implement video in later version
        } else {

            //ramdom header images
            //@see https://developer.wordpress.org/reference/functions/_get_random_header_data/
            if ('random-uploaded-image' == $header_image_mod && leapin_is_pro()) {
                /**
                 * @type Array
                 */
                $headers = get_uploaded_header_images();

            } else if (preg_match("/^(?:http|https)/i", $header_image_mod)) { // one image
                /**
                 * @type Object
                 */
                $headers = get_custom_header();

            } elseif (!empty($_wp_default_headers)) {  // register_default_headers registered and enabled to display
                $headers = $_wp_default_headers;
            }

            if (!empty($headers) && is_array($headers)) {

//                if (count($headers) > 0) {
                $html .= self::getContainerBeforeTag();
                $i = 0;
                foreach ($headers as $header) {
                    $img_url = self::getImgUrl((object)$header);
                    $css .= "#wp-custom-header .card-$i .card__thumbnail::after{background-image: url($img_url);}";
                    $html .= "<li class=\"card card-$i font-xlarge swiper-slide\">";
                    $html .= self::getCustomHeaderWidgetHtml($i++);
                    $html .= '</li>';
                } //endforeach
                $html .= self::getContainerAfterTag();
//                }
            } elseif (is_object($headers)) {
                $html .= self::getContainerBeforeTag();
                $i = 0;
                $img_url = self::getImgUrl((object)$headers);
                $css .= "#wp-custom-header .card-$i .card__thumbnail::after{background-image: url($img_url);}";
                $html .= "<li class=\"card card-$i font-xlarge swiper-slide\">";
                $html .= self::getCustomHeaderWidgetHtml($i++);
                $html .= '</li>';
                $html .= self::getContainerAfterTag();
            }

            if (count($headers) === 1) {
                $css .= "#wp-custom-header .swiper-pagination{display: none;}";
            }

            add_filter('leapin_load_css_on_each_pjax', function ($css_all) use ($css) {
                if (!leapin_is_pro()) {
                    $css .= '#wp-custom-header .card__content { opacity: 0; transition: none;}';
                    $css .= '#wp-custom-header .swiper-slide-active .card__content { opacity: 1; transition: opacity .5s ease 1s;}';
                }
                return $css_all . $css;
            });
        }
        return $html;
    }

    public static function getImgUrl($header)
    {
        return $url = sprintf($header->url, get_template_directory_uri(), get_stylesheet_directory_uri());
    }

    public static function getImgTag($header, $attr = array())
    {
        $url = self::getImgUrl($header);

        if (property_exists($header, 'width')) {
            $width = absint($header->width);
        }
        if (property_exists($header, 'height')) {
            $height = absint($header->height);
        }

        if (!array_key_exists('alt', $attr)) {
            if (property_exists($header, 'alt_text')) {
                $alt_text = $header->alt_text;
                $attr['alt'] = $alt_text;
            } elseif (property_exists($header, 'description')) {
                $alt_text = $header->description;
                $attr['alt'] = $alt_text;
            } else {
                $attr['alt'] = '';
            }
        }

        //@see https://developer.wordpress.org/reference/functions/get_header_image_tag/
        $attr = wp_parse_args(
            $attr,
            array(
                'src' => $url,
                'width' => $width,
                'height' => $height
            )
        );

        if (!empty($header->attachment_id)) {
            $image_meta = leapin_get_post_meta('_wp_attachment_metadata', $header->attachment_id);
            $size_array = array($width, $height);

            if (is_array($image_meta)) {
                $srcset = wp_calculate_image_srcset($size_array, $header->url, $image_meta, $header->attachment_id);
                $sizes = !empty($attr['sizes']) ? $attr['sizes'] : wp_calculate_image_sizes($size_array, $header->url, $image_meta, $header->attachment_id);
                if ($srcset && $sizes) {
                    $attr['srcset'] = $srcset;
                    $attr['sizes'] = $sizes;
                }
            }
        }

        $attr = array_map('esc_attr', $attr);

        $html = '<img';
        foreach ($attr as $name => $value) {
            $html .= ' ' . $name . '="' . $value . '"';
        }
        $html .= ' />';

        return $html;
    }

    public static function isCarouselActive()
    {
        $headers = array();
        $header_image_mod = get_theme_mod('header_image', '');

        //@see https://developer.wordpress.org/reference/functions/_get_random_header_data/
        if ('random-uploaded-image' == $header_image_mod && (is_home() || is_front_page())) {
            /**
             * @type Array
             */
            $headers = get_uploaded_header_images();

        }

        return count($headers) > 1 ? true : false;
    }

    public static function isVideoActive()
    {
        return is_header_video_active() && (has_header_video() || is_customize_preview());
    }

    public static function getCustomHeaderWidgetHtml($i = 0)
    {
        $widgets = leapin_get_widget_data_for('on_custom_header_image');
        $title = '';
        $desc = '';
        $link = '';
        ob_start();
        if (is_array($widgets) && array_key_exists($i, $widgets)) {
            $widget = $widgets[$i];
            if (property_exists($widget, 'title') && !empty($widget->title)) {
                $title = '<div class="card__header"><p class="card__title" itemprop="headline"><a href="#">' . $widget->title . '</a></p></div>';
            }
            if (property_exists($widget, 'desc') && !empty($widget->desc)) {
                $desc = '<div class="card__excerpt" itemprop="articleBody">' . $widget->desc . '</div>';
            }
            if (property_exists($widget, 'link') && !empty($widget->link)
                && property_exists($widget, 'url') && !empty($widget->url)) {
                $link = sprintf('<div class="card__footer"><a class="card__more flat_btn ripple" href="%s">%s</a></div>', $widget->url, $widget->link);
            }
            ?>
            <article class="cf card__wrap">
                <div class="card__thumbnail"></div>
                <div class="card__content">
                    <?php echo $title; ?>
                    <?php echo $desc; ?>
                    <?php echo $link; ?>
                    <div class="swiper-pagination"></div>
                </div>
            </article>
            <?php
        }
        return ob_get_clean();
    }

}

// Start
new LEAPIN_Custom_Header();
