<?php
/**
 * Theme helpers and sanitizers.
 *
 * @package ttsunsolar
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Theme image URL helper.
 *
 * @param string $filename Image file name inside solarkit/images.
 * @return string
 */
function ttsunsolar_image_uri( $filename ) {
	return trailingslashit( TTSUNSOLAR_URI ) . 'solarkit/images/' . ltrim( $filename, '/' );
}

/**
 * Theme mod with empty-string fallback to default.
 *
 * @param string $key     Setting key.
 * @param mixed  $default Default value.
 * @return mixed
 */
function ttsunsolar_mod( $key, $default = '' ) {
	$value = get_theme_mod( $key, $default );
	if ( is_string( $value ) && '' === trim( $value ) ) {
		return $default;
	}
	return $value;
}

/**
 * Social network URLs (defaults keep preview populated).
 *
 * @return array
 */
function ttsunsolar_get_social_links() {
	return array(
		'facebook'  => ttsunsolar_mod( 'ttsunsolar_facebook', 'https://www.facebook.com/' ),
		'twitter'   => ttsunsolar_mod( 'ttsunsolar_twitter', 'https://twitter.com/' ),
		'linkedin'  => ttsunsolar_mod( 'ttsunsolar_linkedin', 'https://www.linkedin.com/' ),
		'pinterest' => ttsunsolar_mod( 'ttsunsolar_pinterest', 'https://www.pinterest.com/' ),
		'instagram' => ttsunsolar_mod( 'ttsunsolar_instagram', 'https://www.instagram.com/' ),
	);
}

/**
 * Font Awesome class for a social network.
 *
 * @param string $network Network key.
 * @return string
 */
function ttsunsolar_social_icon_class( $network ) {
	$map = array(
		'facebook'  => 'fa-brands fa-facebook-f',
		'twitter'   => 'fa-brands fa-x-twitter',
		'linkedin'  => 'fa-brands fa-linkedin-in',
		'pinterest' => 'fa-brands fa-pinterest-p',
		'instagram' => 'fa-brands fa-instagram',
	);
	return isset( $map[ $network ] ) ? $map[ $network ] : 'fa-solid fa-link';
}

/**
 * Sanitize checkbox / hide toggle.
 *
 * @param mixed $checked Raw value.
 * @return bool
 */
function ttsunsolar_sanitize_checkbox( $checked ) {
	return (bool) $checked;
}

/**
 * Sanitize phone-ish text.
 *
 * @param string $phone Phone string.
 * @return string
 */
function ttsunsolar_sanitize_phone( $phone ) {
	return preg_replace( '/[^\d+\-\s().]/', '', (string) $phone );
}

/**
 * Sanitize published page ID.
 *
 * @param int                  $page_id Page ID.
 * @param WP_Customize_Setting $setting Setting.
 * @return int
 */
function ttsunsolar_sanitize_page( $page_id, $setting ) {
	$page_id = absint( $page_id );
	return ( 'publish' === get_post_status( $page_id ) ) ? $page_id : $setting->default;
}

/**
 * Build tel: href.
 *
 * @param string $phone Phone number.
 * @return string
 */
function ttsunsolar_tel_href( $phone ) {
	$digits = preg_replace( '/[^\d+]/', '', (string) $phone );
	return $digits ? 'tel:' . $digits : '';
}

/**
 * Whether Solar Services section should render.
 *
 * @return bool
 */
function ttsunsolar_show_services_section() {
	return ! (bool) get_theme_mod( 'ttsunsolar_hide_services', false );
}

/**
 * Default service card data for empty Customizer pages.
 *
 * @return array[]
 */
function ttsunsolar_default_services() {
	return array(
		array(
			'title'   => __( 'Residential Solar', 'ttsunsolar' ),
			'excerpt' => __( 'Rooftop solar systems sized for family homes with clean installs and clear savings.', 'ttsunsolar' ),
			'image'   => ttsunsolar_image_uri( 'service-residential.jpg' ),
			'url'     => home_url( '/' ),
		),
		array(
			'title'   => __( 'Commercial Solar', 'ttsunsolar' ),
			'excerpt' => __( 'Scalable solar for offices, warehouses, and business campuses.', 'ttsunsolar' ),
			'image'   => ttsunsolar_image_uri( 'service-commercial.jpg' ),
			'url'     => home_url( '/' ),
		),
		array(
			'title'   => __( 'Battery Storage', 'ttsunsolar' ),
			'excerpt' => __( 'Store daytime energy and keep essential loads powered after sunset.', 'ttsunsolar' ),
			'image'   => ttsunsolar_image_uri( 'service-battery.jpg' ),
			'url'     => home_url( '/' ),
		),
		array(
			'title'   => __( 'EV Charging', 'ttsunsolar' ),
			'excerpt' => __( 'Home and workplace charging paired with solar for lower fuel costs.', 'ttsunsolar' ),
			'image'   => ttsunsolar_image_uri( 'service-ev.jpg' ),
			'url'     => home_url( '/' ),
		),
	);
}

/**
 * Collect Solar Services cards from Customizer page picks or defaults.
 *
 * @return array[]
 */
function ttsunsolar_get_services_cards() {
	$cards = array();

	for ( $i = 1; $i <= 4; $i++ ) {
		$page_id = absint( get_theme_mod( 'ttsunsolar_service_' . $i, 0 ) );
		if ( $page_id < 1 ) {
			continue;
		}

		$query = new WP_Query(
			array(
				'page_id'         => $page_id,
				'post_status'     => 'publish',
				'posts_per_page'  => 1,
				'no_found_rows'   => true,
			)
		);

		if ( ! $query->have_posts() ) {
			wp_reset_postdata();
			continue;
		}

		$query->the_post();
		$image = get_the_post_thumbnail_url( get_the_ID(), 'medium_large' );
		if ( ! $image ) {
			$defaults = ttsunsolar_default_services();
			$image    = isset( $defaults[ $i - 1 ]['image'] ) ? $defaults[ $i - 1 ]['image'] : ttsunsolar_image_uri( 'service-residential.jpg' );
		}

		$cards[] = array(
			'title'   => get_the_title(),
			'excerpt' => wp_trim_words( wp_strip_all_tags( get_the_excerpt() ? get_the_excerpt() : get_the_content() ), 18 ),
			'image'   => $image,
			'url'     => get_permalink(),
		);
		wp_reset_postdata();
	}

	if ( empty( $cards ) ) {
		return ttsunsolar_default_services();
	}

	return $cards;
}

/**
 * Default brand name used when Site Identity title is empty (logo place).
 *
 * @return string
 */
function ttsunsolar_default_site_name() {
	return __( 'TTSun Solar', 'ttsunsolar' );
}

/**
 * Default brand tagline used when Site Identity tagline is empty.
 *
 * @return string
 */
function ttsunsolar_default_site_tagline() {
	return __( 'Clean Energy Solutions', 'ttsunsolar' );
}

/**
 * Display name for header logo place.
 * Falls back to "TTSun Solar" when the site title is empty.
 *
 * @return string
 */
function ttsunsolar_get_site_name() {
	$name = trim( wp_strip_all_tags( (string) get_bloginfo( 'name', 'display' ) ) );
	if ( '' === $name ) {
		return ttsunsolar_default_site_name();
	}
	return $name;
}

/**
 * Display tagline for header.
 * Falls back to "Clean Energy Solutions" when empty.
 *
 * @return string
 */
function ttsunsolar_get_site_tagline() {
	$tagline = trim( wp_strip_all_tags( (string) get_bloginfo( 'description', 'display' ) ) );
	if ( '' === $tagline ) {
		return ttsunsolar_default_site_tagline();
	}
	return $tagline;
}

/**
 * Whether homepage sections should render on the front page.
 *
 * @return bool
 */
function ttsunsolar_show_homepage_sections() {
	return is_front_page();
}

/**
 * Whether the inner page banner should render.
 *
 * @return bool
 */
function ttsunsolar_show_inner_banner() {
	return ! is_front_page();
}

/**
 * Inner banner image URL.
 *
 * @return string
 */
function ttsunsolar_get_inner_banner_image() {
	$image = get_theme_mod( 'ttsunsolar_inner_banner_image', '' );
	if ( ! $image ) {
		$image = ttsunsolar_image_uri( 'inner-banner.jpg' );
	}
	return $image;
}

/**
 * Inner banner title for the current view.
 *
 * @return string
 */
function ttsunsolar_get_inner_banner_title() {
	if ( is_404() ) {
		return __( 'Page not found', 'ttsunsolar' );
	}
	if ( is_search() ) {
		return sprintf(
			/* translators: %s: search query */
			__( 'Search Results for: %s', 'ttsunsolar' ),
			get_search_query()
		);
	}
	if ( is_home() && ! is_front_page() ) {
		$posts_page = (int) get_option( 'page_for_posts' );
		if ( $posts_page ) {
			return get_the_title( $posts_page );
		}
		return __( 'Blog', 'ttsunsolar' );
	}
	if ( is_archive() ) {
		return wp_strip_all_tags( get_the_archive_title() );
	}
	if ( is_singular() ) {
		return get_the_title();
	}
	return wp_get_document_title();
}

/**
 * Whether templates should hide the duplicate entry H1.
 * Titles stay in content; banner is image-only.
 *
 * @return bool
 */
function ttsunsolar_hide_entry_title() {
	return false;
}

/**
 * Render styled posts pagination.
 */
function ttsunsolar_posts_pagination() {
	the_posts_pagination(
		array(
			'mid_size'           => 2,
			'prev_text'          => '&lsaquo; ' . esc_html__( 'Prev', 'ttsunsolar' ),
			'next_text'          => esc_html__( 'Next', 'ttsunsolar' ) . ' &rsaquo;',
			'screen_reader_text' => esc_html__( 'Posts navigation', 'ttsunsolar' ),
			'class'              => 'ttsunsolar-pagination',
		)
	);
}

/**
 * Homepage banner data (single image).
 *
 * @return array
 */
function ttsunsolar_get_banner_data() {
	$image = get_theme_mod( 'ttsunsolar_banner_image', '' );
	if ( ! $image && function_exists( 'get_header_image' ) ) {
		$image = get_header_image();
	}
	if ( ! $image ) {
		$image = ttsunsolar_image_uri( 'slider-1.jpg' );
	}

	$tagline = ttsunsolar_mod( 'ttsunsolar_banner_tagline', __( 'Reliable clean energy', 'ttsunsolar' ) );
	$title   = ttsunsolar_mod( 'ttsunsolar_banner_title', __( 'Lower bills, backup power, and a cleaner grid.', 'ttsunsolar' ) );
	$button  = ttsunsolar_mod( 'ttsunsolar_banner_button', __( 'See More', 'ttsunsolar' ) );
	$url     = get_theme_mod( 'ttsunsolar_banner_url', '' );

	if ( ! $url ) {
		$url = home_url( '/' );
	}

	return array(
		'image'   => $image,
		'tagline' => $tagline,
		'title'   => $title,
		'button'  => $button,
		'url'     => $url,
	);
}

/**
 * Footer recent posts (real posts or demo cards).
 *
 * @param int $count Number of posts.
 * @return array[]
 */
function ttsunsolar_get_footer_posts( $count = 2 ) {
	$query = new WP_Query(
		array(
			'post_type'           => 'post',
			'posts_per_page'      => absint( $count ),
			'ignore_sticky_posts' => true,
			'no_found_rows'       => true,
		)
	);

	$items = array();
	if ( $query->have_posts() ) {
		while ( $query->have_posts() ) {
			$query->the_post();
			$image = get_the_post_thumbnail_url( get_the_ID(), 'thumbnail' );
			$items[] = array(
				'title'   => get_the_title(),
				'excerpt' => wp_trim_words( wp_strip_all_tags( get_the_excerpt() ? get_the_excerpt() : get_the_content() ), 12 ),
				'image'   => $image ? $image : ttsunsolar_image_uri( 'footer-post-1.jpg' ),
				'url'     => get_permalink(),
			);
		}
		wp_reset_postdata();
	}

	if ( ! empty( $items ) ) {
		return $items;
	}

	return array(
		array(
			'title'   => __( 'When Battery Storage Makes Sense', 'ttsunsolar' ),
			'excerpt' => __( 'Backup power and energy independence for modern homes.', 'ttsunsolar' ),
			'image'   => ttsunsolar_image_uri( 'footer-post-1.jpg' ),
			'url'     => home_url( '/' ),
		),
		array(
			'title'   => __( 'Solar Benefits for Commercial Buildings', 'ttsunsolar' ),
			'excerpt' => __( 'Stabilize costs and advance sustainability goals.', 'ttsunsolar' ),
			'image'   => ttsunsolar_image_uri( 'footer-post-2.jpg' ),
			'url'     => home_url( '/' ),
		),
	);
}

/**
 * Footer links fallback matching demo structure.
 */
function ttsunsolar_fallback_footer_menu() {
	$links = array(
		__( 'Home', 'ttsunsolar' )       => home_url( '/' ),
		__( 'About Us', 'ttsunsolar' )   => home_url( '/' ),
		__( 'Services', 'ttsunsolar' )   => home_url( '/#services' ),
		__( 'Projects', 'ttsunsolar' )   => home_url( '/' ),
		__( 'Contact Us', 'ttsunsolar' ) => home_url( '/' ),
	);
	echo '<ul class="footer-links">';
	foreach ( $links as $label => $url ) {
		echo '<li><a href="' . esc_url( $url ) . '">' . esc_html( $label ) . '</a></li>';
	}
	echo '</ul>';
}

/**
 * Primary menu fallback.
 */
function ttsunsolar_fallback_menu() {
	echo '<ul class="main-nav__list menu">';
	wp_list_pages(
		array(
			'title_li' => '',
			'depth'    => 1,
		)
	);
	echo '</ul>';
}

/**
 * Render footer copyright + credit link.
 */
function ttsunsolar_render_footer_copyright() {
	$copy = get_theme_mod( 'ttsunsolar_copyright', '' );
	if ( '' === trim( (string) $copy ) ) {
		$copy = sprintf(
			/* translators: 1: year, 2: site name */
			__( '© %1$s %2$s. All rights reserved.', 'ttsunsolar' ),
			gmdate( 'Y' ),
			get_bloginfo( 'name' )
		);
	}

	$credit_text = get_theme_mod( 'ttsunsolar_credit_text', __( 'Theme by ThemesTulip', 'ttsunsolar' ) );
	$credit_url  = get_theme_mod( 'ttsunsolar_credit_url', TTSUNSOLAR_VENDOR_URL );
	if ( '' === trim( (string) $credit_text ) ) {
		$credit_text = __( 'Theme by ThemesTulip', 'ttsunsolar' );
	}
	if ( '' === trim( (string) $credit_url ) ) {
		$credit_url = TTSUNSOLAR_VENDOR_URL;
	}

	echo '<p class="footer-copyright">';
	echo esc_html( $copy );

	if ( $credit_text ) {
		echo ' <span class="footer-copyright__sep" aria-hidden="true">|</span> ';
		if ( $credit_url ) {
			echo '<a class="footer-copyright__credit" href="' . esc_url( $credit_url ) . '" target="_blank" rel="noopener noreferrer">' . esc_html( $credit_text ) . '</a>';
		} else {
			echo '<span class="footer-copyright__credit">' . esc_html( $credit_text ) . '</span>';
		}
	}

	echo '</p>';
}
