<?php
if (!defined('ABSPATH')) exit;
$route = home_url(get_option('zoddak_custom_route'));
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'=>'town',
        'name' => T_('Town')
    ],
    [
        'slug'=>'place',
        'name' => T_('Place')
    ],
    [
        'slug' => 'prop_types',
        '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('zoddak_custom_route','propiedades'), '/' ) . '/' );
?>
<?php echo apply_filters('zoddak_listings_before', ''); ?>

<div class="zoddak-page-wrapper">
    <?php 
        $hideLangSelector = get_option('zoddak_lang_selector',0);
    ?>
    
    
    <div class="search-menu-preview" >
      <h3 data-translate="Search Properties"><?php echo T_('Search developments') ?></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"
                
                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); ?>">
      <!-- Selectores -->
      <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" <?= !empty($selected_towns) ? 'style="display:none"' : '' ?>>
                    <?php echo T_('Select');?>
                </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 ($areasToShow as $provinceData): ?>

                    <?php
                        $provinceName = $provinceData['province'] ?? '';
                        $towns        = $provinceData['towns'] ?? [];
                        if ($provinceName === '' || empty($towns) || !is_array($towns)) continue;
                    ?>

                    <div class="province-group">
                        <strong class="province-title"><?= esc_html($provinceName) ?></strong>
                            <?php foreach ($towns as $townData): ?>
                                <?php
                                    $townName = $townData['town'] ?? '';
                                    if ($townName === '') continue;

                                    $town_checked = in_array($townName, $selected_towns, true) ? 'checked' : '';
                                    $places = $townData['places'] ?? [];
                                ?>

                                <div class="group">
                                    <strong class="town"><?= esc_html($townName) ?></strong>

                                    <label>
                                        <input
                                            type="checkbox"
                                            name="towns[]"
                                            value="<?= esc_attr($townName) ?>"
                                            <?= $town_checked ?>
                                        >
                                        <?= esc_html($townName) ?>
                                    </label>

                                    <?php if (!empty($places) && is_array($places)): ?>
                                        <?php foreach ($places as $place): ?>
                                            <?php
                                                if (empty($place)) continue;
                                                // Evita duplicar el town si viene repetido en places
                                                if (strcasecmp($place, $townName) === 0) continue;

                                                $checked = in_array($place, $selected_towns, true) ? 'checked' : '';
                                            ?>
                                            <label>
                                                <input
                                                    type="checkbox"
                                                    name="places[]"
                                                    value="<?= esc_attr($place) ?>"
                                                    <?= $checked ?>
                                                >
                                                <?= esc_html($place) ?>
                                            </label>
                                        <?php endforeach; ?>
                                    <?php endif; ?>

                                </div>
                            <?php endforeach; ?>

                        </div>
                    <?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');?></option>

                <?php foreach ($typesToShow as $type): ?>
                    <?php $value = strtolower($type); ?>
                    <option value="<?= $value ?>"
                        <?= selected($filters['prop_types'] ?? '', $value, false); ?>>
                        <?= $type ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>
                <div class="filter-selector">
                    <label for="stages"><?php echo T_('Stages');?></label>
                    <?php $selected_stage = isset($_GET['stages']) ? sanitize_text_field($_GET['stages']) : ''; ?>
                    <select name="stages" id="">
                        <option value=""><?php echo T_('Select'); ?></option>
                        
                        <?php foreach ($visibleStages as $stage): ?>
                            <option value="<?= esc_attr($stage['id']); ?>" <?= selected($selected_stage, $stage['id'], false); ?>>
                                <?= esc_html($stage['label']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
            
        </div>
        
        <!-- Botones -->
        <div class="search-form-buttons">
            <a href="<?= esc_url($actionUrl); ?>" class="reset-button" 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 
        $devs = $body;
    ?>
        <?php if(!isset($devs)): ?>
            <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($devs as $dev):?>
                <a href="<?=esc_url($route); ?>/<?= $dev['reference'] ?>"  class="card-preview
                    <?= esc_attr($options['cardSize']); ?>
                    <?= esc_attr($options['layout'] === 'vertical' ? 'vertical' : 'horizontal'); ?>" data-ref="<?php echo $dev['reference'];?>">
                    <div class="container-img">
                        <?php 
                        $imgSize = '';
                        if($options['layout'] === 'vertical'){
                            $imgSize = 'images_md';
                        }else{
                            $imgSize = 'images_lg';
                        };?>
                        <img src="<?= esc_url($dev[$imgSize][0]); ?>" alt="small-image" class="property-image">
                        <?php
                            $stageNames = [
                                // id 1 - Próximamente / Coming soon
                                1 => ['Próximamente', 'Coming soon', 'Snart til salg', 'Demnächst', 'Prochainement', 'Binnenkort beschikbaar', 'Kommer snart', 'Tulossa pian', 'Скоро в продаже', 'Kommer snart'],

                                // id 3 - Sobre plano / Offplan
                                3 => ['Sobre plano', 'Offplan', 'Sælges fra plantegning', 'Projekt in Planung', 'Sur plan', 'Op plan', 'Selges fra tegninger', 'Myydään suunnitelmista', 'Продажа по плану', 'Säljes från ritning'],

                                // id 4 - Con licencia / With licence
                                4 => ['Con licencia', 'With licence', 'Med byggetilladelse', 'Mit Baugenehmigung', 'Avec permis de construire', 'Met bouwvergunning', 'Med byggetillatelse', 'Rakennusluvalla', 'С разрешением на строительство', 'Med bygglov'],

                                // id 5 - Comenzado / Started
                                5 => ['Comenzado', 'Started', 'Under opførelse', 'Im Bau', 'En construction', 'In aanbouw', 'Byggingen er i gang', 'Rakentaminen aloitettu', 'Строительство началось', 'Byggstartad'],

                                // id 6 - Terminado / Completed
                                6 => ['Terminado', 'Completed', 'Færdiggjort', 'Fertiggestellt', 'Terminé', 'Voltooid', 'Ferdigstilt', 'Valmistunut', 'Завершено', 'Färdigställt'],
                            ];

                            $currentStage = $dev['stage'] ?? ''; 

                            $stageId = null;
                            foreach ($stageNames as $id => $names) {
                                if (in_array($currentStage, $names, true)) {
                                    $stageId = $id;
                                    break;
                                }
                            }
                            switch ($stageId) {
                                case 1:
                                    $stageColor = '#9b59b6';
                                    break;
                                case 3:
                                    $stageColor = '#02198dff';
                                    break;
                                case 4:
                                    $stageColor = '#e67e22';
                                    break;
                                case 5:
                                    $stageColor = '#5bb0e9ff';
                                    break;
                                case 6:
                                    $stageColor = '#2ecc71';
                                    break;
                                default:
                                    $stageColor = 'red';
                                    break;
                            }
                            $completed = in_array($currentStage, $stageNames[6], true) ? 'completed' : '';
                            ?>

                        <?php if (isset($dev['stage'])): ?>
                            <span class="stage-badge">
                                <span class="stage-dot <?= esc_attr($completed); ?>" style="background-color:<?= esc_attr($stageColor); ?>;"></span>
                                <?= esc_html($currentStage); ?>
                            </span>
                        <?php endif; ?>
                        <p class="prop-ref">#<?= esc_html($dev['reference']);?></p>
                    </div>
                    <div class="container-info <?php $options['layout'];?>">
                        <?php
                        $in = [
                            'en' => 'in',
                            'es' => 'en',
                            'fr' => 'à',
                            'da' => 'i',
                            'de' => 'in',
                            'no' => 'i',
                            'fi' => 'ssa', // normalmente se añade al final de la palabra, pero "ssa" es la raíz
                            'ru' => 'в',
                            'sv' => 'i'
                        ];
                        ;?>
                        <div>
                            <h4 class="property-loc"><?= esc_html($dev['prop_type']) . ' ';?> <?php echo T_('in');?> <?= esc_html($dev['town'] ?? 'Ubicación no disponible'); ?></h4>
                            <hr class="line-hor">
                        </div>
                        <div id="priceOut" class="price">
                            <?php if (isset($dev['min_price']) || isset($dev['max_price'])): ?>
                                <?php if ($dev['min_price'] === $dev['max_price']): ?>
                                    <span class="value"><?= number_format($dev['min_price']); ?> €</span>
                                    <i  class="fa-solid fa-tags icon"></i>
                                <?php else: ?>
                                    <div class="span-info">
                                        <?php if (isset($dev['min_price'])): ?>
                                            <span class="value"><?= number_format($dev['min_price']); ?></span>
                                        <?php endif; ?>
                                        <span>-</span>
                                        <?php if (isset($dev['max_price'])): ?>
                                            <span class="value"><?= number_format($dev['max_price']); ?> €</span>
                                            <i  class="fa-solid fa-tags icon"></i>
                                        <?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 (isset($dev['min_price']) || isset($dev['max_price'])): ?>
                                        <?php if ($dev['min_price'] === $dev['max_price']): ?>
                                            <span class="value"><?= number_format($dev['min_price']); ?> €</span>
                                            <i  class="fa-solid fa-tags icon"></i>
                                        <?php else: ?>
                                            <div class="span-info">
                                                <?php if (isset($dev['min_price'])): ?>
                                                    <span class="value"><?= number_format($dev['min_price']); ?></span>
                                                <?php endif; ?>
                                                <span>-</span>
                                                <?php if (isset($dev['max_price'])): ?>
                                                    <span class="value"><?= number_format($dev['max_price']); ?> €</span>
                                                    <i  class="fa-solid fa-tags icon"></i>
                                                <?php endif; ?>
                                            </div>
                                        <?php endif; ?>
                                    <?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 (isset($dev['min_price']) || isset($dev['max_price'])): ?>
                                            <label class="label"> <?php echo T_('Price:');?></label>
                                            <?php if ($dev['min_price'] === $dev['max_price']): ?>
                                                <span class="value"><?=$dev['price_title'] . ' ';?><?= number_format($dev['min_price']); ?> €</span>
                                                <i  class="fa-solid fa-tags icon"></i>
                                            <?php else: ?>
                                                <div class="span-info">
                                                    <?php if (isset($dev['min_price'])): ?>
                                                        <span class="value"><?= number_format($dev['min_price']); ?></span>
                                                    <?php endif; ?>
                                                    <span>-</span>
                                                    <?php if (isset($dev['max_price'])): ?>
                                                        <span class="value"><?= number_format($dev['max_price']); ?> €</span>
                                                    <?php endif; ?>
                                                </div>
                                            <?php endif; ?>
                                        <?php endif; ?>   
                                    </div>
                                <?php endif;?>
                                <div class="grid">
                                    <?php if (isset($dev['min_beds']) || isset($dev['max_beds'])): ?>
                                        <label class="label"><?php echo T_('Beds');?>:</label>
                                        <?php if ($dev['min_beds'] === $dev['max_beds']): ?>
                                            <div class="info-and-icon">
                                                <span class="value"><?= esc_html($dev['min_beds']); ?></span>
                                                <i class="fa-solid fa-bed icon"></i>
                                            </div>
                                        <?php else: ?>
                                            <div class="span-info">
                                                <?php if (isset($dev['min_beds'])): ?>
                                                    <span class="value"><?= esc_html($dev['min_beds']); ?></span>
                                                <?php endif; ?>
                                                <span>-</span>
                                                <?php if (isset($dev['max_beds'])): ?>
                                                    <span class="value"><?= esc_html($dev['max_beds']); ?></span>
                                                    <i class="fa-solid fa-bed icon"></i>
                                                <?php endif; ?>
                                            </div>
                                        <?php endif; ?>
                                    <?php endif; ?>
                                </div>
                                
                                <!-- Baños -->
                                <div class="grid">
                                    <?php if (isset($dev['min_baths']) || isset($dev['max_baths'])): ?>
                                        <label class="label"><?php echo T_('Baths');?>:</label>
                                        <?php if ($dev['min_baths'] === $dev['max_baths']): ?>
                                            <div class="info-and-icon">
                                                <span class="value"><?= esc_html($dev['min_baths']); ?></span>
                                                <i class="fa-solid fa-bath icon"></i>
                                            </div>
                                        <?php else: ?>
                                            <div class="span-info">
                                                <?php if (isset($dev['min_baths'])): ?>
                                                    <span class="value"><?= esc_html($dev['min_baths']); ?></span>
                                                <?php endif; ?>
                                                <span>-</span>
                                                <?php if (isset($dev['max_baths'])): ?>
                                                    <span class="value"><?= esc_html($dev['max_baths']); ?></span>
                                                    <i class="fa-solid fa-bath icon"></i>
                                                <?php endif; ?>
                                            </div>
                                        <?php endif; ?>
                                    <?php endif; ?>
                                </div>

                                <!-- Área construida -->
                                <?php if (isset($dev['min_built_area']) || isset($dev['max_built_area'])): ?>
                                    <div class="grid">
                                        <label class="label"><?php echo T_('Built area');?></label>
                                        <?php if ($dev['min_built_area'] === $dev['max_built_area']): ?>
                                            <div class="info-and-icon">
                                                <span class="value"><?= esc_html($dev['min_built_area']); ?> m²</span>
                                                <i class="fa-solid fa-ruler-combined icon"></i>
                                            </div>

                                        <?php else: ?>
                                            <div class="span-info">
                                                <?php if (isset($dev['min_built_area'])): ?>
                                                    <span class="value"><?= esc_html($dev['min_built_area']); ?></span>
                                                <?php endif; ?>
                                                <span>-</span>
                                                <?php if (isset($dev['max_built_area'])): ?>
                                                    <span class="value"><?= esc_html($dev['max_built_area']); ?> m²</span>
                                                    <i class="fa-solid fa-ruler-combined icon"></i>
                                                <?php endif; ?>
                                            </div>
                                        <?php endif; ?>
                                    </div>
                                <?php endif; ?>
                                <?php if (isset($dev['min_plot_area']) || isset($dev['max_plot_area'])): ?>
                                    <div id="plotArea" class="grid">
                                        <label class="label"><?php echo T_('Plot area');?>:</label>
                                        <?php if ($dev['min_plot_area'] === $dev['max_plot_area']): ?>
                                            <div class="info-and-icon">
                                                <span class="value"><?= esc_html($dev['min_plot_area']); ?> m²</span>
                                                <i class="fa-solid fa-mountain-city icon"></i>
                                            </div>
                                            
                                        <?php else: ?>
                                            <div class="span-info">
                                                <?php if (isset($dev['min_plot_area'])): ?>
                                                    <span class="value"><?= esc_html($dev['min_plot_area']); ?></span>
                                                <?php endif; ?>
                                                <span>-</span>
                                                <?php if (isset($dev['max_plot_area'])): ?>
                                                    <span class="value"><?= esc_html($dev['max_plot_area']); ?> m²</span>
                                                    <i class="fa-solid fa-mountain-city icon"></i>

                                                <?php endif; ?>
                                            </div>
                                        <?php endif; ?>
                                    </div>
                                <?php endif; ?>
                                <?php if($options['layout'] === 'vertical'):?>
                                    <div class="grid">
                                        <?php if (isset($dev['units_available'])): ?>
                                            <label class="label"><?php echo T_('Units available');?>:</label>
                                            <?php if ($dev['units_available'] === $dev['max_built_area']): ?>
                                                <span class="value"><?= esc_html($dev['units_available']); ?> m²</span>
                                            <?php else: ?>
                                                <div class="span-info">
                                                    <?php if (isset($dev['units_available'])): ?>
                                                        <span class="value"><?= esc_html($dev['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($dev['units_available'])): ?>
                                            <label class="label"><?php echo T_('Units available') ?></label>
                                            <?php if ($dev['units_available'] === $dev['max_built_area']): ?>
                                                <span class="value"><?= esc_html($dev['units_available']); ?> m²</span>
                                            <?php else: ?>
                                                <div class="span-info">
                                                    <?php if (isset($dev['units_available'])): ?>
                                                        <span class="value"><?= esc_html($dev['units_available']); ?></span>
                                                    <?php endif; ?>
                                                </div>
                                            <?php endif; ?>
                                        <?php endif; ?>
                                    </div>
                                <?php endif;?>
                            </div>
                    </div>
                </a>
                </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;">
                    <?= T_('Page') ?> <?php echo $currentPage; ?> <?= T_('of') ?> <?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_PLUGIN_URL . 'images/zoddak.png' ?>" alt="zoddak logo">
    </div>
</div>
<?php echo apply_filters('zoddak_listings_after', ''); ?>


<?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();
    //         if (ref) {
    //         window.open(`${base_url}/${encodeURIComponent(ref)}`, '_blank');
    //     }
    // });
    
</script>

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

  // Garantiza que existan ambos spans
  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'));
  }

  // Abrir/cerrar
  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>
