<?php
/**
 * Plugin Name: DARWEB Sync
 * Plugin URI:  https://darweb.ma
 * Description: Synchronise vos annonces immobilières WordPress avec la plateforme DARWEB. Compatible Houzez, RealHomes, Essential Real Estate, WPL Pro et Custom Post Types.
 * Version:     1.0.0
 * Author:      DARWEB
 * Author URI:  https://darweb.ma
 * License:     GPL v2 or later
 * Text Domain: darweb-sync
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

define( 'DARWEB_SYNC_VERSION', '1.0.0' );

class DarwebSync {

	private $option_prefix = 'darweb_sync_';

	public function __construct() {
		add_action( 'rest_api_init',    [ $this, 'register_routes' ] );
		add_action( 'save_post',        [ $this, 'on_save_post' ], 20, 3 );
		add_action( 'before_delete_post', [ $this, 'on_delete_post' ] );
		add_action( 'wp_trash_post',    [ $this, 'on_trash_post' ] );
		add_action( 'admin_menu',       [ $this, 'add_admin_menu' ] );
		add_action( 'admin_init',       [ $this, 'register_settings' ] );
	}

	/* -----------------------------------------------------------------------
	 * Plugin detection
	 * -------------------------------------------------------------------- */

	public function detect_plugin(): string {
		if ( defined( 'HOUZEZ_VERSION' ) || function_exists( 'houzez_setup' ) ) {
			return 'houzez';
		}
		if ( defined( 'REALHOMES_FRAMEWORK_VERSION' ) || function_exists( 'inspiry_get_property_details' ) ) {
			return 'real-homes';
		}
		if ( class_exists( 'Essential_Real_Estate' ) || post_type_exists( 're_listing' ) ) {
			return 'essential-re';
		}
		if ( defined( 'WPL_ABSPATH' ) || class_exists( 'WPL_Global' ) ) {
			return 'wpl';
		}
		if ( post_type_exists( 'property' ) ) {
			return 'custom';
		}
		return 'unknown';
	}

	/* -----------------------------------------------------------------------
	 * REST API routes
	 * -------------------------------------------------------------------- */

	public function register_routes() {
		register_rest_route( 'darweb/v1', '/properties', [
			'methods'             => 'GET',
			'callback'            => [ $this, 'rest_get_properties' ],
			'permission_callback' => [ $this, 'check_api_key' ],
		] );

		register_rest_route( 'darweb/v1', '/test', [
			'methods'             => 'GET',
			'callback'            => [ $this, 'rest_test' ],
			'permission_callback' => [ $this, 'check_api_key' ],
		] );
	}

	public function check_api_key( $request ): bool {
		$stored_key = get_option( $this->option_prefix . 'api_key', '' );
		if ( empty( $stored_key ) ) {
			return false;
		}
		$provided = sanitize_text_field( $request->get_param( 'api_key' ) ?? '' );
		return hash_equals( $stored_key, $provided );
	}

	public function rest_test( $request ): WP_REST_Response {
		return new WP_REST_Response( [
			'success'         => true,
			'plugin_version'  => DARWEB_SYNC_VERSION,
			'detected_plugin' => $this->detect_plugin(),
			'wp_version'      => get_bloginfo( 'version' ),
			'site_name'       => get_bloginfo( 'name' ),
			'site_url'        => get_site_url(),
		] );
	}

	public function rest_get_properties( $request ): WP_REST_Response {
		$detected = $this->detect_plugin();
		$page     = max( 1, intval( $request->get_param( 'page' ) ?? 1 ) );
		$per_page = min( 200, max( 1, intval( $request->get_param( 'per_page' ) ?? 100 ) ) );

		switch ( $detected ) {
			case 'houzez':
				$items = $this->get_houzez_properties( $page, $per_page );
				break;
			case 'real-homes':
				$items = $this->get_realhomes_properties( $page, $per_page );
				break;
			case 'essential-re':
				$items = $this->get_essential_re_properties( $page, $per_page );
				break;
			case 'wpl':
				$items = $this->get_wpl_properties( $page, $per_page );
				break;
			default:
				$items = $this->get_generic_properties( $page, $per_page );
				break;
		}

		return new WP_REST_Response( [
			'properties'    => $items['properties'],
			'total'         => $items['total'],
			'total_pages'   => $items['total_pages'],
			'page'          => $page,
			'per_page'      => $per_page,
			'detected_plugin' => $detected,
		] );
	}

	/* -----------------------------------------------------------------------
	 * Houzez theme
	 * -------------------------------------------------------------------- */

	private function get_houzez_properties( int $page, int $per_page ): array {
		$query = new WP_Query( [
			'post_type'      => 'property',
			'post_status'    => 'publish',
			'posts_per_page' => $per_page,
			'paged'          => $page,
		] );

		$items = [];
		foreach ( $query->posts as $post ) {
			$meta   = get_post_meta( $post->ID );
			$cities = wp_get_post_terms( $post->ID, 'property_city', [ 'fields' => 'names' ] );
			$types  = wp_get_post_terms( $post->ID, 'property_type', [ 'fields' => 'names' ] );
			$status = wp_get_post_terms( $post->ID, 'property_status', [ 'fields' => 'names' ] );

			$items[] = $this->normalize( [
				'id'            => $post->ID,
				'title'         => $post->post_title,
				'description'   => wp_strip_all_tags( $post->post_content ),
				'price'         => $this->meta( $meta, 'fave_property_price' ),
				'property_type' => ! empty( $types ) ? $types[0] : '',
				'purpose'       => $this->map_houzez_status( ! empty( $status ) ? $status[0] : '' ),
				'city'          => ! empty( $cities ) ? $cities[0] : $this->meta( $meta, 'fave_property_map_address' ),
				'address'       => $this->meta( $meta, 'fave_property_map_address' ),
				'latitude'      => $this->meta( $meta, 'fave_property_map_latitude' ),
				'longitude'     => $this->meta( $meta, 'fave_property_map_longitude' ),
				'surface'       => $this->meta( $meta, 'fave_property_size' ),
				'bedrooms'      => $this->meta( $meta, 'fave_property_bedrooms' ),
				'bathrooms'     => $this->meta( $meta, 'fave_property_bathrooms' ),
				'rooms'         => $this->meta( $meta, 'fave_property_rooms' ),
				'garage'        => $this->meta( $meta, 'fave_property_garage' ),
				'year_built'    => $this->meta( $meta, 'fave_property_year' ),
				'furnished'     => $this->meta( $meta, 'fave_furnished' ),
				'has_pool'      => $this->meta( $meta, 'fave_property_pool' ),
				'has_garage'    => $this->meta( $meta, 'fave_property_garage' ),
				'images'        => $this->get_post_images( $post->ID ),
				'published_at'  => $post->post_date_gmt,
			] );
		}

		return [
			'properties' => $items,
			'total'      => $query->found_posts,
			'total_pages' => $query->max_num_pages,
		];
	}

	private function map_houzez_status( string $s ): string {
		$map = [
			'for-sale'    => 'for-sale',
			'for-rent'    => 'for-rent',
			'À vendre'    => 'for-sale',
			'À louer'     => 'for-rent',
			'Vente'       => 'for-sale',
			'Location'    => 'for-rent',
		];
		return $map[ $s ] ?? 'for-sale';
	}

	/* -----------------------------------------------------------------------
	 * RealHomes / Inspiry theme
	 * -------------------------------------------------------------------- */

	private function get_realhomes_properties( int $page, int $per_page ): array {
		$query = new WP_Query( [
			'post_type'      => 'property',
			'post_status'    => 'publish',
			'posts_per_page' => $per_page,
			'paged'          => $page,
		] );

		$items = [];
		foreach ( $query->posts as $post ) {
			$meta     = get_post_meta( $post->ID );
			$location = $this->meta( $meta, 'REAL_HOMES_property_location' );
			$lat = $lng = '';
			if ( strpos( $location, ',' ) !== false ) {
				[ $lat, $lng ] = array_map( 'trim', explode( ',', $location, 2 ) );
			}
			$types   = wp_get_post_terms( $post->ID, 'property-type', [ 'fields' => 'names' ] );
			$cities  = wp_get_post_terms( $post->ID, 'property-city', [ 'fields' => 'names' ] );

			$items[] = $this->normalize( [
				'id'            => $post->ID,
				'title'         => $post->post_title,
				'description'   => wp_strip_all_tags( $post->post_content ),
				'price'         => $this->meta( $meta, 'REAL_HOMES_property_price' ),
				'property_type' => ! empty( $types ) ? $types[0] : '',
				'purpose'       => $this->meta( $meta, 'REAL_HOMES_property_status' ) ?: 'for-sale',
				'city'          => ! empty( $cities ) ? $cities[0] : '',
				'address'       => $this->meta( $meta, 'REAL_HOMES_property_address' ),
				'latitude'      => $lat,
				'longitude'     => $lng,
				'surface'       => $this->meta( $meta, 'REAL_HOMES_property_size' ),
				'bedrooms'      => $this->meta( $meta, 'REAL_HOMES_property_bedrooms' ),
				'bathrooms'     => $this->meta( $meta, 'REAL_HOMES_property_bathrooms' ),
				'garage'        => $this->meta( $meta, 'REAL_HOMES_garage' ),
				'year_built'    => $this->meta( $meta, 'REAL_HOMES_year_built' ),
				'images'        => $this->get_post_images( $post->ID ),
				'published_at'  => $post->post_date_gmt,
			] );
		}

		return [
			'properties' => $items,
			'total'      => $query->found_posts,
			'total_pages' => $query->max_num_pages,
		];
	}

	/* -----------------------------------------------------------------------
	 * Essential Real Estate
	 * -------------------------------------------------------------------- */

	private function get_essential_re_properties( int $page, int $per_page ): array {
		$query = new WP_Query( [
			'post_type'      => 're_listing',
			'post_status'    => 'publish',
			'posts_per_page' => $per_page,
			'paged'          => $page,
		] );

		$items = [];
		foreach ( $query->posts as $post ) {
			$meta  = get_post_meta( $post->ID );
			$types = wp_get_post_terms( $post->ID, 'essential-real-estate-category', [ 'fields' => 'names' ] );

			$items[] = $this->normalize( [
				'id'            => $post->ID,
				'title'         => $post->post_title,
				'description'   => wp_strip_all_tags( $post->post_content ),
				'price'         => $this->meta( $meta, 're_price' ),
				'property_type' => ! empty( $types ) ? $types[0] : '',
				'purpose'       => $this->meta( $meta, 're_status' ) ?: 'for-sale',
				'city'          => $this->meta( $meta, 're_city' ),
				'address'       => $this->meta( $meta, 're_address' ),
				'region'        => $this->meta( $meta, 're_state' ),
				'latitude'      => $this->meta( $meta, 're_latitude' ),
				'longitude'     => $this->meta( $meta, 're_longitude' ),
				'surface'       => $this->meta( $meta, 're_size' ),
				'surface_terrain' => $this->meta( $meta, 're_land_area' ),
				'bedrooms'      => $this->meta( $meta, 're_bedrooms' ),
				'bathrooms'     => $this->meta( $meta, 're_bathrooms' ),
				'garage'        => $this->meta( $meta, 're_garage' ),
				'year_built'    => $this->meta( $meta, 're_year_built' ),
				'furnished'     => $this->meta( $meta, 're_furnished' ),
				'images'        => $this->get_post_images( $post->ID ),
				'published_at'  => $post->post_date_gmt,
			] );
		}

		return [
			'properties' => $items,
			'total'      => $query->found_posts,
			'total_pages' => $query->max_num_pages,
		];
	}

	/* -----------------------------------------------------------------------
	 * WPL Pro / Realia
	 * -------------------------------------------------------------------- */

	private function get_wpl_properties( int $page, int $per_page ): array {
		global $wpdb;

		$offset = ( $page - 1 ) * $per_page;
		$total  = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->prefix}wpl_properties WHERE status = 1 AND deleted = 0" );

		$rows = $wpdb->get_results(
			$wpdb->prepare(
				"SELECT * FROM {$wpdb->prefix}wpl_properties WHERE status = 1 AND deleted = 0 ORDER BY id DESC LIMIT %d OFFSET %d",
				$per_page,
				$offset
			),
			ARRAY_A
		);

		$items = [];
		foreach ( $rows as $row ) {
			$items[] = $this->normalize( [
				'id'            => $row['id'],
				'title'         => $row['alias'] ?? ( 'Property ' . $row['id'] ),
				'description'   => $row['full_description'] ?? '',
				'price'         => $row['price'] ?? 0,
				'property_type' => $row['property_type'] ?? '',
				'purpose'       => ( $row['listing_type'] ?? 'sale' ) === 'rent' ? 'for-rent' : 'for-sale',
				'city'          => $row['location_text'] ?? '',
				'address'       => $row['address'] ?? '',
				'region'        => $row['city'] ?? '',
				'latitude'      => $row['latitude'] ?? '',
				'longitude'     => $row['longitude'] ?? '',
				'surface'       => $row['area'] ?? 0,
				'bedrooms'      => $row['bedroom_no'] ?? 0,
				'bathrooms'     => $row['bathroom_no'] ?? 0,
				'floor'         => $row['floor'] ?? null,
				'year_built'    => $row['year_built'] ?? null,
				'images'        => $this->get_wpl_images( $row['id'] ),
				'published_at'  => $row['creation_date'] ?? current_time( 'mysql', true ),
			] );
		}

		return [
			'properties' => $items,
			'total'      => $total,
			'total_pages' => (int) ceil( $total / $per_page ),
		];
	}

	private function get_wpl_images( int $property_id ): array {
		global $wpdb;
		$rows = $wpdb->get_results(
			$wpdb->prepare(
				"SELECT * FROM {$wpdb->prefix}wpl_property_attachments WHERE parent_id = %d AND type = 'image' ORDER BY orderby ASC",
				$property_id
			),
			ARRAY_A
		);
		$images = [];
		foreach ( $rows as $row ) {
			if ( ! empty( $row['res_path'] ) ) {
				$images[] = [ 'url' => WPL_ABSPATH . $row['res_path'], 'caption' => '' ];
			}
		}
		return $images;
	}

	/* -----------------------------------------------------------------------
	 * Generic / Custom CPT
	 * -------------------------------------------------------------------- */

	private function get_generic_properties( int $page, int $per_page ): array {
		$query = new WP_Query( [
			'post_type'      => 'property',
			'post_status'    => 'publish',
			'posts_per_page' => $per_page,
			'paged'          => $page,
		] );

		$items = [];
		foreach ( $query->posts as $post ) {
			$meta = get_post_meta( $post->ID );
			$items[] = $this->normalize( [
				'id'            => $post->ID,
				'title'         => $post->post_title,
				'description'   => wp_strip_all_tags( $post->post_content ),
				'price'         => $this->meta_any( $meta, [ 'price', 'property_price', '_price', 'real_price' ] ),
				'property_type' => $this->meta_any( $meta, [ 'property_type', '_property_type', 'type' ] ),
				'purpose'       => $this->meta_any( $meta, [ 'status', 'listing_type', 'property_status', '_status' ] ) ?: 'for-sale',
				'city'          => $this->meta_any( $meta, [ 'city', 'ville', '_city', 'property_city' ] ),
				'address'       => $this->meta_any( $meta, [ 'address', 'adresse', '_address' ] ),
				'region'        => $this->meta_any( $meta, [ 'region', 'state', '_region' ] ),
				'latitude'      => $this->meta_any( $meta, [ 'latitude', 'lat', '_latitude' ] ),
				'longitude'     => $this->meta_any( $meta, [ 'longitude', 'lng', 'long', '_longitude' ] ),
				'surface'       => $this->meta_any( $meta, [ 'size', 'area', 'surface', 'surface_habitable', '_size' ] ),
				'surface_terrain' => $this->meta_any( $meta, [ 'land_area', 'surface_terrain', 'plot_area' ] ),
				'bedrooms'      => $this->meta_any( $meta, [ 'bedrooms', 'chambres', '_bedrooms', 'rooms' ] ),
				'bathrooms'     => $this->meta_any( $meta, [ 'bathrooms', 'salles_bain', '_bathrooms' ] ),
				'year_built'    => $this->meta_any( $meta, [ 'year_built', 'year', '_year_built', 'annee' ] ),
				'furnished'     => $this->meta_any( $meta, [ 'furnished', 'meuble', '_furnished' ] ),
				'images'        => $this->get_post_images( $post->ID ),
				'published_at'  => $post->post_date_gmt,
			] );
		}

		return [
			'properties' => $items,
			'total'      => $query->found_posts,
			'total_pages' => $query->max_num_pages,
		];
	}

	/* -----------------------------------------------------------------------
	 * Image helpers
	 * -------------------------------------------------------------------- */

	private function get_post_images( int $post_id ): array {
		$images       = [];
		$thumbnail_id = get_post_thumbnail_id( $post_id );
		if ( $thumbnail_id ) {
			$src = wp_get_attachment_image_src( $thumbnail_id, 'full' );
			if ( $src ) {
				$images[] = [ 'url' => $src[0], 'caption' => get_the_title( $thumbnail_id ) ];
			}
		}
		$gallery = get_post_meta( $post_id, 'fave_property_images', true )
			?: get_post_meta( $post_id, 'REAL_HOMES_property_images', true )
			?: get_post_meta( $post_id, '_property_gallery', true )
			?: [];

		if ( is_string( $gallery ) ) {
			$gallery = array_filter( array_map( 'trim', explode( ',', $gallery ) ) );
		}

		foreach ( (array) $gallery as $attachment_id ) {
			if ( ! is_numeric( $attachment_id ) ) {
				continue;
			}
			$already = array_column( $images, 'url' );
			$src     = wp_get_attachment_image_src( (int) $attachment_id, 'full' );
			if ( $src && ! in_array( $src[0], $already, true ) ) {
				$images[] = [ 'url' => $src[0], 'caption' => get_the_title( $attachment_id ) ];
			}
		}

		return $images;
	}

	/* -----------------------------------------------------------------------
	 * Meta helpers
	 * -------------------------------------------------------------------- */

	private function meta( array $meta, string $key ): string {
		return isset( $meta[ $key ][0] ) ? $meta[ $key ][0] : '';
	}

	private function meta_any( array $meta, array $keys ): string {
		foreach ( $keys as $key ) {
			if ( isset( $meta[ $key ][0] ) && $meta[ $key ][0] !== '' ) {
				return $meta[ $key ][0];
			}
		}
		return '';
	}

	private function normalize( array $data ): array {
		return [
			'id'               => $data['id'],
			'title'            => $data['title'] ?? '',
			'description'      => $data['description'] ?? '',
			'price'            => $data['price'] ?? 0,
			'property_type'    => $data['property_type'] ?? '',
			'purpose'          => $data['purpose'] ?? 'for-sale',
			'city'             => $data['city'] ?? '',
			'region'           => $data['region'] ?? '',
			'district'         => $data['district'] ?? '',
			'address'          => $data['address'] ?? '',
			'postal_code'      => $data['postal_code'] ?? '',
			'latitude'         => $data['latitude'] ?? '',
			'longitude'        => $data['longitude'] ?? '',
			'surface'          => $data['surface'] ?? '',
			'surface_habitable'=> $data['surface_habitable'] ?? $data['surface'] ?? '',
			'surface_terrain'  => $data['surface_terrain'] ?? '',
			'rooms'            => $data['rooms'] ?? '',
			'bedrooms'         => $data['bedrooms'] ?? '',
			'bathrooms'        => $data['bathrooms'] ?? '',
			'floor'            => $data['floor'] ?? '',
			'year_built'       => $data['year_built'] ?? '',
			'condition'        => $data['condition'] ?? '',
			'furnished'        => $data['furnished'] ?? '',
			'has_pool'         => $data['has_pool'] ?? $data['pool'] ?? '',
			'has_garden'       => $data['has_garden'] ?? $data['garden'] ?? '',
			'has_terrace'      => $data['has_terrace'] ?? $data['terrace'] ?? '',
			'has_balcony'      => $data['has_balcony'] ?? $data['balcony'] ?? '',
			'has_garage'       => $data['has_garage'] ?? $data['garage'] ?? '',
			'has_parking'      => $data['has_parking'] ?? $data['parking'] ?? '',
			'has_elevator'     => $data['has_elevator'] ?? $data['elevator'] ?? '',
			'has_ac'           => $data['has_ac'] ?? $data['air_conditioning'] ?? '',
			'has_heating'      => $data['has_heating'] ?? $data['heating'] ?? '',
			'has_equipped_kitchen' => $data['has_equipped_kitchen'] ?? '',
			'has_security'     => $data['has_security'] ?? $data['security'] ?? '',
			'has_gated_residence' => $data['has_gated_residence'] ?? $data['gated'] ?? '',
			'has_sea_view'     => $data['has_sea_view'] ?? $data['sea_view'] ?? '',
			'has_mountain_view'=> $data['has_mountain_view'] ?? $data['mountain_view'] ?? '',
			'is_waterfront'    => $data['is_waterfront'] ?? $data['waterfront'] ?? '',
			'near_beach'       => $data['near_beach'] ?? '',
			'near_transport'   => $data['near_transport'] ?? '',
			'near_city_center' => $data['near_city_center'] ?? '',
			'near_shops'       => $data['near_shops'] ?? '',
			'developer_name'   => $data['developer_name'] ?? '',
			'archived'         => false,
			'images'           => $data['images'] ?? [],
			'published_at'     => $data['published_at'] ?? current_time( 'mysql', true ),
		];
	}

	/* -----------------------------------------------------------------------
	 * Webhook sender
	 * -------------------------------------------------------------------- */

	private function get_property_post_types(): array {
		return [ 'property', 're_listing', 'wpl_property' ];
	}

	public function on_save_post( int $post_id, WP_Post $post, bool $update ) {
		if ( wp_is_post_revision( $post_id ) || wp_is_post_autosave( $post_id ) ) {
			return;
		}
		if ( ! in_array( $post->post_type, $this->get_property_post_types(), true ) ) {
			return;
		}
		if ( $post->post_status !== 'publish' ) {
			return;
		}

		$webhook_url    = get_option( $this->option_prefix . 'webhook_url', '' );
		$webhook_secret = get_option( $this->option_prefix . 'webhook_secret', '' );
		$config_id      = get_option( $this->option_prefix . 'config_id', '' );

		if ( empty( $webhook_url ) || empty( $webhook_secret ) || empty( $config_id ) ) {
			return;
		}

		$property = $this->get_single_property( $post_id );
		if ( ! $property ) {
			return;
		}

		$payload = wp_json_encode( [
			'config_id' => $config_id,
			'event'     => $update ? 'updated' : 'created',
			'property'  => $property,
		] );

		$signature = 'sha256=' . hash_hmac( 'sha256', $payload, $webhook_secret );

		wp_remote_post( $webhook_url, [
			'headers'   => [
				'Content-Type'       => 'application/json',
				'X-Darweb-Signature' => $signature,
			],
			'body'      => $payload,
			'timeout'   => 10,
			'blocking'  => false,
		] );
	}

	public function on_delete_post( int $post_id ) {
		$this->send_delete_webhook( $post_id, 'deleted' );
	}

	public function on_trash_post( int $post_id ) {
		$this->send_delete_webhook( $post_id, 'trashed' );
	}

	private function send_delete_webhook( int $post_id, string $event ) {
		$post = get_post( $post_id );
		if ( ! $post || ! in_array( $post->post_type, $this->get_property_post_types(), true ) ) {
			return;
		}

		$webhook_url    = get_option( $this->option_prefix . 'webhook_url', '' );
		$webhook_secret = get_option( $this->option_prefix . 'webhook_secret', '' );
		$config_id      = get_option( $this->option_prefix . 'config_id', '' );

		if ( empty( $webhook_url ) || empty( $webhook_secret ) || empty( $config_id ) ) {
			return;
		}

		$payload = wp_json_encode( [
			'config_id' => $config_id,
			'event'     => $event,
			'property'  => [ 'id' => $post_id ],
		] );

		$signature = 'sha256=' . hash_hmac( 'sha256', $payload, $webhook_secret );

		wp_remote_post( $webhook_url, [
			'headers'   => [
				'Content-Type'       => 'application/json',
				'X-Darweb-Signature' => $signature,
			],
			'body'      => $payload,
			'timeout'   => 10,
			'blocking'  => false,
		] );
	}

	private function get_single_property( int $post_id ): ?array {
		$detected = $this->detect_plugin();
		$post     = get_post( $post_id );
		if ( ! $post ) {
			return null;
		}

		$meta = get_post_meta( $post_id );

		switch ( $detected ) {
			case 'houzez':
				$cities = wp_get_post_terms( $post_id, 'property_city', [ 'fields' => 'names' ] );
				$types  = wp_get_post_terms( $post_id, 'property_type', [ 'fields' => 'names' ] );
				$status = wp_get_post_terms( $post_id, 'property_status', [ 'fields' => 'names' ] );
				return $this->normalize( [
					'id'            => $post_id,
					'title'         => $post->post_title,
					'description'   => wp_strip_all_tags( $post->post_content ),
					'price'         => $this->meta( $meta, 'fave_property_price' ),
					'property_type' => ! empty( $types ) ? $types[0] : '',
					'purpose'       => $this->map_houzez_status( ! empty( $status ) ? $status[0] : '' ),
					'city'          => ! empty( $cities ) ? $cities[0] : '',
					'address'       => $this->meta( $meta, 'fave_property_map_address' ),
					'latitude'      => $this->meta( $meta, 'fave_property_map_latitude' ),
					'longitude'     => $this->meta( $meta, 'fave_property_map_longitude' ),
					'surface'       => $this->meta( $meta, 'fave_property_size' ),
					'bedrooms'      => $this->meta( $meta, 'fave_property_bedrooms' ),
					'bathrooms'     => $this->meta( $meta, 'fave_property_bathrooms' ),
					'has_garage'    => $this->meta( $meta, 'fave_property_garage' ),
					'year_built'    => $this->meta( $meta, 'fave_property_year' ),
					'images'        => $this->get_post_images( $post_id ),
					'published_at'  => $post->post_date_gmt,
				] );

			case 'real-homes':
				$location = $this->meta( $meta, 'REAL_HOMES_property_location' );
				$lat = $lng = '';
				if ( strpos( $location, ',' ) !== false ) {
					[ $lat, $lng ] = array_map( 'trim', explode( ',', $location, 2 ) );
				}
				$types  = wp_get_post_terms( $post_id, 'property-type', [ 'fields' => 'names' ] );
				$cities = wp_get_post_terms( $post_id, 'property-city', [ 'fields' => 'names' ] );
				return $this->normalize( [
					'id'            => $post_id,
					'title'         => $post->post_title,
					'description'   => wp_strip_all_tags( $post->post_content ),
					'price'         => $this->meta( $meta, 'REAL_HOMES_property_price' ),
					'property_type' => ! empty( $types ) ? $types[0] : '',
					'purpose'       => $this->meta( $meta, 'REAL_HOMES_property_status' ) ?: 'for-sale',
					'city'          => ! empty( $cities ) ? $cities[0] : '',
					'address'       => $this->meta( $meta, 'REAL_HOMES_property_address' ),
					'latitude'      => $lat,
					'longitude'     => $lng,
					'surface'       => $this->meta( $meta, 'REAL_HOMES_property_size' ),
					'bedrooms'      => $this->meta( $meta, 'REAL_HOMES_property_bedrooms' ),
					'bathrooms'     => $this->meta( $meta, 'REAL_HOMES_property_bathrooms' ),
					'images'        => $this->get_post_images( $post_id ),
					'published_at'  => $post->post_date_gmt,
				] );

			default:
				return $this->normalize( [
					'id'           => $post_id,
					'title'        => $post->post_title,
					'description'  => wp_strip_all_tags( $post->post_content ),
					'price'        => $this->meta_any( $meta, [ 'price', 'property_price', '_price' ] ),
					'property_type'=> $this->meta_any( $meta, [ 'property_type', '_property_type', 'type' ] ),
					'purpose'      => $this->meta_any( $meta, [ 'status', 'listing_type', '_status' ] ) ?: 'for-sale',
					'city'         => $this->meta_any( $meta, [ 'city', 'ville', '_city' ] ),
					'address'      => $this->meta_any( $meta, [ 'address', '_address' ] ),
					'latitude'     => $this->meta_any( $meta, [ 'latitude', 'lat', '_latitude' ] ),
					'longitude'    => $this->meta_any( $meta, [ 'longitude', 'lng', '_longitude' ] ),
					'surface'      => $this->meta_any( $meta, [ 'size', 'area', 'surface', '_size' ] ),
					'bedrooms'     => $this->meta_any( $meta, [ 'bedrooms', 'chambres', '_bedrooms' ] ),
					'bathrooms'    => $this->meta_any( $meta, [ 'bathrooms', '_bathrooms' ] ),
					'images'       => $this->get_post_images( $post_id ),
					'published_at' => $post->post_date_gmt,
				] );
		}
	}

	/* -----------------------------------------------------------------------
	 * Admin settings
	 * -------------------------------------------------------------------- */

	public function add_admin_menu() {
		add_options_page(
			'DARWEB Sync',
			'DARWEB Sync',
			'manage_options',
			'darweb-sync',
			[ $this, 'render_settings_page' ]
		);
	}

	public function register_settings() {
		$fields = [ 'api_key', 'webhook_url', 'webhook_secret', 'config_id' ];
		foreach ( $fields as $field ) {
			register_setting( 'darweb_sync_settings', $this->option_prefix . $field, [
				'sanitize_callback' => 'sanitize_text_field',
			] );
		}
	}

	public function render_settings_page() {
		$detected   = $this->detect_plugin();
		$api_key    = get_option( $this->option_prefix . 'api_key', '' );
		$webhook_url = get_option( $this->option_prefix . 'webhook_url', '' );
		$webhook_secret = get_option( $this->option_prefix . 'webhook_secret', '' );
		$config_id  = get_option( $this->option_prefix . 'config_id', '' );
		$rest_url   = rest_url( 'darweb/v1/properties' );
		?>
		<div class="wrap">
			<h1>
				<span style="color:#133dbd;">&#9632;</span> DARWEB Sync
				<span style="font-size:12px;font-weight:400;color:#666;margin-left:8px;">v<?php echo esc_html( DARWEB_SYNC_VERSION ); ?></span>
			</h1>

			<div style="background:#fff;border:1px solid #ddd;border-radius:6px;padding:20px 24px;margin-bottom:20px;max-width:700px;">
				<h2 style="margin-top:0;font-size:15px;border-bottom:1px solid #eee;padding-bottom:10px;">Statut de détection</h2>
				<table style="width:100%;font-size:13px;">
					<tr>
						<td style="padding:6px 0;color:#555;width:200px;">Plugin immobilier détecté</td>
						<td><strong style="color:#133dbd;"><?php echo esc_html( $detected ); ?></strong></td>
					</tr>
					<tr>
						<td style="padding:6px 0;color:#555;">Endpoint REST</td>
						<td><code style="font-size:11px;"><?php echo esc_url( $rest_url ); ?></code></td>
					</tr>
				</table>
			</div>

			<div style="background:#fff;border:1px solid #ddd;border-radius:6px;padding:20px 24px;max-width:700px;">
				<h2 style="margin-top:0;font-size:15px;border-bottom:1px solid #eee;padding-bottom:10px;">Configuration DARWEB</h2>
				<p style="color:#555;font-size:13px;margin-top:0;">
					Copiez ces valeurs depuis votre tableau de bord DARWEB → Import WordPress.
				</p>
				<form method="post" action="options.php">
					<?php settings_fields( 'darweb_sync_settings' ); ?>
					<table class="form-table" style="font-size:13px;">
						<tr>
							<th scope="row" style="width:180px;">
								<label for="darweb_api_key">Clé API DARWEB</label>
							</th>
							<td>
								<input type="text" id="darweb_api_key" name="<?php echo esc_attr( $this->option_prefix . 'api_key' ); ?>"
									value="<?php echo esc_attr( $api_key ); ?>" class="regular-text" style="font-family:monospace;"
									placeholder="Collez votre clé API ici" />
								<p class="description">Copiez depuis DARWEB Dashboard → Import WordPress → Clé API</p>
							</td>
						</tr>
						<tr>
							<th scope="row"><label for="darweb_config_id">Config ID</label></th>
							<td>
								<input type="text" id="darweb_config_id" name="<?php echo esc_attr( $this->option_prefix . 'config_id' ); ?>"
									value="<?php echo esc_attr( $config_id ); ?>" class="regular-text" style="font-family:monospace;"
									placeholder="UUID de la configuration" />
								<p class="description">L'identifiant de votre configuration dans DARWEB</p>
							</td>
						</tr>
						<tr>
							<th scope="row"><label for="darweb_webhook_url">URL Webhook</label></th>
							<td>
								<input type="url" id="darweb_webhook_url" name="<?php echo esc_attr( $this->option_prefix . 'webhook_url' ); ?>"
									value="<?php echo esc_url( $webhook_url ); ?>" class="regular-text"
									placeholder="https://...supabase.co/functions/v1/wp-webhook" />
								<p class="description">Copiez depuis DARWEB Dashboard → Import WordPress → URL Webhook</p>
							</td>
						</tr>
						<tr>
							<th scope="row"><label for="darweb_webhook_secret">Secret Webhook</label></th>
							<td>
								<input type="password" id="darweb_webhook_secret" name="<?php echo esc_attr( $this->option_prefix . 'webhook_secret' ); ?>"
									value="<?php echo esc_attr( $webhook_secret ); ?>" class="regular-text" style="font-family:monospace;"
									placeholder="Clé secrète HMAC SHA-256" />
								<p class="description">Copiez depuis DARWEB Dashboard → Import WordPress → Secret Webhook</p>
							</td>
						</tr>
					</table>
					<?php submit_button( 'Enregistrer la configuration', 'primary', 'submit', true ); ?>
				</form>
			</div>

			<?php if ( ! empty( $api_key ) && ! empty( $config_id ) ) : ?>
			<div style="background:#f0f7ff;border:1px solid #b3d4f5;border-radius:6px;padding:16px 24px;margin-top:16px;max-width:700px;">
				<h3 style="margin:0 0 8px;font-size:14px;color:#133dbd;">Connexion configurée</h3>
				<p style="margin:0;font-size:13px;color:#333;">
					Le plugin enverra automatiquement les mises à jour vers DARWEB à chaque publication ou suppression d'annonce.<br>
					Pour importer toutes vos annonces existantes, utilisez le bouton <strong>Importer toutes les annonces</strong> dans votre tableau de bord DARWEB.
				</p>
			</div>
			<?php endif; ?>
		</div>
		<?php
	}
}

new DarwebSync();
