<?php
if (!defined('ABSPATH')) exit;

if (empty($property)) {
    echo '<div class="property-single-container"><p>Property not found.</p></div>';
    return;
}

$lang = get_query_var('zoddak_lang') ?: 'es';
$title = $property['titles'][$lang] ?? ($property['titles']['en'] ?? ($property['titles']['es'] ?? ''));
$description = $property['description'][$lang] ?? ($property['description']['en'] ?? ($property['description']['es'] ?? ''));

$price = !empty($property['price']) ? (int)$property['price'] : null;
$price_title = !empty($property['price_freq']) && $property['price_freq'] === 'rent' ? T_('Rent') : T_('Price');

$prop_type = $property['type'] ?? '';
$stage = ''; 
$lang = explode('_', get_locale())[0];
$municipality = $property['location']['municipality'] ?? '';
$district     = $property['location']['district'] ?? '';
$region       = $property['location']['region'] ?? '';
$other_features = [];
$features = $property['features'] ?? [];

$exclude = [
    'South', 'South East', 'South West',
    'Sea', 'Mountain', 'Golf', 'Lake', 'Panoramic',
    'Garage', 'Private', 'Heated', 'Fully Furnished', 'Fully Fitted'
];

foreach ($features as $feature) {
    if (!in_array($feature, $exclude)) {
        $other_features[] = $feature;
    }
}
$place = trim(implode(', ', array_filter([$municipality, $district, $region])));

$lat = null;
$lng = null;
if (!empty($property['coords']) && is_array($property['coords']) && count($property['coords']) === 2) {
  $lng = $property['coords'][0];
  $lat = $property['coords'][1];
}

$images = $property['gallery'] ?? [];
if (!is_array($images)) $images = [];
?>
<link rel="stylesheet"
      href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css">

<div class="zoddak-wrapper">
    <div data-ref="<?= $ref; ?>" class="property-single-container" 
        style="--btn-details-color: <?= esc_attr($primary_color);?>;--primary-color: <?= esc_attr($primary_color) ?>; --property-type-bg-color: <?= esc_attr($type_color) ?>; --page-width: <?= esc_attr($options['pageWidth']) ?>;">
    
        <div class="lang-and-back">
            <div class="property-back-link">
                <?php
                    $route = get_option('rs_zoddak_custom_route');
                ?>
                <a href="/<?= $route ?>">← <span><?php echo T_('Back to Properties'); ?></span></a>    
            </div>
            <div class="lang-selector">
                <label for="lang-switcher" class="lang-switcher-label"><?php echo T_('Language:') ?></label>
                <?php $current_lang = get_query_var('rs_zoddak_lang'); ?>
                <select name="lang-switcher" id="langSwitcher">
                    <?php foreach($routes as $lang => $rt):?> 
                        <option value="/<?= $lang ?>/<?= $rt ?>/<?= $ref ?>" <?= selected($current_lang, $lang, false) ?>><?=strtoupper($lang) ?></option>
                    <?php endforeach;?>
                </select>
            </div>
        </div>
    
    <div class="property-gallery-section">
        <div class="property-gallery">
    
        <?php if (!empty($images)): ?>
          <?php
                $total_images = count($images);
                $visible_thumbs = 5;
            ?>
    
          <div class="swiper main-swiper">
            <div class="swiper-wrapper">
              <?php foreach ($images as $img): ?>
                <div class="swiper-slide">
                  <img src="<?= esc_url($img) ?>" alt="<?= esc_attr($title) ?>">
                </div>
              <?php endforeach; ?>
            </div>
    
            <div class="swiper-button-prev"></div>
            <div class="swiper-button-next"></div>
          </div>
    
          <div class="thumbs-wrapper">
            <div class="swiper thumbs-swiper">
              <div class="swiper-wrapper">
                <?php foreach ($images as $index => $img): ?>
                    <div class="swiper-slide">
                      <img src="<?= esc_url($img) ?>" alt="Thumbnail <?= $index + 1 ?>">
                    </div>
                <?php endforeach; ?>
              </div>
            </div>
          </div>
    
        <?php endif; ?>
      </div>
    </div>
    
    
    
    <script>
        window.propertyImages = <?= json_encode($images); ?>;
    </script>
        <!-- Property info -->
        <div class="property-single-header">
            <h1 class="property-title">
                <?= esc_html($title); ?>
            </h1>
            <div class="property-ref"><strong>#</strong><?=esc_html($property['reference']) ?></div>
            <div class="property-meta">
                <?php if (!empty($price)): ?>
                    <div class="property-price">
                        <span class="price-title"><?= esc_html($price_title); ?></span>
                        <?= number_format($price, 0, ',', '.') ?>€
                    </div>
                <?php endif; ?>

                <?php if (!empty($prop_type)): ?>
                    <div class="property-type">
                        <span><?= esc_html($prop_type) ?></span>
                    </div>
                <?php endif; ?>
                <?php if (!empty($property['new_build'])): ?>
                    <div class="property-stage"><span><?= esc_html(T_('New build')) ?></span></div>
                    <?php endif; ?>

                    <?php if (!empty($property['is_new'])): ?>
                    <div class="property-stage"><span><?= esc_html(T_('New')) ?></span></div>
                <?php endif; ?>
    
                <div class="property-location"><?= esc_html($place) ?></div>
            </div>
        </div>
        <div class="property-info-section">
            <div class="property-info-column">

            
                <div class="property-features-section">
                    <h3><?php echo T_('Features');?></h3>
                </div>
                <div class="property-info-container">

                    <table class="property-features-table">
                        <tbody>
                            <?php if (!empty($property['beds'])): ?>
                            <tr>
                                <th><i class="fas fa-bed"></i></th>
                                <td><?= number_format((int)$property['beds']);?> <?php echo T_('Bedrooms')?></td>
                            </tr>
                            <?php endif; ?>

                            <?php if (!empty($property['baths'])): ?>
                            <tr>
                                <th><i class="fas fa-bath"></i></th>
                                <td><?= number_format((int)$property['baths']);?> <?php echo T_('Bathrooms')?></td>
                            </tr>
                            <?php endif; ?>

                            <?php if (!empty($property['built'])): ?>
                            <tr>
                                <th><span class="dashicons dashicons-admin-home"></span></th>
                                <td><?= number_format((int)$property['built'], 0, ',', '.') ?> m2 <?php echo T_('Built area');?></td>
                            </tr>
                            <?php endif; ?>

                            <?php if (!empty($property['plot'])): ?>
                            <tr>
                                <th><span class="dashicons dashicons-layout"></span></th>
                                <td><?= number_format((int)$property['plot'], 0, ',', '.') ?> m2 <?php echo esc_html(T_('Plot area'));?></td>
                            </tr>
                            <?php endif; ?>
                            <?php if (!empty($property['terrace'])): ?>
                            <tr>
                                <th><i class="bi bi-aspect-ratio"></i></th>
                                <td><?= number_format((int)$property['terrace'], 0, ',', '.') ?> m2 <?php echo esc_html(T_('Terrace'));?></td>
                            </tr>
                            <?php endif; ?>
                            <?php if (!empty($property['year'])): ?>
                            <tr>
                                <th><i class="bi bi-calendar3"></i></th>
                                <td><?= (int)$property['year']; ?> <?php echo esc_html(T_('Year'));?></td>
                            </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>  
                <?php if (!empty($other_features)) : ?>
                    <div class="rs-property-section mt-4">

                        <div class="accordion" id="rsAccordionOther">
                            <div class="accordion-item">
                                <h2 class="accordion-header" id="rsHeadingOther">
                                    <button class="accordion-button collapsed rs-section-title"
                                            type="button"
                                            data-bs-toggle="collapse"
                                            data-bs-target="#rsCollapseOther"
                                            aria-expanded="false"
                                            aria-controls="rsCollapseOther">
                                        Otros
                                    </button>
                                </h2>

                                <div id="rsCollapseOther"
                                    class="accordion-collapse collapse"
                                    aria-labelledby="rsHeadingOther"
                                    data-bs-parent="#rsAccordionOther">
                                    <div class="accordion-body">

                                        <div class="row">
                                            <?php foreach ($other_features as $feature) : ?>
                                                <div class="col-md-4 mb-2">
                                                    <div class="rs-feature-item">
                                                        <i class="fas fa-check text-success me-2"></i>
                                                        <?= esc_html($feature[$lang] ?? ''); ?>
                                                    </div>
                                                </div>
                                            <?php endforeach; ?>
                                        </div>

                                    </div>
                                </div>
                            </div>
                        </div>

                    </div>
                <?php endif; ?>


                <?php if (!empty($description)): ?>
                    <div class="property-description">
                        <h3><?php echo T_('Description'); ?></h3>
                        <div class="property-description-content">
                            <?= wp_kses_post($description) ?>
                        </div>
                    </div>
                <?php endif; ?>
                <?php 
                    $remaining = $property['units_total'] - $property['units_sold']
                ;?> 
                <?php if (!empty($lat) && !empty($lng)): ?>
                    <div class="property-map-section">
                        <h3><?php echo T_('Location'); ?></h3>
                        <div id="property-map" 
                            style="height: 400px; width: 100%; margin-bottom: 20px;"
                            data-lat="<?= esc_attr($lat) ?>"
                            data-lng="<?= esc_attr($lng) ?>"
                            data-color="<?= esc_attr($primary_color) ?>">
                        
                        
                        <?php $clave_api = get_option('rs_zoddak_google_maps_api');
                        ?>
        
                        <?php if ($clave_api): ?>
                            <?php
                                $google_url = sprintf(
                                    'https://maps.googleapis.com/maps/api/js?key=%s&callback=initMap',
                                    esc_attr($clave_api)
                                );
                            ?>
                            <script src="<?php echo $google_url; ?>" async defer></script>
                        <?php else: ?>
                            <link rel="stylesheet" href="https://unpkg.com/leaflet/dist/leaflet.css" />
                            <script src="https://unpkg.com/leaflet/dist/leaflet.js"></script>
                        <?php endif; ?>
                    <?php endif; ?>
                    </div>
                </div>
            </div>
            
            <div class="property-contact-column">
                <div class="property-contact-form">
                    <h2><?php echo T_('Inquire about this property'); ?></h2>
                    <?php
                        $form_shortcode = !empty($options['contactForm']) ? $options['contactForm'] : '';
                        if ($form_shortcode) {
                            echo do_shortcode($form_shortcode);
                        } else {
                            // Si no hay formulario, mostramos uno por defecto o un aviso
                            echo do_shortcode('[contact-form-7 id="2456" title="Property Contact"]');
                            echo '<div class="zoddak-contact-warning" style="margin-top:10px; background:#fff8e5; border:1px solid #f3c65c; border-radius:8px; padding:12px; color:#8a6d3b; font-size:14px;">
                                    ⚠️ No custom contact form configured. Default form loaded.
                                </div>';
                        }
                        ?>
                </div>
            </div>
        </div>
    </div>
    <div class="powered-by-zoddak">
        <span>Powered by: </span>
        <img id="zoddakLogo" src="<?php echo  ZODDAK_RESALES_PLUGIN_URL . 'images/zoddak.png' ?>" alt="zoddak logo">
    </div>
</div>
<?php get_footer(); ?>
<script>
    const logoZoddak = document.getElementById('zoddakLogo');
    logoZoddak.addEventListener('click', () => {
        window.open('https://www.zoddak.com', '_blank');
    })
</script>
