<?php
/*
* Stop execution if someone tried to get file directly.
*/
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}


/*
* Get the social icons settings from DB
*/
if ( ! function_exists( 'fl_get_social_icons_settings' ) ) {
	function fl_get_social_icons_settings() {
		$fl_settings = get_option( 'fl_settings', false );
		// In free version, do not persist custom social icon design values; only allow preview.
		if ( function_exists( 'fl_fs' ) && ! fl_fs()->is__premium_only() && is_customize_preview() ) {
			// Allow reading settings during preview for live display only; do not change persistence logic here.
		}
		if ( isset( $fl_settings['social_icons'] ) ) {
			$fl_social_icons_settings = $fl_settings['social_icons'];
		} else {
			$fl_social_icons_settings = array();
		}
		$fl_social_icons_settings = wp_parse_args( $fl_social_icons_settings, fl_social_icons_defaults() );

		// Get saved networks and merge with defaults to preserve customizations
		$saved_networks   = isset( $fl_social_icons_settings['networks'] ) ? $fl_social_icons_settings['networks'] : array();
		$default_networks = fl_social_networks_defaults();

		// Merge saved networks with defaults, preserving all saved customizations (colors, icons, etc.)
		// IMPORTANT: wp_parse_args($saved, $defaults) - saved values take precedence (correct order)
		$fl_social_networks = array();
		foreach ( $default_networks as $network_id => $default_network ) {
			if ( isset( $saved_networks[ $network_id ] ) && is_array( $saved_networks[ $network_id ] ) ) {
				// Merge: saved values override defaults, but defaults fill in missing keys
				// This preserves saved colors even if they're empty strings (they won't be overwritten)
				$fl_social_networks[ $network_id ] = wp_parse_args( $saved_networks[ $network_id ], $default_network );
			} else {
				// Use default if no saved data for this network
				$fl_social_networks[ $network_id ] = $default_network;
			}
		}

		// Also include any saved networks that might not be in defaults (for backward compatibility)
		foreach ( $saved_networks as $network_id => $saved_network ) {
			if ( ! isset( $fl_social_networks[ $network_id ] ) ) {
				$fl_social_networks[ $network_id ] = is_array( $saved_network ) ? $saved_network : array();
			}
		}

		// Reorder networks according to saved sort order if available
		if ( isset( $fl_social_icons_settings['sort'] ) && is_array( $fl_social_icons_settings['sort'] ) ) {
			$ordered_networks = array();
			foreach ( $fl_social_icons_settings['sort'] as $network_id ) {
				if ( isset( $fl_social_networks[ $network_id ] ) ) {
					$ordered_networks[ $network_id ] = $fl_social_networks[ $network_id ];
				}
			}
			// Add any missing networks (new ones) at the end
			foreach ( $fl_social_networks as $network_id => $network ) {
				if ( ! isset( $ordered_networks[ $network_id ] ) ) {
					$ordered_networks[ $network_id ] = $network;
				}
			}
			$fl_social_networks = $ordered_networks;
		}

		$fl_social_icons_settings['networks'] = $fl_social_networks;

		return $fl_social_icons_settings;
	}
}

/**
 * Prevent saving social icon settings for free users only.
 * Premium users can save all social icons customizations (icons, colors, position).
 * Upsell notification is handled in Customizer controls frame via JavaScript.
 *
 * @param mixed $new_value The new option value.
 * @param mixed $old_value The old option value.
 * @return mixed Filtered option value.
 */
add_filter(
	'pre_update_option_fl_settings',
	function ( $new_value, $old_value ) {
		// CRITICAL: WordPress Customizer may send partial data when saving nested paths
		// We must merge $new_value with $old_value to preserve all other settings
		$old_settings = is_array( $old_value ) ? $old_value : array();
		$new_value    = is_array( $new_value ) ? $new_value : array();

		// Merge top-level: preserve all old settings, update with new ones
		$final_value = wp_parse_args( $new_value, $old_settings );

		// Only block saves for free build users. Premium build users can save all changes.
		if ( function_exists( 'fl_fs' ) && ! fl_fs()->is__premium_only() ) {
			if ( isset( $final_value['social_icons'] ) && isset( $new_value['social_icons'] ) ) {
				// Free users: Allow functional settings, block premium design customizations
				$old_social_icons = isset( $old_settings['social_icons'] ) ? $old_settings['social_icons'] : array();
				$new_social_icons = $new_value['social_icons'];

				// Start with old values (blocks everything by default)
				$final_value['social_icons'] = $old_social_icons;

				// Whitelist: Allow these basic functional settings to be saved
				$allowed_basic_settings = array( 'enable_minimizer', 'type', 'bar_position' );
				foreach ( $allowed_basic_settings as $key ) {
					if ( isset( $new_social_icons[ $key ] ) ) {
						$final_value['social_icons'][ $key ] = $new_social_icons[ $key ];
					}
				}

				// Whitelist: Allow URL keys (facebook_url, twitter_url, linkedin_url, etc.)
				// These are functional settings, not design customizations
				foreach ( $new_social_icons as $key => $value ) {
					if ( preg_match( '/_url$/', $key ) ) {
						$final_value['social_icons'][ $key ] = $value;
					}
				}

				// Whitelist: Allow enable/disable toggles for networks (but not design customizations)
				if ( isset( $new_social_icons['networks'] ) && is_array( $new_social_icons['networks'] ) ) {
					// Ensure networks array exists in final value
					if ( ! isset( $final_value['social_icons']['networks'] ) ) {
						$final_value['social_icons']['networks'] = array();
					}

					// Preserve old network data
					$old_networks = isset( $old_social_icons['networks'] ) ? $old_social_icons['networks'] : array();
					$new_networks = $new_social_icons['networks'];

					foreach ( $new_networks as $network_id => $network_data ) {
						// Only allow 'enabled' toggle changes for free users
						// All other network properties (colors, icons, etc.) remain unchanged
						if ( isset( $old_networks[ $network_id ] ) ) {
							// Start with old data
							$final_value['social_icons']['networks'][ $network_id ] = $old_networks[ $network_id ];

							// Allow only the 'enabled' field to be updated
							if ( isset( $network_data['enabled'] ) ) {
								$final_value['social_icons']['networks'][ $network_id ]['enabled'] = $network_data['enabled'];
							}
						}
					}
				}

				// Preserve sort order if it exists in old data (don't allow changes for free users)
				if ( isset( $old_social_icons['sort'] ) ) {
					$final_value['social_icons']['sort'] = $old_social_icons['sort'];
				}
			}
		} else {

			// Ensure base structure exists
			$final_value['social_icons']             = $final_value['social_icons'] ?? ( $old_settings['social_icons'] ?? array() );
			$final_value['social_icons']['networks'] = $final_value['social_icons']['networks'] ?? array();

			// Actual DB-saved networks (not cached)
			$actual_db    = get_option( 'fl_settings', array() );
			$old_networks = $actual_db['social_icons']['networks'] ?? array();

			$merged   = $old_networks;
			$new      = $final_value['social_icons']['networks'];
			$defaults = function_exists( 'fl_social_networks_defaults' ) ? fl_social_networks_defaults() : array();

			// Detect bulk reload
			$new_count   = count( $new );
			$total       = count( $defaults );
			$all_default = true;
			$has_custom  = false;

			foreach ( $new as $id => $item ) {

				$def   = $defaults[ $id ]['icon'] ?? '';
				$saved = $old_networks[ $id ]['icon'] ?? '';

				if ( ( $item['icon'] ?? '' ) !== $def ) {
					$all_default = false;
				}
				if ( ! empty( $saved ) && $saved !== $def ) {
					$has_custom = true;
				}
			}

			$is_reload = ( $new_count === $total ) && $all_default && $has_custom && $total > 0;

			// Merge new values
			foreach ( $new as $id => $fields ) {

				if ( ! isset( $merged[ $id ] ) ) {
					$merged[ $id ] = $fields;
					continue;
				}

				foreach ( $fields as $key => $value ) {

					$old = $merged[ $id ][ $key ] ?? '';
					$def = $defaults[ $id ][ $key ] ?? '';

					// Real user change → save
					if ( $value !== $old ) {

						// Block only when bulk reload tries to force default on custom
						if ( $is_reload && $key === 'icon' && $value === $def && $old !== $def ) {
							continue;
						}

						$merged[ $id ][ $key ] = $value;
					}
				}
			}

			$final_value['social_icons']['networks'] = $merged;
		}
		// Return merged value
		return $final_value;
	},
	10,
	2
);
/*
* Create default array of social icons
*/
if ( ! function_exists( 'fl_social_icons_defaults' ) ) {
	function fl_social_icons_defaults() {
		$defaults = array(
			'enable_minimizer' => 'on',
			'type'             => 'bar',
			'bar_position'     => 'left',
		);
		return apply_filters( 'fl_social_icons_defaults', $defaults );
	}
}

/*
* Create default array of social icons
*/
if ( ! function_exists( 'fl_social_networks_defaults' ) ) {
	function fl_social_networks_defaults() {

		$defaults = array(
			'facebook'   => array(
				'id'      => 'facebook',
				'name'    => 'Facebook',
				'icon'    => 'fa fa-facebook',
				'enabled' => 'on',
				'tooltip' => 'Facebook',
			),
			'twitter'    => array(
				'id'      => 'twitter',
				'name'    => 'X',
				'icon'    => 'svg',
				'enabled' => 'on',
				'tooltip' => 'Twitter',
			),
			'linkedin'   => array(
				'id'      => 'linkedin',
				'name'    => 'Linkedin',
				'icon'    => 'fa fa-linkedin',
				'enabled' => 'on',
				'tooltip' => 'Linkedin',
			),
			'pinterest'  => array(
				'id'      => 'pinterest',
				'name'    => 'Pinterest',
				'icon'    => 'fa fa-pinterest-p',
				'enabled' => 'on',
				'tooltip' => 'Pinterest',
			),
			'whatsapp'   => array(
				'id'      => 'whatsapp',
				'name'    => 'WhatsApp',
				'icon'    => 'fa fa-whatsapp',
				'enabled' => 'on',
				'tooltip' => 'WhatsApp',
			),
			'reddit'     => array(
				'id'      => 'reddit',
				'name'    => 'Reddit',
				'icon'    => 'fa fa-reddit-alien',
				'enabled' => 'on',
				'tooltip' => 'Reddit',
			),
			'googleplus' => array(
				'id'      => 'googleplus',
				'name'    => 'Google+',
				'icon'    => 'fa fa-google-plus',
				'enabled' => 'on',
				'tooltip' => 'Google+',
			),
			'youtube'    => array(
				'id'      => 'youtube',
				'name'    => 'YouTube',
				'icon'    => 'fa fa-youtube-play',
				'enabled' => 'on',
				'tooltip' => 'YouTube',
			),
		);

		return apply_filters( 'fl_social_networks_defaults', $defaults );
	}
}

/*
* Create social sharing link
*/
if ( ! function_exists( 'fl_social_share_url' ) ) {
	function fl_social_share_url( $network ) {

		$fl_social_share_url = '';

		// Load settings so custom social URLs can be used
		$fl_settings = get_option( 'fl_settings', array() );

		$fl_permalink = ( class_exists( 'WooCommerce' ) && is_checkout() || fl_is_homepage() ) ? get_bloginfo( 'url' ) : get_permalink();

		if ( class_exists( 'BuddyPress' ) && is_buddypress() ) {

			$fl_permalink = bp_get_requested_url();
		}

		$fl_permalink = rawurlencode( $fl_permalink );

		$title = class_exists( 'WooCommerce' ) && is_checkout() || fl_is_homepage() ? get_bloginfo( 'name' ) : get_the_title();

		$title = rawurlencode( wp_strip_all_tags( html_entity_decode( $title, ENT_QUOTES, 'UTF-8' ) ) );

		switch ( $network ) {

			case 'facebook':
				$custom_url = '';
				if ( isset( $fl_settings['social_icons']['facebook_url'] ) && ! empty( $fl_settings['social_icons']['facebook_url'] ) ) {
					$custom_url = esc_url( $fl_settings['social_icons']['facebook_url'] );
				}
				$fl_social_share_url = $custom_url ? $custom_url : add_query_arg(
					array(
						'u' => $fl_permalink,
						't' => $title,
					),
					'http://www.facebook.com/sharer.php'
				);

				break;

			case 'twitter':
				$custom_url = '';
				if ( isset( $fl_settings['social_icons']['twitter_url'] ) && ! empty( $fl_settings['social_icons']['twitter_url'] ) ) {
					$custom_url = esc_url( $fl_settings['social_icons']['twitter_url'] );
				}
				$fl_social_share_url = $custom_url ? $custom_url : add_query_arg(
					array(
						'text' => $title,
						'url'  => $fl_permalink,
					),
					'http://twitter.com/share'
				);

				break;

			case 'linkedin':
				$custom_url = '';
				if ( isset( $fl_settings['social_icons']['linkedin_url'] ) && ! empty( $fl_settings['social_icons']['linkedin_url'] ) ) {
					$custom_url = esc_url( $fl_settings['social_icons']['linkedin_url'] );
				}
				$fl_social_share_url = $custom_url ? $custom_url : add_query_arg(
					array(
						'mini'  => 'true',
						'url'   => $fl_permalink,
						'title' => $title,
					),
					'http://www.linkedin.com/shareArticle'
				);
				break;

			case 'googleplus':
				$custom_url = '';
				if ( isset( $fl_settings['social_icons']['googleplus_url'] ) && ! empty( $fl_settings['social_icons']['googleplus_url'] ) ) {
					$custom_url = esc_url( $fl_settings['social_icons']['googleplus_url'] );
				}
				$fl_social_share_url = $custom_url ? $custom_url : add_query_arg(
					array(
						'url' => $fl_permalink,
					),
					'https://plus.google.com/share'
				);
				break;

			case 'pinterest':
				$custom_url = '';
				if ( isset( $fl_settings['social_icons']['pinterest_url'] ) && ! empty( $fl_settings['social_icons']['pinterest_url'] ) ) {
					$custom_url = esc_url( $fl_settings['social_icons']['pinterest_url'] );
				}
				$fl_social_share_url = $custom_url ? $custom_url : add_query_arg(
					array(
						'url'         => $fl_permalink,
						'description' => $title,
					),
					'https://pinterest.com/pin/create/button/'
				);
				break;

			case 'whatsapp':
				$custom_url = '';
				if ( isset( $fl_settings['social_icons']['whatsapp_url'] ) && ! empty( $fl_settings['social_icons']['whatsapp_url'] ) ) {
					$custom_url = esc_url( $fl_settings['social_icons']['whatsapp_url'] );
				}
				$fl_social_share_url = $custom_url ? $custom_url : 'https://api.whatsapp.com/send?' . http_build_query(
					array(
						'text' => $title . ' ' . $fl_permalink,
					)
				);
				break;

			case 'reddit':
				$custom_url = '';
				if ( isset( $fl_settings['social_icons']['reddit_url'] ) && ! empty( $fl_settings['social_icons']['reddit_url'] ) ) {
					$custom_url = esc_url( $fl_settings['social_icons']['reddit_url'] );
				}
				$fl_social_share_url = $custom_url ? $custom_url : add_query_arg(
					array(
						'url'   => $fl_permalink,
						'title' => $title,
					),
					'http://www.reddit.com/submit'
				);
				break;

			case 'youtube':
				$youtube_url = '';
				if ( isset( $fl_settings['social_icons']['youtube_url'] ) && ! empty( $fl_settings['social_icons']['youtube_url'] ) ) {
					$youtube_url = esc_url( $fl_settings['social_icons']['youtube_url'] );
				}
				$fl_social_share_url = $youtube_url ? $youtube_url : 'https://www.youtube.com/';
				break;

			default:
				$fl_social_share_url = add_query_arg(
					array(
						'u' => $fl_permalink,
						't' => $title,
					),
					'http://www.facebook.com/sharer.php'
				);
				break;
		}

		return $fl_social_share_url;
	}
}


/*
* Check if home or frontpage
*/
if ( ! function_exists( 'fl_is_homepage' ) ) {
	function fl_is_homepage() {

		return is_front_page() || is_home();
	}
}

if ( ! function_exists( 'fl_get_customizer_url' ) ) {
	/**
	 * Get the customizer url
	 *
	 *
	 * @return string
	 * @since 1.0.0
	 */
	function fl_get_customizer_url() {

		$url          = null;
		$recent_posts = wp_get_recent_posts( array( 'posts_per_page' => 1 ) );

		if ( isset( $recent_posts['0'] ) ) {
			$first_post_url = get_permalink( $recent_posts['0']['ID'] );
			$url            = add_query_arg(
				array(
					'url'              => urlencode( $first_post_url ),
					'autofocus[panel]' => 'fl_customizer_panel',
				),
				admin_url( 'customize.php' )
			);
		}
		return $url;
	}
}

if ( ! function_exists( 'fl_get_sort_order' ) ) {
	/**
	 * Get the sort order
	 *
	 *
	 * @return string
	 * @since 1.0.0
	 */
	function fl_get_sort_order( $module = 'links' ) {

		$settings   = get_option( 'fl_settings', false );
		$sort_order = 'fl_next,fl_prev,fl_random,fl_top,fl_bottom,fl_home,fl_copy_url';

		if ( $module == 'links' && isset( $settings['fl_sort'] ) && ! empty( $settings['fl_sort'] ) ) {
			$sort_order = $settings['fl_sort'];
		}

		$array = explode( ',', $sort_order );

		// Find the key and remove 'fl_minimizer'
		if ( ( $key = array_search( 'fl_minimizer', $array ) ) !== false ) {
			unset( $array[ $key ] );
		}

		// Filter out empty values and reindex array
		$array = array_filter( $array, 'strlen' );
		$array = array_values( $array );

		// Convert array back to string
		$sort_order = implode( ',', $array );

		// Ensure we always return a valid sort order
		if ( empty( $sort_order ) ) {
			$sort_order = 'fl_next,fl_prev,fl_random,fl_top,fl_bottom,fl_home,fl_copy_url';
		}

		if ( $module == 'social' ) {
			if ( isset( $settings['social_icons']['sort'] ) && ! empty( $settings['social_icons']['sort'] ) ) {
				$sort_order = $settings['social_icons']['sort'];
			} else {
				$sort_order = 'facebook,twitter,linkedin';
			}
		}
		return $sort_order;
	}
}
