<?php
/**
 * Nevo Theme Customizer Footer Builder
 *
 * @package Nevo
 */
if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

class Nevo_Customizer_Footer_Builder {

    /**
     * Panel ID, use for builder ID too
     *
     * @var string
     */
    public $panel = 'nevo_footer';

    /**
     * Builder Sections and Controller ID
     *
     * @var string
     *
     */
    public $builder_section_controller = 'nevo_footer_builder_controller_section';

    /**
     * Main Instance
     *
     * Insures that only one instance of Nevo_Customizer_Footer_Builder exists in memory at any one
     * time. Also prevents needing to define globals all over the place.
     *
     * @return object
     */
    public static function instance() {

        // Store the instance locally to avoid private static replication
        static $instance = null;

        // Only run these methods if they haven't been ran previously
        if ( null === $instance ) {
            $instance = new Nevo_Customizer_Footer_Builder;
        }

        // Always return the instance
        return $instance;
    }

    /**
     *  Run functionality with hooks
     *
     * @return void
     */
    public function run() {

        add_action( 'customize_register', array( $this, 'set_customizer' ), 1 );
		
		add_filter( 'nevo/customizer/config', array( $this, 'nevo_customizer_footer_builder_config' ), 20 );

        add_filter( 'nevo_default_theme_options', array( $this, 'footer_defaults' ) );
		
        add_filter( 'nevo_builders', array( $this, 'footer_builder' ) );

        add_action( 'nevo_footer_content', array( $this, 'nevo_footer_display' ), 10 );
    }

    /**
     * Callback functions for customize_register,
     * Fixed previous array issue
     *
     * @param null
     * @return void
     */
    public function set_customizer() {
        $builder = nevo_get_footer_builder_options( Nevo_Customizer_Footer_Builder()->builder_section_controller );
        if ( is_array( $builder ) ) {
            $builder = json_encode( urldecode_deep( $builder ), true );
        }
        set_theme_mod( Nevo_Customizer_Footer_Builder()->builder_section_controller, $builder );
    }

    /**
     * Get footer builder
     *
     * @param null
     * @return void
     */
    public function get_builder() {
        $builder = nevo_get_footer_builder_options( Nevo_Customizer_Footer_Builder()->builder_section_controller );
        if ( ! is_array( $builder ) ) {
            $builder = json_decode( urldecode_deep( $builder ), true );
        }
        return $builder;
    }


    /**
     * Callback functions for nevo_default_theme_options,
     * Add Footer Builder defaults values
     *
     * @param array $default_options
     * @return array
     */
    public function footer_defaults( $default_options = array() ) {

        $footer_defaults = [

            $this->builder_section_controller => [
                'desktop'   => [
                    'bottom'      => [
                        'nc-col-1'      => [
                            [
                                'id'    => 'footer-copyright'
                            ]
                        ]
                    ]
                ]
            ]
        ];
        return array_merge( $default_options, $footer_defaults );
    }

    /**
     * Callback functions for nevo_builders,
     * Add Footer Builder elements
     *
     * @param array $builder builder fields
     * @return array
     */
    public function footer_builder( $builder ) {

        $items = apply_filters( 
		'Nevo_Customizer_Footer_Builder_items',
			array(
				'footer_copyright'   => array(
					'name'    => esc_html__( 'Copyright', 'nevo' ),
					'id'      => 'footer-copyright',
					'section' => 'footer_copyright',
				),
				'footer_menu' => array(
					'name'    => esc_html__( 'Footer Menu', 'nevo' ),
					'id'      => 'footer-menu',
					'section' => 'footer_menu',
				),
				'footer_social' => array(
					'name'    => esc_html__( 'Social Icons', 'nevo' ),
					'id'      => 'footer-social',
					'section' => 'footer_social',
				),
				'footer_button' => array(
					'name'    => esc_html__( 'Button 1', 'nevo' ),
					'id'      => 'footer-button',
					'section' => 'footer_button',
				),
				'footer_html' => array(
					'name'    => esc_html__( 'HTML 1', 'nevo' ),
					'id'      => 'html-1',
					'section' => 'footer_html',
				),
				'footer_date_format'  => array(
                    'name'    => esc_html__( 'Date Format', 'nevo' ),
                    'id'      => 'date-format',
                    'section' => 'footer_date_format',
                ),
				'footer_widget_1' => array(
					'name'    => esc_html__( 'Footer Widget 1', 'nevo' ),
					'id'      => 'footer-1',
					'section' => 'sidebar-widgets-footer-1',
				),
				'footer_widget_2' => array(
					'name'    => esc_html__( 'Footer Widget 2', 'nevo' ),
					'id'      => 'footer-2',
					'section' => 'sidebar-widgets-footer-2',
				),
				'footer_widget_3' => array(
					'name'    => esc_html__( 'Footer Widget 3', 'nevo' ),
					'id'      => 'footer-3',
					'section' => 'sidebar-widgets-footer-3',
				),
				'footer_widget_4' => array(
					'name'    => esc_html__( 'Footer Widget 4', 'nevo' ),
					'id'      => 'footer-4',
					'section' => 'sidebar-widgets-footer-4',
				),
				'footer_widget_5' => array(
					'name'    => esc_html__( 'Footer Widget 5', 'nevo' ),
					'id'      => 'footer-5',
					'section' => 'sidebar-widgets-footer-5',
				),
				'footer_widget_6' => array(
					'name'    => esc_html__( 'Footer Widget 6', 'nevo' ),
					'id'      => 'footer-6',
					'section' => 'sidebar-widgets-footer-6',
				),
			)
        );

        $footer_builder = array(
            Nevo_Customizer_Footer_Builder()->panel => array(
                'id'         => Nevo_Customizer_Footer_Builder()->panel,
                'title'      => esc_html__( 'Footer Builder', 'nevo' ),
                'control_id' => Nevo_Customizer_Footer_Builder()->builder_section_controller,
                'panel'      => Nevo_Customizer_Footer_Builder()->panel,
                'section'    => Nevo_Customizer_Footer_Builder()->builder_section_controller,
                'devices'    => array(
                    'desktop' => esc_html__( 'Global Footer', 'nevo' )
                ),
                'items'      => $items,
                'rows'       => array(
                    'top'       => esc_html__( 'Top Row', 'nevo' ),
                    'main'      => esc_html__( 'Middle Row', 'nevo' ),
                    'bottom'    => esc_html__( 'Bottom Row', 'nevo' )
                ),
                'cols'       => array(
                    'top'       => 3,
                    'main'      => 3,
                    'bottom'    => 3
                ),
				'builder'		=> 'footer',
				'sidebar'		=> 'no-sidebar'
            ),
        );
        $footer_builder = apply_filters( 'Nevo_Customizer_Footer_Builder', $footer_builder );
        return array_merge( $builder, $footer_builder );

    }
	
    /**
     * Callback functions for customize_register,
     * Add Panel Section control
     *
     * @param object $wp_customize
     * @return void
     */
    public function nevo_customizer_footer_builder_config( $configs = array() ) {
		$footer_defaults = self::footer_defaults();
		$config = array(
			array(
				'name'  => $this->panel,
				'type'  => 'panel',
				'priority' => 30,
				'title' => __( 'Footer', 'nevo' ),
			),
			array(
				'name'  => $this->builder_section_controller,
				'type'  => 'section',
				'panel' => $this->panel,
				'priority' => 10,
				'title' => __( 'Footer', 'nevo' ),
			),
			array(
				'name'            => $this->builder_section_controller,
				'type'            => 'text',
				'section'         => $this->builder_section_controller,
				'theme_supports'  => '',
				'selector'        => '.site-footer',
				'render_callback' => 'nevo_construct_footer',
				'sanitize_callback' => 'nevo_sanitize_field',
				'priority' 		  => 5,
				'title'           => __( 'Text', 'nevo' ),
				'default'         => $footer_defaults,
			),
		);
		return array_merge( $configs, $config );
	}

	/**
     *Column Element
     *
     * @param $column_elements
     */
    public function column_elements( $column_elements) {
		foreach ( $column_elements as $element ) {
			$id     = esc_html($element['id']);
			nevo_footer_element( $id );
		}
    }
	
    /**
     * Callback Function For nevo_action_footer
     * Display Footer Content
     *
     * @return void
     */
    public function nevo_footer_display() {

        $builder = $this->get_builder();

        if ( isset( $builder['desktop'] ) && ! empty( $builder['desktop'] ) ) {

            $footer_builder_data    = [];
			$active_sidebar         = [];
            $footer_builder         = $builder['desktop'];

            foreach ( $footer_builder as $key => $single_row ) {

                if ( ! empty( $single_row ) ) {

                    foreach ( $single_row as $col_key => $columns ) {

                        if ( ! empty( $columns ) ) {

                            $footer_builder_data[$key][$col_key]    = $columns;
							$active_sidebar[]                       = $columns[0]['id'];
                        }
                    }
                }
            }
            if ( ! empty( $footer_builder_data ) ) {

                $this->footer_content( $footer_builder_data );
            }
			
			if( is_customize_preview() ){
				self::get_elements($active_sidebar);
			}
        }

    }

    /**
     * Display Footer Content
     *
     * @param $footer_builder
     * @return void
     */
    public function footer_content( $footer_builder ) {
		if ( isset( $footer_builder['top'] ) ) {
			if ( nevo_get_page_setting( 'disable_footer_top' ) ) {
				return;
			}
			$top_elements   = $footer_builder['top'];
			
			$layout 	= Nevo()->get_setting( 'nevo_footer_top_layout' );
			
			// Top Footer Class
			$top_footer_class = ['footer-section top-footer'];
			
			if ( !empty( array_key_exists('nc-col-0', $top_elements ) ) ) {
				$top_footer_class['start'] = 'has-start';
			}else{
				$top_footer_class['start'] = 'start-empty';
			}
			if ( !empty( array_key_exists('nc-col-1', $top_elements ) ) ) {
				$top_footer_class['center'] = 'has-center';
			}else{
				$top_footer_class['center'] = 'center-empty';
			}
			if ( !empty( array_key_exists('nc-col-2', $top_elements ) ) ) {
				$top_footer_class['end'] = 'has-end';
			}else{
				$top_footer_class['end'] = 'end-empty';
			}
			$columns = count( $top_elements );
			
			$top_footer_class = join( ' ', $top_footer_class );
			
			?>
			<div <?php nevo_do_element_classes( 'top_footer', array( ''. esc_attr( $top_footer_class ) .'' ) ); ?>>
				<div class="nevo-container inside-footer <?php echo esc_attr( $layout ); ?>">
					<div class="grid-columns grid-columns-<?php echo esc_attr( $columns );?>">
					
						<?php if ( array_key_exists( 'nc-col-0', $top_elements ) ) : ?>
							<?php 
							$columns = count( $top_elements['nc-col-0'] );
							$col_per_row = [
								'xs' => 1,
								'sm' => ($columns == 1 || $columns == 3) ? 1 : 2,
								'md' => ($columns == 3 || $columns == 6) ? 3 : (($columns == 1 || $columns == 2) ? $columns : 2),
								'lg' => $columns,
							];
							?>
							<div class="footer-row-cols d-flex<?php get_data_columns( $col_per_row ); ?>">
								<?php $this->column_elements( $top_elements['nc-col-0'] ); ?>
							</div>
						<?php endif; ?>

						<?php if ( array_key_exists( 'nc-col-1', $top_elements ) ) : ?>
							<?php 
							$columns = count( $top_elements['nc-col-1'] );
							$col_per_row = [
								'xs' => 1,
								'sm' => ($columns == 1 || $columns == 3) ? 1 : 2,
								'md' => ($columns == 3 || $columns == 6) ? 3 : (($columns == 1 || $columns == 2) ? $columns : 2),
								'lg' => $columns,
							];
							?>
							<div class="footer-row-cols d-flex<?php get_data_columns( $col_per_row ); ?>">
								<?php $this->column_elements( $top_elements['nc-col-1'] ); ?>
							</div>
						<?php endif; ?>

						<?php if ( array_key_exists('nc-col-2', $top_elements ) ) : ?>
							<?php 
							$columns = count( $top_elements['nc-col-2'] );
							$col_per_row = [
								'xs' => 1,
								'sm' => ($columns == 1 || $columns == 3) ? 1 : 2,
								'md' => ($columns == 3 || $columns == 6) ? 3 : (($columns == 1 || $columns == 2) ? $columns : 2),
								'lg' => $columns,
							];
							?>
							<div class="footer-row-cols d-flex<?php get_data_columns( $col_per_row ); ?>">
								<?php $this->column_elements( $top_elements['nc-col-2'] ); ?>
							</div>
						<?php endif; ?>
					</div>
				</div>
			</div><!-- .top-footer -->
			<?php
		}
		if ( isset( $footer_builder['main'] ) ) {
			if ( nevo_get_page_setting( 'disable_footer_main' ) ) {
				return;
			}
			$middle_elements   = $footer_builder['main'];
			
			$layout 	= Nevo()->get_setting( 'nevo_footer_middle_layout' );
			
			// Middle Footer Class
			$middle_footer_class = ['footer-section middle-footer'];
			
			if ( !empty( array_key_exists('nc-col-0', $middle_elements ) ) ) {
				$middle_footer_class['start'] = 'has-start';
			}else{
				$middle_footer_class['start'] = 'start-empty';
			}
			if ( !empty( array_key_exists('nc-col-1', $middle_elements ) ) ) {
				$middle_footer_class['center'] = 'has-center';
			}else{
				$middle_footer_class['center'] = 'center-empty';
			}
			if ( !empty( array_key_exists('nc-col-2', $middle_elements ) ) ) {
				$middle_footer_class['end'] = 'has-end';
			}else{
				$middle_footer_class['end'] = 'end-empty';
			}
			$columns = count( $middle_elements );
			
			$middle_footer_class = join( ' ', $middle_footer_class );
			
			?>
			<div <?php nevo_do_element_classes( 'middle_footer', array( ''. esc_attr( $middle_footer_class ) .'' ) ); ?>>
				<div class="nevo-container inside-footer <?php echo esc_attr( $layout ); ?>">
					<div class="grid-columns grid-columns-<?php echo esc_attr( $columns );?>">
					
						<?php if ( array_key_exists( 'nc-col-0', $middle_elements ) ) : ?>
							<?php 
							$columns = count( $middle_elements['nc-col-0'] );
							$col_per_row = [
								'xs' => 1,
								'sm' => ($columns == 1 || $columns == 3) ? 1 : 2,
								'md' => ($columns == 3 || $columns == 6) ? 3 : (($columns == 1 || $columns == 2) ? $columns : 2),
								'lg' => $columns,
							];
							?>
							<div class="footer-row-cols d-flex<?php get_data_columns( $col_per_row ); ?>">
								<?php $this->column_elements( $middle_elements['nc-col-0'] ); ?>
							</div>
						<?php endif; ?>

						<?php if ( array_key_exists( 'nc-col-1', $middle_elements ) ) : ?>
							<?php 
							$columns = count( $middle_elements['nc-col-1'] );
							$col_per_row = [
								'xs' => 1,
								'sm' => ($columns == 1 || $columns == 3) ? 1 : 2,
								'md' => ($columns == 3 || $columns == 6) ? 3 : (($columns == 1 || $columns == 2) ? $columns : 2),
								'lg' => $columns,
							];
							?>
							<div class="footer-row-cols d-flex<?php get_data_columns( $col_per_row ); ?>">
								<?php $this->column_elements( $middle_elements['nc-col-1'] ); ?>
							</div>
						<?php endif; ?>

						<?php if ( array_key_exists('nc-col-2', $middle_elements ) ) : ?>
							<?php 
							$columns = count( $middle_elements['nc-col-2'] );
							$col_per_row = [
								'xs' => 1,
								'sm' => ($columns == 1 || $columns == 3) ? 1 : 2,
								'md' => ($columns == 3 || $columns == 6) ? 3 : (($columns == 1 || $columns == 2) ? $columns : 2),
								'lg' => $columns,
							];
							?>
							<div class="footer-row-cols d-flex<?php get_data_columns( $col_per_row ); ?>">
								<?php $this->column_elements( $middle_elements['nc-col-2'] ); ?>
							</div>
						<?php endif; ?>
					</div>
				</div>
			</div><!-- .middle-footer -->
			<?php
		}
		if ( isset( $footer_builder['bottom'] ) ) {
			if ( nevo_get_page_setting( 'disable_footer_bottom' ) ) {
				return;
			}
			$bottom_elements   = $footer_builder['bottom'];

			$layout 	= Nevo()->get_setting( 'nevo_footer_bottom_layout' );
			
			// Bottom Footer Class
			if ( !empty( array_key_exists('nc-col-0', $bottom_elements ) ) ) {
				$bottom_footer_class['start'] = 'has-start';
			}else{
				$bottom_footer_class['start'] = 'start-empty';
			}
			if ( !empty( array_key_exists('nc-col-1', $bottom_elements ) ) ) {
				$bottom_footer_class['center'] = 'has-center';
			}else{
				$bottom_footer_class['center'] = 'center-empty';
			}
			if ( !empty( array_key_exists('nc-col-2', $bottom_elements ) ) ) {
				$bottom_footer_class['end'] = 'has-end';
			}else{
				$bottom_footer_class['end'] = 'end-empty';
			}
			$bottom_footer_class[] = $layout;
			?>
			<footer <?php nevo_do_attr( 'site_info' ); ?>>
				<div class="nevo-container inside-footer d-flex text-center <?php echo esc_attr( implode( ' ', $bottom_footer_class) );?>">
				
					<?php if ( array_key_exists( 'nc-col-0', $bottom_elements ) || array_key_exists('nc-col-2', $bottom_elements ) ) : ?>
						<div class="footer-col col-start d-lg-flex justify-content-start align-items-center">
							<?php
							if ( array_key_exists('nc-col-0', $bottom_elements ) ) :
								$this->column_elements( $bottom_elements['nc-col-0'] );
							endif;
							?>
						</div>
					<?php endif; ?>

					<?php if ( array_key_exists( 'nc-col-1', $bottom_elements ) ) : ?>
						<div class="footer-col col-center d-lg-flex justify-content-center align-items-center">
							<?php $this->column_elements( $bottom_elements['nc-col-1'] ); ?>
						</div>
					<?php endif; ?>

					<?php if ( array_key_exists( 'nc-col-0', $bottom_elements ) || array_key_exists('nc-col-2', $bottom_elements ) ) : ?>
						<div class="footer-col col-end d-lg-flex justify-content-end align-items-center">
							<?php
							if ( array_key_exists('nc-col-2', $bottom_elements ) ) :
								$this->column_elements( $bottom_elements['nc-col-2'] );
							endif;
							?>
						</div>
					<?php endif; ?>
					
				</div>
			</footer><!-- .bottom-footer -->
			<?php
		}
    }
	/**
     * Footer get_elements only for the sidebar so that we can see sidebar in customizer
     *
     * @param $sidebar_elements array
     * @return void
     */
    public function get_elements( $sidebar_elements ) {

        if ( is_array( $sidebar_elements ) && is_customize_preview() ) {

            $sidebar_array = [
                'footer-1',
                'footer-2',
                'footer-3',
                'footer-4',
                'footer-5',
                'footer-6'
            ];
            $sidebar_elements = array_diff( $sidebar_array, $sidebar_elements);
            echo '<div class="nevo-container d-none">';
            foreach ( $sidebar_elements as $key ) {
                nevo_footer_element( esc_html($key) );
            }
            echo '</div><!-- .d-none -->';
        }
    }
}

/**
 * Create Instance for Nevo_Customizer_Footer_Builder
 *
 * @param
 * @return object
 */
if ( ! function_exists( 'nevo_customizer_footer_builder' ) ) {

    function nevo_customizer_footer_builder() {

        return Nevo_Customizer_Footer_Builder::instance();
    }

    nevo_customizer_footer_builder()->run();
}

/**
 * Get footer builder default options
 *
 * @param null
 * @return mixed nevo_theme_options
 *
 */
if ( ! function_exists( 'nevo_get_footer_builder_options' ) ) :
    function nevo_get_footer_builder_options( $key = '' ) {
        if ( ! empty( $key ) ) {
            $footer_default_values  = Nevo_Customizer_Footer_Builder()->footer_defaults();
            $theme_mod_values       = get_theme_mod( $key, isset( $footer_default_values[ $key ] ) ? $footer_default_values[ $key ] : '' );
            return apply_filters( 'nevo_' . $key, $theme_mod_values );
        }
        return false;
    }
endif;

if ( ! function_exists( 'nevo_footer_element' ) ) :
/**
 * Wrapper function to print HTML markup for all footer element.
 * 
 * @param string $element
 */
function nevo_footer_element( $element ) {
	// Abort if element slug is empty.
	if ( empty( $element ) ) {
		return;
	}

	// Classify element into its type.
	$type = preg_replace( '/-\d$/', '', $element );

	// Add passing variables.
	$variables = array( 'element' => $element, 'slug' => $element );

	// Get footer element template.
	$html = nevo_get_template_part( 'footer/' . $type, null, $variables, false );

	// Filters to modify the final HTML tag.
	$html = apply_filters( 'nevo_footer_element', $html, $element );
	$html = apply_filters( 'nevo_footer_element/' . $element, $html );

	echo $html; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
}
endif;