<?php
// EN: If this file is called directly, abort.
// IT: Se questo file viene chiamato direttamente, interrompi.
if (! defined('ABSPATH')) exit; // Exit
/*
|---------------------------------------------------------------------------
| FILE
|---------------------------------------------------------------------------
| FROM → service/houzez/runner-import.ptp
| TO   → WordPress (Houzez Theme) Property Posts
| Function: update_meta, update_taxonomy, get_postid_bymeta
| DESCRIPTION:
| Updates existing properties in WordPress using XML feed data,
| specifically for the Houzez theme.
| Updates title, content, metadata, taxonomies, images, floorplans if changed.
*/

if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly
}

/**
 * EN: Update class for Houzez properties, extending the generic ManagerProcessor.
 * IT: Classe di aggiornamento immobili Houzez, estende il ManagerProcessor generico.
 */
class PKINEX_UpdateRealHouzez extends PKINEX_ManagerProcessor
{
    private SimpleXMLElement $source_data;
    private string $id_name;
    private array $list_id_update;

    public function __construct(SimpleXMLElement $source_data, string $id_name, array $list_id_update)
    {
        parent::__construct(true); // Load options if needed

        $this->source_data = $source_data;
        $this->id_name = $id_name;
        $this->list_id_update = array_flip($list_id_update);
    }

    /**
     * Main update loop
     */
    public function pkinex_update_real_houzez(): void
    {
        // EN: Build once: map "external code → post_id" for all Houzez properties.
        // IT: Costruisce una sola volta la mappa "codice esterno → post_id" per tutte le proprietà Houzez.
        $map_codice_post = $this->pkinex_build_postid_map_by_meta('property', $this->id_name);

        // EN: If map is empty, nothing to update.
        // IT: Se la mappa è vuota, non c'è nulla da aggiornare.
        if (empty($map_codice_post)) {
            return;
        }

        // EN: Main update loop.
        // IT: Ciclo principale di aggiornamento.
        foreach ($this->source_data->immobili->immobile as $immobile) {

            // 1) CODICE COME STRINGA (IMPORTANTISSIMO: niente intval qui)
            $codice = trim((string) $immobile->{$this->id_name});
            if ($codice === '') {
                continue;
            }

            // 2) Se questo codice NON è nella lista update → salta
            if (! isset($this->list_id_update[$codice])) {
                continue;
            }

            // 3) Recupera il post_id dalla mappa (niente più WP_Query per ogni immobile)
            $post_id = $map_codice_post[$codice] ?? 0;
            if ($post_id <= 0) {
                continue;
            }

            $post = get_post($post_id);
            if (! $post) {
                continue;
            }

            $update_args     = ['ID' => $post_id];
            $needs_post_save = false;

            // ----------------------
            // POST TITLE
            // ----------------------
            $new_title = sanitize_text_field((string) $immobile->Titolo);
            if ($post->post_title !== $new_title && $new_title !== '') {
                $update_args['post_title'] = $new_title;
                $needs_post_save           = true;
            }

            // ----------------------
            // POST CONTENT
            // ----------------------
            $new_content = wp_kses_post((string) $immobile->AnnuncioCompleto);
            if ($post->post_content !== $new_content && $new_content !== '') {
                $update_args['post_content'] = $new_content;
                $needs_post_save             = true;
            }

            if ($needs_post_save) {
                wp_update_post($update_args);
            }

            // ----------------------
            // META FIELDS
            // ----------------------
            $this->pkinex_update_meta($post_id, 'fave_property_id', sanitize_text_field((string) $immobile->Riferimento));
            $this->pkinex_update_meta($post_id, 'fave_property_price', floatval($immobile->Costo));
            $this->pkinex_update_meta($post_id, 'fave_property_size', floatval($immobile->Mq));
            $this->pkinex_update_meta($post_id, 'fave_property_size_prefix', 'Mq');
            $this->pkinex_update_meta($post_id, 'fave_agent_display_option', 'agent_info');
            $this->pkinex_update_meta($post_id, 'fave_property_rooms', intval($immobile->Locali));
            $this->pkinex_update_meta($post_id, 'fave_property_garage', sanitize_text_field((string) $immobile->Box));
            $this->pkinex_update_meta($post_id, 'fave_property_year', intval($immobile->AnnoCostruzione));
            $this->pkinex_update_meta($post_id, 'fave_energy_class', sanitize_text_field((string) $immobile->ACE));

            $energyValue = (string) $immobile->IEE . ' ' . (string) $immobile->unita_misura_IEE;
            $this->pkinex_update_meta($post_id, 'fave_energy_global_index', sanitize_text_field($energyValue));

            $featured = strtolower(trim((string) $immobile->Evidenza)) === 'si' ? 1 : 0;
            $this->pkinex_update_meta($post_id, 'fave_featured', $featured);

            // ----------------------
            // ADDRESS META
            // ----------------------
            $lat = round(floatval((string) $immobile->Lat), 7);
            $lng = round(floatval((string) $immobile->Lng), 7);

            $this->pkinex_update_meta($post_id, 'fave_property_address', sanitize_text_field((string) $immobile->Indirizzo));
            $this->pkinex_update_meta($post_id, 'fave_property_zip', intval($immobile->CAP));
            $this->pkinex_update_meta($post_id, 'fave_property_city', sanitize_text_field((string) $immobile->Comune));
            $this->pkinex_update_meta($post_id, 'houzez_geolocation_lat', $lat);
            $this->pkinex_update_meta($post_id, 'houzez_geolocation_long', $lng);

            $location = "{$lat},{$lng},14";
            $this->pkinex_update_meta($post_id, 'fave_property_location', sanitize_text_field($location));

            $full_address = (string) $immobile->Indirizzo . ', ' . $immobile->CAP . ' ' . $immobile->Comune;
            $this->pkinex_update_meta($post_id, 'fave_property_map_address', sanitize_text_field($full_address));

            // ----------------------
            // TAXONOMIES
            // ----------------------
            $slugStatus = strtolower(trim((string) $immobile->Contratto)) === 'vendita' ? 'for-sale' : 'for-rent';
            $this->pkinex_update_taxonomy($post_id, 'property_status', $slugStatus);
            $this->pkinex_update_taxonomy($post_id, 'property_area', trim((string) $immobile->Zona));
            $this->pkinex_update_taxonomy($post_id, 'property_type', trim((string) $immobile->Tipologia));
            $this->pkinex_update_taxonomy($post_id, 'property_city', trim((string) $immobile->Comune));

            // ----------------------
            // GALLERY & FLOORPLAN
            // ----------------------
            $this->pkinex_update_gallery($post_id, $immobile);
            $this->pkinex_update_plan($post_id, (string) $immobile->Planimetria);
        }
    }
}
