<?php

get_header();

if ( have_posts() ) :

	while ( have_posts() ) :

		the_post();

		$postID = get_the_ID();

		$types     = get_the_terms( $postID, 'iwp_type' );
		$type      = '';
		$type_slug = '';
		if ( $types && ! is_wp_error( $types ) ) {
			$term      = is_array( reset( $types ) ) ? (object) reset( $types ) : reset( $types );
			$type      = $term->name;
			$type_slug = $term->slug;
		}

		$offres     = get_the_terms( $postID, 'iwp_offre' );
		$offre      = '';
		$offre_slug = '';
		if ( $offres && ! is_wp_error( $offres ) ) {
			$term       = is_array( reset( $offres ) ) ? (object) reset( $offres ) : reset( $offres );
			$offre      = $term->name;
			$offre_slug = $term->slug;
		}

		$localisations = get_the_terms( $postID, 'iwp_localisation' );
		$localisation  = '';
		if ( $localisations && ! is_wp_error( $localisations ) ) {
			$term         = is_array( reset( $localisations ) ) ? (object) reset( $localisations ) : reset( $localisations );
			$localisation = $term->name;
		}

		$iwp_caracteristiques = get_the_terms( $postID, 'iwp_caracteristiques' );
		$caracteristiques     = array();
		if ( $iwp_caracteristiques && ! is_wp_error( $iwp_caracteristiques ) ) {
			foreach ( $iwp_caracteristiques as $term ) {
				$term               = is_array( $term ) ? (object) $term : $term;
				$caracteristiques[] = $term->name;
			}
		}

		$iwp_agences = get_the_terms( $postID, 'iwp_agences' );
		$agence      = '';
        $agence_name = '';
		if ( $iwp_agences && ! is_wp_error( $iwp_agences ) ) {
			$term        = is_array( reset( $iwp_agences ) ) ? (object) reset( $iwp_agences ) : reset( $iwp_agences );
			$agence      = $term->term_id;
			$agence_name = $term->name;
		}

		$iwp_agents = get_the_terms( $postID, 'iwp_agent' );
		$agent      = '';
		if ( $iwp_agents && ! is_wp_error( $iwp_agents ) ) {
			$term  = is_array( reset( $iwp_agents ) ) ? (object) reset( $iwp_agents ) : reset( $iwp_agents );
			$agent = $term->term_id;
		}

	endwhile;
endif;

$affNum              = get_post_meta( get_the_ID(), 'affNum', true );
$prix                = get_post_meta( get_the_ID(), 'prix', true );
$prixHorsHono        = get_post_meta( get_the_ID(), 'prixHorsHono', true );
$pourcentageHono     = get_post_meta( get_the_ID(), 'pourcentageHono', true );
$loyer               = get_post_meta( get_the_ID(), 'loyer', true );
$loyerMensuelCC      = get_post_meta( get_the_ID(), 'loyerMensuelCC', true );
$loyerPeriod         = get_post_meta( get_the_ID(), 'loyerPeriod', true );
$typeLoyer           = $loyerMensuelCC ? 'HC' : get_post_meta( get_the_ID(), 'typeLoyer', true );
$latitude            = get_post_meta( get_the_ID(), 'latitude', true );
$longitude           = get_post_meta( get_the_ID(), 'longitude', true );
$nombre_pieces       = get_post_meta( get_the_ID(), 'nbrePieces', true );
$nombre_chambres     = get_post_meta( get_the_ID(), 'nbreChambres', true );
$surface             = get_post_meta( get_the_ID(), 'surfaceHabitable', true );
$surface_jardin      = get_post_meta( get_the_ID(), 'surfaceTerrain', true );
$chargesHonoraires   = get_post_meta( get_the_ID(), 'chargesHonoraires', true );
$provisionSurCharges = get_post_meta( get_the_ID(), 'provisionSurCharges', true );
$chargesAnnuelles    = get_post_meta( get_the_ID(), 'chargesAnnuelles', true );
$depotGarantie       = get_post_meta( get_the_ID(), 'depotGarantie', true );
$honoEDL             = get_post_meta( get_the_ID(), 'honoEDL', true );
$copro               = get_post_meta( get_the_ID(), 'copro', true );
$nbLots              = get_post_meta( get_the_ID(), 'nbLots', true );
$nbLotsHab           = get_post_meta( get_the_ID(), 'nbLotsHab', true );
$nbLotsHab           = get_post_meta( get_the_ID(), 'nbLotsHab', true );
$taxeFonciere        = get_post_meta( get_the_ID(), 'taxeFonciere', true );
$tarifs              = get_post_meta( get_the_ID(), 'tarifs', true );
$exclusivite         = get_post_meta( get_the_ID(), 'exclusivite', true );
$coup_coeur          = get_post_meta( get_the_ID(), 'coupCoeur', true );

if ( ! empty( $tarifs ) ) {
	$tarifMin = '';
	foreach ( $tarifs as $tarif ) {
		if ( $tarifMin == '' || $tarif[2] < $tarifMin ) {
			$tarifMin = $tarif[2];
		}
	}
	$prix = $tarifMin;

	if ( empty( $tarifMin ) ) {
		$prix = $loyer;
	}
} elseif ( empty( $prix ) && ! empty( $loyer ) ) {
	$prix = $loyer;
}

if ( ! function_exists( 'immowp_single_sidebar_icon' ) ) {
	function immowp_single_sidebar_icon( $icon = 'mail' ) {
		$icons = array(
			'location' => '<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M15 10.5a3 3 0 11-6 0 3 3 0 016 0z" /><path stroke-linecap="round" stroke-linejoin="round" d="M19.5 10.5c0 7.142-7.5 11.25-7.5 11.25S4.5 17.642 4.5 10.5a7.5 7.5 0 1115 0z" /></svg>',
			'mail'     => '<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M21.75 6.75v10.5a2.25 2.25 0 01-2.25 2.25H4.5a2.25 2.25 0 01-2.25-2.25V6.75m19.5 0A2.25 2.25 0 0019.5 4.5h-15a2.25 2.25 0 00-2.25 2.25m19.5 0v.243a2.25 2.25 0 01-1.072 1.916l-7.5 4.615a2.25 2.25 0 01-2.256 0L3.322 8.91a2.25 2.25 0 01-1.072-1.916V6.75" /></svg>',
			'phone'    => '<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M2.25 6.75c0 8.284 6.716 15 15 15h1.5a2.25 2.25 0 002.25-2.25v-1.1a1.125 1.125 0 00-.852-1.09l-4.423-1.106a1.125 1.125 0 00-1.173.417l-.97 1.293a.75.75 0 01-1.21.038l-1.47-1.838a11.25 11.25 0 01-2.682-5.27l-.21-1.26a.75.75 0 01.478-.82l1.708-.683a1.125 1.125 0 00.682-1.02V3.75A1.5 1.5 0 009.332 2.3l-3.478-.869a1.125 1.125 0 00-1.347.78l-.978 3.585a2.25 2.25 0 00-.079.634z" /></svg>',
		);

		return $icons[ $icon ] ?? $icons['mail'];
	}
}

?>

<div class="iwp__property">
    <div class="iwp__header">
        <div class="iwp__header-meta">
            <ul>
                <?php if ( ! empty( get_post_meta( get_the_ID(), 'statut', true ) ) ) : ?>
                    <li class="iwp__heart"><?php echo esc_html( get_post_meta( get_the_ID(), 'statut', true ) ); ?></li>
                <?php endif; ?>
                <?php if ( ! empty( $exclusivite ) && $exclusivite ) : ?>
                    <li class="iwp__heart"><?php esc_html_e( 'Exclusivite', 'immowp-gestion-immo' ); ?></li>
                <?php endif; ?>
                <?php if ( ! empty( $coup_coeur ) && $coup_coeur ) : ?>
                    <li class="iwp__heart"><?php esc_html_e( 'Coup de coeur', 'immowp-gestion-immo' ); ?></li>
                <?php endif; ?>
                <?php if ( ! empty( $type ) ) : ?>
                    <li class="iwp_type"><?php echo esc_html( $type ); ?></li>
                <?php endif; ?>
                <?php if ( ! empty( $offre ) ) : ?>
                    <li class="iwp_status"><?php echo esc_html( $offre ); ?></li>
                <?php endif; ?>
            </ul>
        </div>
        <div class="iwp__header-title">
            <div class="iwp__header-title__address">
                <h1><?php echo esc_html( get_the_title() ); ?></h1>
                <?php if ( ! empty( $localisation ) ) : ?>
                    <span>
                        <svg version="1.1" id="Layer_1" xmlns="https://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 512 512" style="enable-background:new 0 0 512 512;" xml:space="preserve"><g><g><path d="M256,0C153.755,0,70.573,83.182,70.573,185.426c0,126.888,165.939,313.167,173.004,321.035    c6.636,7.391,18.222,7.378,24.846,0c7.065-7.868,173.004-194.147,173.004-321.035C441.425,83.182,358.244,0,256,0z M256,469.729    c-55.847-66.338-152.035-197.217-152.035-284.301c0-83.834,68.202-152.036,152.035-152.036s152.035,68.202,152.035,152.035    C408.034,272.515,311.861,403.37,256,469.729z"/></g></g><g><g><path d="M256,92.134c-51.442,0-93.292,41.851-93.292,93.293s41.851,93.293,93.292,93.293s93.291-41.851,93.291-93.293    S307.441,92.134,256,92.134z M256,245.328c-33.03,0-59.9-26.871-59.9-59.901s26.871-59.901,59.9-59.901s59.9,26.871,59.9,59.901    S289.029,245.328,256,245.328z"/></g></svg>
                        <?php echo esc_html( $localisation ); ?>
                    </span>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <div class="iwp__property-container">
        <!-- Main Content (Left) -->
        <div class="iwp__main-content">
            <!-- Gallery Slider -->
            <?php 
            $pswp_gallery_id = 'pswp-gallery-' . get_the_ID();
            $image_ids = get_post_meta( get_the_ID(), 'image_ids', true );
            if ( $image_ids ) :
                $images = is_array( $image_ids ) ? $image_ids : explode( ',', $image_ids );
            ?>
            <div class="iwp__gallery-wrapper">
                <div class="iwp__gallery-badges">
                     <?php if ( ! empty( get_post_meta( get_the_ID(), 'statut', true ) ) ) : ?>
                        <span class="iwp__badge iwp__badge--status"><?php echo esc_html( get_post_meta( get_the_ID(), 'statut', true ) ); ?></span>
                    <?php endif; ?>
                    <?php if ( ! empty( $exclusivite ) && $exclusivite ) : ?>
                        <span class="iwp__badge iwp__badge--exclusive"><?php esc_html_e( 'Exclusivité', 'immowp-gestion-immo' ); ?></span>
                    <?php endif; ?>
                    <?php if ( ! empty( $coup_coeur ) && $coup_coeur ) : ?>
                        <span class="iwp__badge iwp__badge--heart"><?php esc_html_e( 'Coup de coeur', 'immowp-gestion-immo' ); ?></span>
                    <?php endif; ?>
                </div>
                <!-- Main Slider -->
                <div class="swiper iwp__gallery-slider" id="<?php echo esc_attr( $pswp_gallery_id ); ?>">
                    <div class="swiper-wrapper">
                        <?php foreach ( $images as $image_id ) : 
                            $img_src       = wp_get_attachment_image_src( $image_id, 'large' );
                            $img_src_full  = wp_get_attachment_image_src( $image_id, 'full' );
                            $display_src   = $img_src ? $img_src[0] : ( $img_src_full ? $img_src_full[0] : '' );
                            $full_src      = $img_src_full ? $img_src_full[0] : $display_src;
                            $full_width    = $img_src_full ? $img_src_full[1] : ( $img_src ? $img_src[1] : 0 );
                            $full_height   = $img_src_full ? $img_src_full[2] : ( $img_src ? $img_src[2] : 0 );
                            if ( $display_src ) :
                        ?>
                        <div class="swiper-slide">
                            <a 
                                href="<?php echo esc_url( $full_src ); ?>" 
                                class="iwp__gallery-lightbox-link"
                                data-pswp-src="<?php echo esc_url( $full_src ); ?>"
                                data-pswp-width="<?php echo esc_attr( $full_width ); ?>"
                                data-pswp-height="<?php echo esc_attr( $full_height ); ?>"
                                data-cropped="true"
                            >
                                <img src="<?php echo esc_url( $display_src ); ?>" alt="<?php the_title_attribute(); ?>">
                            </a>
                            <div class="iwp__slide-counter">1 / <?php echo count($images); ?></div>
                        </div>
                        <?php endif; endforeach; ?>
                    </div>
                    <div class="swiper-button-next"></div>
                    <div class="swiper-button-prev"></div>
                </div>
            </div>
            <?php endif; ?>

            <!-- Property Content -->
            <div class="iwp__property-details-content">
				<!-- Description -->
				<?php if ( ! empty( get_the_content() ) ) : ?>
					<div class="iwp__block iwp__block-description iwp__card">
						<div class="iwp__card-header">
							<h2><?php esc_html_e( 'Description', 'immowp-gestion-immo' ); ?></h2>
						</div>
						<div class="iwp__card-body">
							<?php the_content(); ?>
						</div>
					</div>
				<?php endif; ?>
				
				<!-- Overview -->
				<div class="iwp__block iwp__block-overview iwp__card">
					<?php require __DIR__ . '/single-parts/resume.php'; ?>
				</div>
				
				<!-- Détails -->
				<?php require __DIR__ . '/single-parts/details.php'; ?>
				
				<!-- Visite -->
				<?php if ( ! empty( trim( get_post_meta( get_the_ID(), 'visiteVirtuelle', true ) ) ) ) : ?>
					<?php include __DIR__ . '/single-parts/visite-virtuelle.php'; ?>
				<?php endif; ?>
				
				<!-- video -->
				<?php if ( ! empty( trim( get_post_meta( get_the_ID(), 'video', true ) ) ) ) : ?>
					<?php include __DIR__ . '/single-parts/video.php'; ?>
				<?php endif; ?>
				
            </div>
        </div>
    </div>
</div>

<!-- Swiper Init -->
<script>
document.addEventListener('DOMContentLoaded', function() {
    var swiperMain = new Swiper(".iwp__gallery-slider", {
        spaceBetween: 10,
        loop: true,
        navigation: {
            nextEl: ".swiper-button-next",
            prevEl: ".swiper-button-prev",
        },
        on: {
            slideChange: function () {
                var index = this.realIndex + 1;
                var total = this.slides.length - this.loopedSlides * 2;
                 // Adjust total count for loop mode since slides.length includes duplicates
                // Simple fallback if not using loop
                if (!this.loopedSlides) {
                    total = this.slides.length;
                } else {
                    // swiper 8+ logic might differ slightly but realIndex handles current slide
                    // total slides in loop mode is usually slides.length / 3 if loop creates duplicates or just use original count if possible
                    // A safer way to get total is counting elements before init or checking dataset
                     total = document.querySelectorAll('.iwp__gallery-slider .swiper-slide:not(.swiper-slide-duplicate)').length;
                }
                
                var counters = document.querySelectorAll('.iwp__slide-counter');
                counters.forEach(c => c.innerText = index + ' / ' + total);
            }
        }
    });
});
</script>
<?php if ( ! empty( $image_ids ) ) : ?>
<script type="module">
import PhotoSwipeLightbox from '<?php echo esc_url( plugins_url( '../../js/photoswipe/photoswipe-lightbox.esm.js', __FILE__ ) ); ?>';
const lightbox = new PhotoSwipeLightbox({
    gallery: '#<?php echo esc_js( $pswp_gallery_id ); ?>',
    children: 'a.iwp__gallery-lightbox-link',
    pswpModule: () => import('<?php echo esc_url( plugins_url( '../../js/photoswipe/photoswipe.esm.js', __FILE__ ) ); ?>'),
});
lightbox.init();
</script>
<?php endif; ?>

<?php
get_footer();
