<?php
if (!defined('ABSPATH')) exit;
get_header();
$route = home_url(get_option('rs_zoddak_custom_route', 'resales'));
if($options['pageWidth'] === '960px'){
    $layout = 'layout-small';
}elseif($options['pageWidth'] === '1200px'){
    $layout = 'layout-medium';
}elseif($options['pageWidth'] === '1400px'){
    $layout = 'layout-large';
}else{
    $layout = 'layout-total';
}
$orders = [
    
    [
        'slug'=>'municipality',
        'name' => T_('Municipio')
    ],
    [
        'slug' => 'type',
        'name' => T_('Type'),
    ],
    [
        'slug' => 'min_price',
        'name' => T_('Price: Lower to Higher')
    ],
    [
        'slug' => 'max_price',
        'name' => T_('Price: Higher to Lower')
    ],
    [
        'slug' => 'min_beds',
        'name' => T_('Beds: Min to Max')
    ],
    [
        'slug' => 'max_beds',
        'name' => T_('Beds: Max to Min')
    ],
];
$actionUrl = home_url( trim( get_option('rs_zoddak_custom_route','propiedades'), '/' ) . '/' );
?>

<div class="zoddak-page-wrapper">
    <!-- <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 ?>" <?= selected($current_lang, $lang, false) ?>><?=strtoupper($lang) ?></option>
            <?php endforeach;?>
        </select>
    </div> -->

  <!-- 🔎 Filtro de búsqueda -->
    <div class="search-menu-preview" >
      <h3 data-translate="Search Properties"><?php echo T_('Search Properties') ?></h3>
      <button type="button" class="filters-toggle">
        <span><?php echo T_('Show Filters') ?></span>
        <i  class="fa-solid fa-chev iconron-down"></i>
    </button>
    <div class="filters-container">
        <form id="searchForm" method="get" class="filter-selector-row reference-row">
            <div class="filter-selector">
                <label for="reference" data-translate="Property Reference"><?php echo T_('Find') ?></label>
                <div class="reference-search-container">
                    <input type="text" name="reference" id="reference" 
                    placeholder="REF-12345"
                    value="<?= esc_attr($filters['reference'] ?? ''); ?>"
                    class="reference-input">

                    <button type="submit" id="search-reference-btn" 
                    class="search-button" 
                    data-translate="Find"><?php echo T_('Find') ?></button>
                </div>
            </div>
        </form>    
      <form method="get" action="<?= esc_url($actionUrl); ?>">

      <div class="filter-selector-row">
        <!----Baños----->
        <div class="filter-selector">
              <label for="min_baths" data-translate="Bathrooms"><?php echo T_('Bathrooms') ?></label>
              <select name="min_baths" id="min_baths">
                  <option value="" data-translate="Any"><?php echo T_('Any') ?></option>
                  <?php foreach ([1,2,3,4,5,6,7] as $n): ?>
                      <option value="<?= $n; ?>" <?= selected($filters['min_baths'] ?? '', $n, false); ?>>
                          <?= $n; ?>+
                      </option>
                  <?php endforeach; ?>
              </select>
          </div>
      
          <!-- Dormitorios -->
          <div class="filter-selector">
              <label for="min_beds" data-translate="Bedrooms"><?php echo T_('Bedrooms');?></label>
              <select name="min_beds" id="min_beds">
                  <option value="" data-translate="Any"><?php echo T_('Any') ?></option>
                  <?php foreach ([1,2,3,4,5,6,7] as $n): ?>
                      <option value="<?= $n; ?>" <?= selected($filters['min_beds'] ?? '', $n, false); ?>>
                          <?= $n; ?>+
                      </option>
                  <?php endforeach; ?>
              </select>
          </div>
      
          <!-- Precio mínimo -->
          <div class="filter-selector">
              <label for="min_price" data-translate="Minimum Price"><?php echo T_('Minimum Price') ?></label>
              <select name="min_price" id="min_price">
                  <option value="" data-translate="Any"><?php echo T_('Any') ?></option>
                  <?php foreach ($filtered_prices as $price): ?>
                      <option value="<?= $price; ?>" <?= selected($filters['min_price'] ?? '', $price, false); ?>>
                          <?= number_format($price, 0, ',', '.'); ?>€
                      </option>
                  <?php endforeach; ?>
              </select>
          </div>
      
          <!-- Precio máximo -->
            <div class="filter-selector">
                <label for="max_price" data-translate="Maximum Price"><?php echo T_('Maximum Price') ?></label>
                <select name="max_price" id="max_price">
                    <option value="" data-translate="Any"><?php echo T_('Any') ?></option>
                    <?php foreach ($filtered_prices as $price): ?>
                        <option value="<?= $price; ?>" <?= selected($filters['max_price'] ?? '', $price, false); ?>>
                            <?= number_format($price, 0, ',', '.'); ?>€
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <!-- Área -->
            <div class="filter-selector">
            <label data-translate="Area"><?php echo T_('Area') ?></label>

            <!-- <?php
                $selected_towns = isset($_GET['towns']) ? (array) $_GET['towns'] : [];
            ?> -->

            <div class="dropdown-btn custom-multiselect" id="areaDropdown">
                
                <span class="placeholder">
                    <?php echo T_('Select areas');?>
                </span>
                <div id="dropdownCont" class="dropdown-content">
                    <div class="buttons">
                        <button id="btnSelect" class="btn-select"><?php echo T_('SELECT ALL') ?></button>
                        <button id="btnDeselect" class="btn-deselect"><?php echo  T_('DESELECT ALL') ?></button>
                    </div>
                    <div class="dropdown-items">

                    <?php foreach ($locations as $comarca): ?>
                        <?php
                        $comarcaName = $comarca['Name'] ?? '';
                        $comarcaSlug = $comarca['slug'] ?? '';
                        $municipios  = $comarca['municipios'] ?? [];

                        $comarca_checked = (!empty($selected_locations) && in_array($comarcaSlug, $selected_locations, true))
                            ? 'checked' : '';
                        ?>

                        <!-- COMARCA -->
                        <label class="ms-item level-0">
                        <input type="checkbox" name="comarcas[]" value="<?= esc_attr($comarcaSlug) ?>" <?= $comarca_checked ?>>
                        <span><?= esc_html($comarcaName) ?></span>
                        </label>

                        <?php if (!empty($municipios) && is_array($municipios)): ?>
                        <?php foreach ($municipios as $mn): ?>
                            <?php
                            $mnName = $mn['Name'] ?? '';
                            $mnSlug = $mn['slug'] ?? '';
                            $distritos = $mn['distritos'] ?? [];

                            $mn_checked = (!empty($selected_locations) && in_array($mnSlug, $selected_locations, true))
                                ? 'checked' : '';
                            ?>

                            <!-- MUNICIPIO -->
                            <label class="ms-item level-1">
                            <input type="checkbox" name="municipios[]" value="<?= esc_attr($mnSlug) ?>" <?= $mn_checked ?>>
                            <span><?= esc_html($mnName) ?></span>
                            </label>
                        <?php endforeach; ?>
                        <?php endif; ?>

                    <?php endforeach; ?>

                    </div>
                </div>
                <span class="selected-items">
                    <?= !empty($selected_towns) ? esc_html(implode(', ', $selected_towns)) : '' ?>
                </span>
                <span class="arrow">▾</span>
            </div>

        </div>

        <div class="filter-selector">
            <label for="type" data-translate="Property Type"><?php echo T_('Property Type') ?></label>
            <select name="type" id="type">
                <option value="" data-translate="Select Type"><?php echo T_('Select Type');?></option>
                <?php foreach ($types as $type): ?>
                    <?php $value = strtolower($type['slug']); ?>
                    <option value="<?= $value ?>"
                        <?= selected($filters['types'] ?? '', $value, false); ?>>
                        <?= $type['description'][$lang]; ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>
    </div>

      <!-- Botones -->
      <div class="search-form-buttons">
          <a href="<?= esc_url($actionUrl); ?>" class="reset-button text-white" data-translate="Reset"><?php echo T_('Reset') ?></a>
          <button type="submit" class="search-button" data-translate="Search"><?php echo T_('Search'); ?></button>
      </div>
      
      </form>
    </div>
    
      <!-- Campo de referencia arriba -->

  </div>
    <div class="total-items-and-order">
        <div class="total-items">
            <span class="label"><?php echo T_('Total:') ?></span>
            <span>
                <?= $total_items ?>
                <?php echo $total_items === 1 ? T_('Property') : T_('Properties') ?>
            </span>
        </div>
        <form id="orderBy" class="filter-selector">
              <?php $selected_order = isset($_GET['order_by']) ? sanitize_text_field($_GET['order_by']) : ''; ?>
              <select name="order_by" id="order_by">
                  <option value=""><?php echo T_('Order by') ?></option>
                  <?php foreach($orders as $order): ?>
                    <option 
                        value="<?= esc_attr($order['slug']) ?>"
                        <?= selected($selected_order, $order['slug'], false); ?>
                    ><?= $order['name']?></option>
                  <?php endforeach;?>
              </select>
              <button type="submit" class="search-button"><?php echo T_('Order') ?></button>
          </form>
    </div>
    <?php 
        $props = $body;
    ?>
        <?php if(!isset($props)): ?>
            <p><?php echo T_('No properties were found.') ?></p>
            <?php else: ?>
                <div class="properties-container 
                <?= esc_attr($options['layout'] === 'vertical' ? 'vertical-layout' : 'horizontal-layout'); ?>
                size-<?= esc_attr($options['cardSize']); ?> <?php echo $layout;?>">
            <?php foreach($props as $prop):?>
                <?php
                    $lang = explode('_', get_locale())[0] ?? 'es';

                    $ref = $prop['reference']
                        ?? ($prop['_id']['$oid'] ?? ($prop['_id'] ?? ''));

                    $title = $prop['titles'][$lang]
                        ?? ($prop['titles']['es'] ?? ($prop['titles']['en'] ?? ''));

                    $imageUrl = $prop['images'] ?? null; // ahora viene como string

                    $price = $prop['price'] ?? null;
                    $location = $prop['municipality']['name']
                        ?? $prop['district']['name']
                        ?? 'Málaga';
                    $beds  = $prop['beds']  ?? null;
                    $baths = $prop['baths'] ?? null;
                    $built = $prop['built'] ?? null;
                    $plot  = $prop['plot']  ?? null;

                    $municipalityName = $prop['municipality']['name'] ?? null;
                ?>

                <a href="<?= esc_url($route); ?>/<?= $ref ?>" target="_blank" data-ref="<?= esc_attr($ref) ?>" class="card-preview
                    <?= esc_attr($options['cardSize']); ?>
                    <?= esc_attr($options['layout'] === 'vertical' ? 'vertical' : 'horizontal'); ?>">

                    <div class="container-img">
                        <img
                            src="<?= esc_url($imageUrl ?: 'https://via.placeholder.com/800x600?text=No+image'); ?>"
                            alt="property-image"
                            class="property-image"
                        >

                        <p class="prop-ref">#<?= esc_html($ref);?></p>
                    </div>
                    <div class="container-info <?php $options['layout'];?>">
                        <?php
                        $in = [
                            'en' => 'in',
                            'es' => 'en',
                            'fr' => 'à',
                            'da' => 'i',
                            'de' => 'in',
                            'no' => 'i',
                            'fi' => 'ssa', 
                            'ru' => 'в',
                            'sv' => 'i'
                        ];
                        ;?>
                        <div>
                            <?php $lang = explode('_', get_locale())[0] ?? 'es';?>
                            <h4 class="property-loc"><?= $prop['type'][$lang] . ' en ' . $location?></h4>
                            <hr class="line-hor">
                        </div>
                        <div id="priceOut" class="price">
                            <?php if (isset($prop['price'])): ?>
                                <?php if ($prop['price'] === $prop['price']): ?>
                                    <span class="value"><?= number_format($prop['price']); ?> €</span>
                                    <i  class="fa-solid fa-tags icon"></i>
                                <?php else: ?>
                                    <div class="span-info">
                                        <?php if (isset($prop['price'])): ?>
                                            <span class="value"><?= number_format($prop['price']); ?></span>
                                        <?php endif; ?>
                                    </div>
                                <?php endif; ?>
                            <?php endif; ?>   
                        </div>
                        <div class="property-info">
                            <?php if($options['layout'] === 'vertical'):?>
                                <div id="price-out" class="price">
                                    <?php if (!empty($price)): ?>
                                        <span class="value"><?= number_format((int)$price); ?> €</span>
                                        <i class="fa-solid fa-tags icon"></i>
                                    <?php endif; ?>
                                </div>
                            <?php endif;?>
                                <div class="grid-templates <?= $options['layout'] === 'horizontal' ? 'horizontal' : 'vertical';?>">
                                <?php if($options['layout'] === 'horizontal'):?>
                                    <div id="price-in" class="grid">
                                        <?php if (!empty($price)): ?>
                                            <span class="value"><?= number_format((int)$price); ?> €</span>
                                            <i class="fa-solid fa-tags icon"></i>
                                        <?php endif; ?>
                                    </div>
                                <?php endif;?>
                                <div class="grid">
                                    <?php if ($beds !== null): ?>
                                    <div class="grid">
                                        <label class="label"><?php echo T_('Beds');?>:</label>
                                        <div class="info-and-icon">
                                        <span class="value"><?= esc_html((int)$beds); ?></span>
                                        <i class="fa-solid fa-bed icon"></i>
                                        </div>
                                    </div>
                                    <?php endif; ?>
                                </div>
                                
                                <!-- Baños -->
                                <div class="grid">
                                    <?php if ($baths !== null): ?>
                                        <div class="grid">
                                            <label class="label"><?php echo T_('Baths');?>:</label>
                                            <div class="info-and-icon">
                                            <span class="value"><?= esc_html((int)$baths); ?></span>
                                            <i class="fa-solid fa-bath icon"></i>
                                            </div>
                                        </div>
                                    <?php endif; ?>
                                </div>

                                <!-- Área construida -->
                                <?php if ($built !== null): ?>
                                <div class="grid">
                                    <label class="label"><?php echo T_('Built area');?></label>
                                    <div class="info-and-icon">
                                    <span class="value"><?= esc_html((int)$built); ?> m²</span>
                                    <i class="fa-solid fa-ruler-combined icon"></i>
                                    </div>
                                </div>
                                <?php endif; ?>

                                <?php if ($plot !== null): ?>
                                    <div class="grid" id="plotArea">
                                        <label class="label"><?php echo T_('Plot area');?>:</label>
                                        <div class="info-and-icon">
                                        <span class="value"><?= esc_html((int)$plot); ?> m²</span>
                                        <i class="fa-solid fa-mountain-city icon"></i>
                                        </div>
                                    </div>
                                <?php endif; ?>
                                <?php if($options['layout'] === 'vertical'):?>
                                    <div class="grid">
                                        <?php if (isset($prop['units_available'])): ?>
                                            <label class="label"><?php echo T_('Units available');?>:</label>
                                            <?php if ($prop['units_available'] === $prop['max_built_area']): ?>
                                                <span class="value"><?= esc_html($prop['units_available']); ?> m²</span>
                                            <?php else: ?>
                                                <div class="span-info">
                                                    <?php if (isset($prop['units_available'])): ?>
                                                        <span class="value"><?= esc_html($prop['units_available']); ?></span>
                                                        <i class="fa-solid fa-layer-group icon"></i>
                                                    <?php endif; ?>
                                                </div>
                                            <?php endif; ?>
                                        <?php endif; ?>
                                    </div>
                                <?php endif;?>
                            </div>
                                <?php if ($options['layout'] === 'horizontal'):?>
                                    <div class="units-box">
                                        <?php if (isset($prop['units_available'])): ?>
                                            <label class="label"><?php echo T_('Units available') ?></label>
                                            <?php if ($prop['units_available'] === $prop['max_built_area']): ?>
                                                <span class="value"><?= esc_html($prop['units_available']); ?> m²</span>
                                            <?php else: ?>
                                                <div class="span-info">
                                                    <?php if (isset($prop['units_available'])): ?>
                                                        <span class="value"><?= esc_html($prop['units_available']); ?></span>
                                                    <?php endif; ?>
                                                </div>
                                            <?php endif; ?>
                                        <?php endif; ?>
                                    </div>
                                <?php endif;?>
                            </div>
                    </div>
                </a>
            <?php endforeach; ?>
        </div>
        <?php 
            $currentPage = isset($_GET['page']) ? intval($_GET['page']) : 1;
            $perPage = 20;
            $totalPages = ceil($total_items / $perPage);

            $params = $_GET;
            unset($params['page']); 
            $base_url = strtok($_SERVER["REQUEST_URI"], '?');
            $query_string = http_build_query($params);
            $base_link = $base_url . ($query_string ? '?' . $query_string . '&' : '?');

            $start = max(1, $currentPage - 2);
            $end = min($totalPages, $currentPage + 2);
            ?>

            <?php if ($totalPages > 1): ?>
            <div class="pagination-preview" style="margin-top:30px; text-align:center;">
                <div style="display:inline-flex; gap:10px; align-items:center;">
                    <!-- Botones Inicio / Anterior -->
                    <a class="pagination arrow" href="<?php echo esc_url($base_link . 'page=1'); ?>">«</a>
                    <a class="pagination arrow" href="<?php echo esc_url($base_link . 'page=' . max(1, $currentPage - 1)); ?>">‹</a>

                    <!-- Páginas intermedias -->
                    <?php for ($i = $start; $i <= $end; $i++): ?>
                        <?php
                            $isCurrent = ($i === $currentPage);
                            if($isCurrent){
                                $class = "current";
                            }else{
                                $class = 'other';
                            }
                        ?>
                        <a class="pagination <?php echo $class;?>" href="<?php echo esc_url($base_link . 'page=' . $i); ?>" style="<?php echo esc_attr($styles); ?>">
                            <?php echo $i; ?>
                        </a>
                    <?php endfor; ?>

                    <!-- Botones Siguiente / Último -->
                    <a class="pagination arrow " href="<?php echo esc_url($base_link . 'page=' . min($totalPages, $currentPage + 1)); ?>">›</a>
                    <a class="pagination arrow" href="<?php echo esc_url($base_link . 'page=' . $totalPages); ?>">»</a>
                </div>
                <div style="margin-top:10px; font-size:0.9rem; color:#666;">
                    Página <?php echo $currentPage; ?> de <?php echo $totalPages; ?>
                </div>
            </div>
            <?php endif; ?>

    <?php endif; ?>
    <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>
    base_url = '<?= esc_url($route); ?>';
    document.getElementById('searchForm').addEventListener('submit', function(e) {
        e.preventDefault();
        const ref = this.querySelector('[name="reference"]').value.trim().toUpperCase();
        if (ref) {
            window.location.href = `${base_url}/${encodeURIComponent(ref)}`;
        }
    });
    
</script>

<script>
document.addEventListener('DOMContentLoaded', () => {
  const dropdownBtn = document.getElementById('areaDropdown');
  const dropdownContent = document.getElementById('dropdownCont');
  const checkboxes = dropdownContent.querySelectorAll('input[type="checkbox"]');

  let selectedSpan = dropdownBtn.querySelector('.selected-items');
  if (!selectedSpan) {
    selectedSpan = document.createElement('span');
    selectedSpan.className = 'selected-items';
    dropdownBtn.insertBefore(selectedSpan, dropdownBtn.querySelector('.arrow'));
  }
  let placeholder = dropdownBtn.querySelector('.placeholder');
  if (!placeholder) {
    placeholder = document.createElement('span');
    placeholder.className = 'placeholder';
    placeholder.textContent = 'Select areas';
    dropdownBtn.insertBefore(placeholder, dropdownBtn.querySelector('.arrow'));
  }

  dropdownBtn.addEventListener('click', (e) => {
    e.stopPropagation();
    dropdownContent.classList.toggle('active');
  });
  document.addEventListener('click', (e) => {
    if (!dropdownBtn.contains(e.target) && !dropdownContent.contains(e.target)) {
      dropdownContent.classList.remove('active');
    }
  });

  // Actualizar texto del botón
  function updateSelectedText() {
    const selected = Array.from(checkboxes)
      .filter(cb => cb.checked)
      .map(cb => cb.value);

    if (selected.length === 0) {
      placeholder.style.display = 'inline';
      selectedSpan.textContent = '';
    } else {
      placeholder.style.display = 'none';
      selectedSpan.textContent = selected.join(', ');
    }
  }

  // Eventos
  checkboxes.forEach(cb => cb.addEventListener('change', updateSelectedText));

  // Inicial
  updateSelectedText();
});
const logoZoddak = document.getElementById('zoddakLogo');
logoZoddak.addEventListener('click', () => {
    window.open('https://www.zoddak.com', '_blank');
})
</script>
