<?php

/**
 * CleanLogic Theme Customizer Class.
 *
 * @package cleanlogic
 */

if (! class_exists('CleanLogic_Theme_Customizer')) {
	class CleanLogic_Theme_Customizer
	{

		public function __construct()
		{
			add_action('customize_register', [$this, 'register']);

			// Live preview script (runs inside the preview iframe)
			add_action('customize_preview_init', [$this, 'enqueue_preview_js']);

			// Front-end CSS for saved color (normal page loads + after Publish reload)
			add_action('wp_enqueue_scripts', [$this, 'enqueue_front_styles'], 20);
		}

		public function register($wp_customize)
		{
			$this->site_identity_settings($wp_customize);
			$this->header_social_settings($wp_customize);
			$this->top_header_hide_show($wp_customize);
			$this->footer_social_settings($wp_customize);
			$this->footer_color_setting($wp_customize);
		}

		private function site_identity_settings($wp_customize)
		{
			$wp_customize->get_setting('blogname')->transport         = 'postMessage';
			$wp_customize->get_setting('blogdescription')->transport  = 'postMessage';
			$wp_customize->get_setting('header_textcolor')->transport = 'postMessage';

			$wp_customize->selective_refresh->add_partial('blogname', array(
				'selector'        => '.site-title a',
				'render_callback' => 'bloginfo_name_callback',
			));

			$wp_customize->selective_refresh->add_partial('blogdescription', array(
				'selector'        => '.site-description',
				'render_callback' => 'bloginfo_description_callback',
			));
		}

		private function header_social_settings($wp_customize)
		{
			$wp_customize->add_section('cleanlogic_header_social_settings', array(
				'title'       => __('Header', 'cleanlogic'),
				'priority'    => 1,
				'description' => __('Add social URLs and contact info to display in the header.', 'cleanlogic'),
			));

			// Contact Email
			$wp_customize->add_setting('cleanlogic_contact_email', array(
				'type'              => 'theme_mod',
				'sanitize_callback' => 'sanitize_email',
				'transport'         => 'postMessage',
			));
			$wp_customize->add_control('cleanlogic_contact_email', array(
				'label'       => __('Contact Email', 'cleanlogic'),
				'section'     => 'cleanlogic_header_social_settings',
				'type'        => 'email',
				'input_attrs' => array('placeholder' => 'enquiry@example.com'),
			));

			// Phone (tel: link)
			$wp_customize->add_setting('cleanlogic_contact_phone', array(
				'type'              => 'theme_mod',
				'sanitize_callback' => 'cleanlogic_sanitize_phone',
				'transport'         => 'postMessage',
			));
			$wp_customize->add_control('cleanlogic_contact_phone', array(
				'label'       => __('Phone (for tel: link)', 'cleanlogic'),
				'section'     => 'cleanlogic_header_social_settings',
				'type'        => 'text',
				'input_attrs' => array('placeholder' => '+919999999999'),
			));

			// Phone label
			$wp_customize->add_setting('cleanlogic_contact_phone_label', array(
				'type'              => 'theme_mod',
				'sanitize_callback' => 'sanitize_text_field',
				'transport'         => 'postMessage',
			));
			$wp_customize->add_control('cleanlogic_contact_phone_label', array(
				'label'       => __('Phone Label (display text)', 'cleanlogic'),
				'section'     => 'cleanlogic_header_social_settings',
				'type'        => 'text',
				'input_attrs' => array('placeholder' => '+91-999-999-9999'),
			));

			$socials = [
				'Facebook_header' => __('Facebook URL:', 'cleanlogic'),
				'Instagram_header'   => __('Instagram URL:', 'cleanlogic'),
				'Linkedin_header' => __('LinkedIn URL:', 'cleanlogic'),
				'Twitter_header'  => __('Twitter URL:', 'cleanlogic'),
			];

			foreach ($socials as $id => $label) {
				$wp_customize->add_setting($id, array(
					'type'              => 'theme_mod',
					'capability'        => 'edit_theme_options',
					'sanitize_callback' => 'esc_url_raw',
				));

				$wp_customize->add_control($id, array(
					'label'   => $label,
					'section' => 'cleanlogic_header_social_settings',
					'type'    => 'text',
				));
			}

			// Selective refresh for contact block
			if (isset($wp_customize->selective_refresh)) {
				$wp_customize->selective_refresh->add_partial('cleanlogic_top_header_contact', array(
					'selector'        => '.top_header_left',
					'render_callback' => 'cleanlogic_render_top_header_contact_partial',
				));
			}
		}

		private function top_header_hide_show($wp_customize)
		{
			$wp_customize->add_setting('top_header', array(
				'default'           => 2,
				'sanitize_callback' => 'absint',
			));

			$wp_customize->add_control(new CleanLogic_Toggle_Control($wp_customize, 'top_header-other', array(
				'label'       => __('Top Header', 'cleanlogic'),
				'description' => __('Hide/Show Top Header.', 'cleanlogic'),
				'section'     => 'cleanlogic_header_social_settings',
				'settings'    => 'top_header',
			)));
		}

		private function footer_social_settings($wp_customize)
		{
			$wp_customize->add_section('cleanlogic_footer_social_settings', array(
				'title'       => __('Footer', 'cleanlogic'),
				'priority'    => 3,
				'description' => __('Add social URLs to display icons in the footer.', 'cleanlogic'),
			));

			$socials = [
				'Facebook'    => __('Facebook URL:', 'cleanlogic'),
				'Instagram'   => __('Instgram URL:', 'cleanlogic'),
				'Linkedin'    => __('LinkedIn URL:', 'cleanlogic'),
				'Twitter'     => __('Twitter URL:', 'cleanlogic'),
			];

			foreach ($socials as $id => $label) {
				$wp_customize->add_setting($id, array(
					'type'              => 'theme_mod',
					'capability'        => 'edit_theme_options',
					'sanitize_callback' => 'esc_url_raw',
				));

				$wp_customize->add_control($id, array(
					'label'   => $label,
					'section' => 'cleanlogic_footer_social_settings',
					'type'    => 'text',
				));
			}
		}

		private function footer_color_setting($wp_customize)
		{
			$wp_customize->add_setting('footer_bg_color', array(
				'default'           => '#1a2942',
				'sanitize_callback' => 'sanitize_hex_color',
				'capability'        => 'edit_theme_options',
				'type'              => 'theme_mod',
				'transport'         => 'postMessage', // <<< REQUIRED for live preview
			));

			$wp_customize->add_control(new WP_Customize_Color_Control($wp_customize, 'footer_bg_color', array(
				'label'    => __('Footer Background Color', 'cleanlogic'),
				'section'  => 'cleanlogic_footer_social_settings',
				'settings' => 'footer_bg_color',
			)));
		}

		public function enqueue_preview_js()
		{
			$path = 'assets/js/customizer.js';
			$src  = get_theme_file_uri($path);
			$ver  = file_exists(get_theme_file_path($path)) ? filemtime(get_theme_file_path($path)) : '20240624';

			wp_enqueue_script(
				'cleanlogic-customizer',
				$src,
				['customize-preview', 'jquery'],
				$ver,
				true
			);
		}

		/**
		 * Prints saved color on normal loads (in <head>) using wp_add_inline_style.
		 * This ensures the saved color applies after Publish and outside the Customizer.
		 */
		public function enqueue_front_styles()
		{
			// Enqueue main stylesheet (safe even if already enqueued elsewhere)
			if (! wp_style_is('cleanlogic-style', 'enqueued')) {
				wp_enqueue_style(
					'cleanlogic-style',
					get_stylesheet_uri(),
					[],
					wp_get_theme()->get('Version')
				);
			}

			$color = sanitize_hex_color(get_theme_mod('footer_bg_color', ''));
			if (! $color) {
				return;
			}

			// Matches your footer markup: <footer id="colophon" class="site-footer" ...>
			$selectors = '#colophon, footer.site-footer, .site-info';
			$css = sprintf( '%s { background-color: %s; }',$selectors, $color );

			wp_add_inline_style('cleanlogic-style', $css);
		}
	}
}

// Initialize
new CleanLogic_Theme_Customizer();

// Partial render callbacks
function bloginfo_name_callback()
{
	bloginfo('name');
}
function bloginfo_description_callback()
{
	bloginfo('description');
}

function cleanlogic_sanitize_phone($value)
{
	$value = trim((string) $value);
	// allow only digits, keep a single leading +
	$value = preg_replace('/(?!^\+)[^\d]/', '', $value);
	return $value;
}


function cleanlogic_get_top_header_contact_html()
{
	$email			= 	get_theme_mod('cleanlogic_contact_email', '');
	$email_safe		= 	is_email($email) ? $email : '';
	$raw_phone   	=   get_theme_mod('cleanlogic_contact_phone', '');
	$phone_link		= 	cleanlogic_sanitize_phone($raw_phone);
	$phone_label	= 	sanitize_text_field(get_theme_mod('cleanlogic_contact_phone_label', ''));
	$mail_icon		= 	get_template_directory_uri() . '/assets/images/mail-fill.svg';
	$phone_icon		= 	get_template_directory_uri() . '/assets/images/phone-fill.svg';

	ob_start(); ?>
	<ul>
		<?php if ($email_safe) : ?>
			<li class="contact-email">
				<a href="<?php echo esc_url('mailto:' . antispambot($email_safe)); ?>">
					<img src="<?php echo esc_url($mail_icon); ?>" alt="<?php esc_attr_e('email', 'cleanlogic'); ?>" width="<?php echo esc_attr(18); ?>" height="<?php echo esc_attr(12); ?>" />
					<span><?php echo esc_html(antispambot($email_safe)); ?></span>
				</a>
			</li>
		<?php endif; ?>

		<?php
		if ($phone_link) :
			$tel_href = 'tel:' . $phone_link; // tel URI allows digits and leading +
		?>
		<li class="contact-phone">
			<a href="<?php echo esc_url($tel_href); ?>">
				<img src="<?php echo esc_url($phone_icon); ?>" alt="<?php esc_attr_e('phone', 'cleanlogic'); ?>" width="<?php echo esc_attr(16); ?>" height="<?php echo esc_attr(16); ?>">
				<span><?php echo esc_html($phone_label ?: $phone_link); ?></span>
			</a>
			</li>
		<?php endif; ?>
		
	</ul>
<?php
	return trim(ob_get_clean());
}

function cleanlogic_render_top_header_contact_partial()
{
	$allowed = array(
		'ul'   => array('class' => true),
		'li'   => array('class' => true),
		'a'    => array('href' => true, 'class' => true, 'target' => true, 'rel' => true),
		'span' => array('class' => true),
		'img'  => array('src' => true, 'alt' => true, 'width' => true, 'height' => true, 'class' => true),
	);
	echo wp_kses(cleanlogic_get_top_header_contact_html(), $allowed);
}
