<?php

function cascapedia_st_jules_locale(): string {
	if ( function_exists( 'pll_current_language' ) ) {
		$lang = pll_current_language( 'slug' );
		if ( in_array( $lang, [ 'fr', 'en' ], true ) ) {
			return $lang;
		}
	}
	$path = parse_url( $_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH ) ?: '/';
	return str_starts_with( $path, '/en' ) ? 'en' : 'fr';
}

function cascapedia_st_jules_clean_text( ?string $value ): string {
	return html_entity_decode( (string) $value, ENT_QUOTES | ENT_HTML5, 'UTF-8' );
}

function cascapedia_st_jules_l( ?string $value ): array {
	$value = cascapedia_st_jules_clean_text( $value );
	return [ 'fr' => $value, 'en' => $value ];
}

function cascapedia_st_jules_image_data( mixed $image ): ?array {
	if ( empty( $image ) ) {
		return null;
	}
	$id = is_array( $image ) ? (int) ( $image['ID'] ?? $image['id'] ?? 0 ) : (int) $image;
	if ( ! $id ) {
		return null;
	}
	$src = wp_get_attachment_image_url( $id, 'full' );
	if ( ! $src ) {
		return null;
	}
	$meta = wp_get_attachment_metadata( $id );
	$alt = get_post_meta( $id, '_wp_attachment_image_alt', true ) ?: get_the_title( $id );
	return [
		'id' => $id,
		'src' => $src,
		'alt' => cascapedia_st_jules_l( $alt ),
		'width' => (int) ( $meta['width'] ?? 0 ),
		'height' => (int) ( $meta['height'] ?? 0 ),
	];
}

function cascapedia_st_jules_link_data( array $row, string $prefix = 'cta' ): ?array {
	$url = (string) ( $row[ $prefix . '_url' ] ?? '' );
	$label = (string) ( $row[ $prefix . '_label' ] ?? '' );
	if ( ! $url || ! $label ) {
		return null;
	}
	return [
		'label' => cascapedia_st_jules_l( $label ),
		'href' => $url,
		'external' => ! empty( $row[ $prefix . '_external' ] ),
	];
}

function cascapedia_st_jules_get_documents(): array {
	$lang = cascapedia_st_jules_locale();
	$posts = get_posts([
		'post_type' => 'document',
		'post_status' => 'publish',
		'posts_per_page' => -1,
		'orderby' => [ 'menu_order' => 'ASC', 'title' => 'ASC' ],
		'lang' => $lang,
	]);
	$groups = [];
	foreach ( $posts as $post ) {
		$terms = get_the_terms( $post, 'document_category' );
		$group = ( ! is_wp_error( $terms ) && ! empty( $terms ) ) ? $terms[0]->name : __( 'Documents', 'cascapedia-st-jules' );
		$file_id = (int) get_post_meta( $post->ID, 'document_file', true );
		$href = $file_id ? wp_get_attachment_url( $file_id ) : '';
		if ( ! $href ) {
			continue;
		}
		$groups[ $group ][] = [
			'title' => cascapedia_st_jules_l( get_the_title( $post ) ),
			'href' => $href,
			'date' => (string) get_post_meta( $post->ID, 'document_date', true ),
			'description' => cascapedia_st_jules_l( wp_strip_all_tags( get_the_excerpt( $post ) ) ),
			'external' => true,
		];
	}
	$out = [];
	foreach ( $groups as $label => $documents ) {
		$out[] = [ 'label' => cascapedia_st_jules_l( $label ), 'documents' => $documents ];
	}
	return $out;
}

function cascapedia_st_jules_get_events(): array {
	$lang = cascapedia_st_jules_locale();
	$posts = get_posts([
		'post_type' => 'event',
		'post_status' => 'publish',
		'posts_per_page' => -1,
		'meta_key' => 'event_date',
		'orderby' => 'meta_value',
		'order' => 'ASC',
		'lang' => $lang,
	]);
	return array_map( static function ( WP_Post $post ): array {
		return [
			'date' => (string) get_post_meta( $post->ID, 'event_date', true ),
			'title' => cascapedia_st_jules_l( get_the_title( $post ) ),
			'location' => cascapedia_st_jules_l( (string) get_post_meta( $post->ID, 'location', true ) ),
			'description' => cascapedia_st_jules_l( wp_strip_all_tags( $post->post_content ) ),
		];
	}, $posts );
}

function cascapedia_st_jules_get_businesses(): array {
	$lang = cascapedia_st_jules_locale();
	$posts = get_posts([
		'post_type' => 'local_business',
		'post_status' => 'publish',
		'posts_per_page' => -1,
		'orderby' => 'title',
		'order' => 'ASC',
		'lang' => $lang,
	]);
	$businesses = array_map( static function ( WP_Post $post ): array {
		return [
			'name' => cascapedia_st_jules_clean_text( get_the_title( $post ) ),
			'description' => cascapedia_st_jules_l( wp_strip_all_tags( $post->post_content ) ),
			'phone' => (string) get_post_meta( $post->ID, 'phone', true ),
			'email' => (string) get_post_meta( $post->ID, 'email', true ),
			'website' => (string) get_post_meta( $post->ID, 'website', true ),
			'address' => (string) get_post_meta( $post->ID, 'address', true ),
		];
	}, $posts );
	return [[ 'name' => cascapedia_st_jules_l( $lang === 'en' ? 'All our businesses' : 'Toutes nos entreprises' ), 'businesses' => $businesses ]];
}

function cascapedia_st_jules_get_gallery_photos( string $gallery_key = '' ): array {
	$lang = cascapedia_st_jules_locale();
	$args = [ 'post_type' => 'gallery', 'post_status' => 'publish', 'posts_per_page' => 1, 'lang' => $lang ];
	if ( $gallery_key ) {
		$args['meta_key'] = 'gallery_key';
		$args['meta_value'] = $gallery_key;
	}
	$gallery = get_posts( $args )[0] ?? null;
	$ids = $gallery ? (array) get_post_meta( $gallery->ID, 'gallery_photos', true ) : [];
	return array_values( array_filter( array_map( 'cascapedia_st_jules_image_data', $ids ) ) );
}

function cascapedia_st_jules_section_data( array $row ): ?array {
	$layout = $row['acf_fc_layout'] ?? '';
	$type = str_replace( '_', '-', $layout );
	$base = [ 'type' => $type ];
	$title = (string) ( $row['title'] ?? '' );
	if ( $title ) $base['title'] = cascapedia_st_jules_l( $title );
	if ( ! empty( $row['body'] ) ) $base['body'] = cascapedia_st_jules_l( (string) $row['body'] );
	if ( ! empty( $row['intro'] ) ) $base['intro'] = cascapedia_st_jules_l( (string) $row['intro'] );
	if ( ! empty( $row['eyebrow'] ) ) $base['eyebrow'] = cascapedia_st_jules_l( (string) $row['eyebrow'] );
	if ( ! empty( $row['align'] ) ) $base['align'] = (string) $row['align'];
	if ( ! empty( $row['background'] ) ) $base['background'] = (string) $row['background'];

	switch ( $layout ) {
		case 'hero_carousel':
			$base['type'] = 'hero-carousel';
			$base['autoplayMs'] = (int) ( $row['autoplay_ms'] ?? 6000 );
			$base['slides'] = [];
			foreach ( (array) ( $row['slides'] ?? [] ) as $slide ) {
				$image = cascapedia_st_jules_image_data( $slide['image'] ?? null );
				if ( ! $image ) continue;
				$base['slides'][] = [
					'image' => $image,
					'eyebrow' => cascapedia_st_jules_l( $slide['eyebrow'] ?? '' ),
					'title' => cascapedia_st_jules_l( $slide['title'] ?? '' ),
					'subtitle' => cascapedia_st_jules_l( $slide['subtitle'] ?? '' ),
				];
			}
			return $base;
		case 'text_image':
			$base['type'] = 'text-image';
			$base['image'] = cascapedia_st_jules_image_data( $row['image'] ?? null );
			$base['imagePosition'] = $row['image_position'] ?? 'right';
			$cta = cascapedia_st_jules_link_data( $row );
			if ( $cta ) $base['cta'] = $cta;
			return $base['image'] ? $base : null;
		case 'services_list':
			$base['type'] = 'services-list';
			$base['services'] = [];
			foreach ( (array) ( $row['services'] ?? [] ) as $service ) {
				$items = array_filter( array_map( 'trim', preg_split( '/\r\n|\r|\n/', (string) ( $service['items'] ?? '' ) ) ) );
				$base['services'][] = [ 'title' => cascapedia_st_jules_l( $service['title'] ?? '' ), 'description' => cascapedia_st_jules_l( $service['description'] ?? '' ), 'items' => array_map( 'cascapedia_st_jules_l', $items ) ];
			}
			return $base;
		case 'photo_gallery':
			$base['type'] = 'photo-gallery';
			$photos = [];
			foreach ( (array) ( $row['photos'] ?? [] ) as $photo ) {
				$data = cascapedia_st_jules_image_data( $photo );
				if ( $data ) $photos[] = $data;
			}
			if ( ! $photos && ! empty( $row['gallery_key'] ) ) $photos = cascapedia_st_jules_get_gallery_photos( (string) $row['gallery_key'] );
			$base['photos'] = $photos;
			return $base;
		case 'events_list':
			$base['type'] = 'events-list';
			$base['events'] = cascapedia_st_jules_get_events();
			return $base;
		case 'businesses_list':
			$base['type'] = 'businesses-list';
			$base['categories'] = cascapedia_st_jules_get_businesses();
			return $base;
		case 'documents_list':
			$base['type'] = 'documents-list';
			$base['groups'] = cascapedia_st_jules_get_documents();
			return $base;
		case 'council_grid':
			$base['type'] = 'council-grid';
			$base['members'] = [];
			foreach ( (array) ( $row['members'] ?? [] ) as $member ) {
				$item = [ 'name' => (string) ( $member['name'] ?? '' ), 'role' => cascapedia_st_jules_l( $member['role'] ?? '' ), 'email' => (string) ( $member['email'] ?? '' ) ];
				$photo = cascapedia_st_jules_image_data( $member['photo'] ?? null );
				if ( $photo ) $item['photo'] = $photo;
				$base['members'][] = $item;
			}
			if ( ! empty( $row['footnote'] ) ) $base['footnote'] = cascapedia_st_jules_l( (string) $row['footnote'] );
			return $base;
		case 'cta_section':
			$base['type'] = 'cta-section';
			if ( ! empty( $row['subtitle'] ) ) $base['subtitle'] = cascapedia_st_jules_l( (string) $row['subtitle'] );
			$base['cta'] = cascapedia_st_jules_link_data( $row ) ?: [ 'label' => cascapedia_st_jules_l( '' ), 'href' => '#' ];
			return $base;
		case 'pdf_embed':
			$base['type'] = 'pdf-embed';
			$file = $row['file'] ?? null;
			$file_id = is_array( $file ) ? (int) ( $file['ID'] ?? $file['id'] ?? 0 ) : (int) $file;
			$base['href'] = $file_id ? (string) wp_get_attachment_url( $file_id ) : '';
			$base['height'] = (int) ( $row['height'] ?? 800 );
			return $base['href'] ? $base : null;
		case 'text_intro':
		default:
			$base['type'] = 'text-intro';
			return $base;
	}
}

function cascapedia_st_jules_site_data(): array {
	$logo = function_exists( 'get_field' ) ? get_field( 'site_logo', 'option' ) : null;
	return [
		'logo' => cascapedia_st_jules_image_data( $logo ),
		'phone' => function_exists( 'get_field' ) ? (string) get_field( 'phone', 'option' ) : '',
		'email' => function_exists( 'get_field' ) ? (string) get_field( 'email', 'option' ) : '',
		'facebook' => function_exists( 'get_field' ) ? (string) get_field( 'facebook_url', 'option' ) : '',
	];
}

function cascapedia_st_jules_current_page_data(): array {
	$post_id = get_queried_object_id();
	if ( ! $post_id && ( is_home() || is_front_page() ) ) {
		$post_id = (int) get_option( 'page_on_front' );
	}
	$sections = [];
	if ( $post_id && function_exists( 'get_field' ) ) {
		foreach ( (array) get_field( 'sections', $post_id ) as $row ) {
			$section = is_array( $row ) ? cascapedia_st_jules_section_data( $row ) : null;
			if ( $section ) $sections[] = $section;
		}
	}
	return [
		'id' => $post_id,
		'seo' => [
			'title' => cascapedia_st_jules_l( $post_id ? ( get_post_meta( $post_id, '_seo_title', true ) ?: get_the_title( $post_id ) ) : '' ),
			'description' => cascapedia_st_jules_l( $post_id ? ( get_post_meta( $post_id, '_seo_description', true ) ?: get_the_excerpt( $post_id ) ) : '' ),
		],
		'sections' => $sections,
	];
}
