<?php
/**
 * Social Media Links Partial
 *
 * @package KsPortfolio
 */

namespace KsPortfolio;

$args    = $args ?? array();
$classes = $args['classes'] ?? '';
$circle  = $args['circle'] ?? '';

// Get social media repeater data
$social_media_items = get_field( 'social_media', 'option' );

// Add circle class if the circle option is enabled
if ( $circle ) {
	$classes .= ' circular-icon';
}

/**
 * Detect social media service from URL
 *
 * @param string $url The social media URL.
 * @return string The service name
 */
function detect_social_service( $url ) {
	$domain = wp_parse_url( $url, PHP_URL_HOST );
	$domain = strtolower( $domain );

	// Define domain patterns for each service
	$services = array(
		'facebook'  => array( 'facebook.com', 'fb.com' ),
		'instagram' => array( 'instagram.com' ),
		'twitter'   => array( 'twitter.com', 'x.com' ),
		'linkedin'  => array( 'linkedin.com' ),
		'github'    => array( 'github.com' ),
		'youtube'   => array( 'youtube.com', 'youtu.be' ),
		'pinterest' => array( 'pinterest.com' ),
        'gitea'     => array( 'gitea.com', 'keithsolomon.net', 'codeberg.org' ),
	);

	foreach ( $services as $service => $domains ) {
		foreach ( $domains as $service_domain ) {
			if ( strpos( $domain, $service_domain ) !== false ) {
				return $service;
			}
		}
	}

	return '';
}

// Loop through the social media repeater items and output links
if ( $social_media_items && is_array( $social_media_items ) ) {
	foreach ( $social_media_items as $item ) {
		$url = $item['url'] ?? '';

		if ( $url ) {
			$service = detect_social_service( $url );

			if ( $service ) {
				?>
				<a href="<?php echo esc_url( $url ); ?>" class="<?php echo esc_attr( $classes ); ?>">
					<?php get_template_part( 'views/icons/' . $service ); ?>
					<span class="sr-only bg-white text-black">Visit my <?php echo esc_html( $service ); ?> page</span>
				</a>
				<?php
			}
		}
	}
}
?>
