<?php
/**
 * This file handles the smooth scroll functionality.
 *
 * @package SekhloPress Connect Addon
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit; // No direct access, please.
}

add_action( 'wp_enqueue_scripts', 'sekhlo_smooth_scroll_scripts' );
/**
 * Add the smooth scroll script if enabled.
 *
 * @since 1.6
 */
function sekhlo_smooth_scroll_scripts() {
	if ( ! function_exists( 'sekhlo_get_defaults' ) ) {
		return;
	}

	$settings = wp_parse_args(
		get_option( 'sekhlo_settings', array() ),
		sekhlo_get_defaults()
	);

	if ( ! $settings['smooth_scroll'] ) {
		return;
	}

	$suffix = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min';

	wp_enqueue_script( 'sekhlo-smooth-scroll', plugin_dir_url( __FILE__ ) . "js/smooth-scroll{$suffix}.js", array(), SEKHLO_CONNECT_ADDON_VERSION, true );

	wp_localize_script(
		'sekhlo-smooth-scroll',
		'gpSmoothScroll',
		array(
			'elements' => apply_filters(
				'sekhlo_smooth_scroll_elements',
				array(
					'.smooth-scroll',
					'li.smooth-scroll a',
				)
			),
			'duration' => apply_filters( 'sekhlo_smooth_scroll_duration', 800 ),
			'offset' => apply_filters( 'sekhlo_smooth_scroll_offset', '' ),
		)
	);
}

add_filter( 'sekhlo_option_defaults', 'sekhlo_smooth_scroll_default' );
/**
 * Add the smooth scroll option to our defaults.
 *
 * @since 1.6
 *
 * @param array $defaults Existing defaults.
 * @return array New defaults.
 */
function sekhlo_smooth_scroll_default( $defaults ) {
	$defaults['smooth_scroll'] = false;

	return $defaults;
}

add_action( 'customize_register', 'sekhlo_smooth_scroll_customizer', 99 );
/**
 * Add our smooth scroll option to the Customizer.
 *
 * @since 1.6
 *
 * @param WP_Customize_Manager $wp_customize Theme Customizer object.
 */
function sekhlo_smooth_scroll_customizer( $wp_customize ) {
	if ( ! function_exists( 'sekhlo_get_defaults' ) ) {
		return;
	}

	$defaults = sekhlo_get_defaults();

	require_once SEKHLO_LIBRARY_DIRECTORY . 'customizer-helpers.php';

	$wp_customize->add_setting(
		'sekhlo_settings[smooth_scroll]',
		array(
			'default' => $defaults['smooth_scroll'],
			'type' => 'option',
			'sanitize_callback' => 'sekhlo_premium_sanitize_checkbox',
		)
	);

	$wp_customize->add_control(
		'sekhlo_settings[smooth_scroll]',
		array(
			'type' => 'checkbox',
			'label' => __( 'Smooth scroll', 'sekhlopress-connect' ),
			'description' => __( 'Initiate smooth scroll on anchor links using the <code>smooth-scroll</code> class.', 'sekhlopress-connect' ),
			'section' => 'sekhlo_general_section',
		)
	);
}
