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

/**
 * Centralized property data retrieval.
 * All templates use this instead of scattered get_post_meta() calls.
 */
class IPP_Property_Helper {

    private $post_id;
    private $display_fields;

    public function __construct( $post_id = null ) {
        $this->post_id = $post_id ?: get_the_ID();
        $defaults = IntegratePalace_Properties_Settings::get_default_display_fields();
        $this->display_fields = get_option( 'ipp_display_fields', $defaults );
        if ( empty( $this->display_fields ) ) {
            $this->display_fields = $defaults;
        }
    }

    /**
     * Check if a field group is enabled for display.
     */
    public function show( $field_key ) {
        return in_array( $field_key, $this->display_fields, true );
    }

    /**
     * Get a meta value with ipp_ prefix, falling back to legacy key.
     */
    public function meta( $key, $legacy_key = '' ) {
        $val = get_post_meta( $this->post_id, 'ipp_' . $key, true );
        if ( empty( $val ) && $legacy_key ) {
            $val = get_post_meta( $this->post_id, $legacy_key, true );
        }
        return $val;
    }

    // ─── Core Info ──────────────────────────────────────────────────

    public function property_code()    { return $this->meta( 'property_code', 'information_property_code' ); }
    public function status()           { return $this->meta( 'status', 'property_status' ); }
    public function archived()         { return $this->meta( 'archived' ); }
    public function management_type()  { return $this->meta( 'management_type', 'property_management_type' ); }
    public function name()             { return $this->meta( 'name' ); }

    // ─── Address ────────────────────────────────────────────────────

    public function address1()   { return $this->meta( 'address1', 'street_number' ); }
    public function address2()   { return $this->meta( 'address2', 'street_name' ); }
    public function address3()   { return $this->meta( 'address3', 'property_city' ); }
    public function address4()   { return $this->meta( 'address4' ); }
    public function unit()       { return $this->meta( 'unit' ); }
    public function postcode()   { return $this->meta( 'postcode', 'zipcode' ); }
    public function suburb()     { return $this->meta( 'suburb', 'information_suburb' ); }
    public function region()     { return $this->meta( 'region', 'information_region' ); }

    public function full_address() {
        $parts = array_filter( [ $this->address1(), $this->address2(), $this->address3() ] );
        return implode( ', ', $parts );
    }

    public function short_address() {
        return trim( $this->address3() . ', ' . $this->address1() . ' ' . $this->address2(), ', ' );
    }

    // ─── Financial ──────────────────────────────────────────────────

    public function rent()           { return $this->meta( 'rent_amount', 'information_rent' ); }
    public function rental_period()  { return $this->meta( 'rental_period', 'property_rental_period' ); }
    public function market_value()   { return $this->meta( 'market_value' ); }

    public function formatted_rent() {
        $rent = $this->rent();
        if ( empty( $rent ) ) return '';
        $period = $this->rental_period();
        $formatted = '$' . number_format( (float) $rent, 0 );
        if ( $period ) {
            $formatted .= ' / ' . strtolower( $period );
        }
        return $formatted;
    }

    // ─── Dates ──────────────────────────────────────────────────────

    public function date_available() { return $this->meta( 'date_available', 'information_date' ); }
    public function start_date()     { return $this->meta( 'start_date' ); }

    public function formatted_date_available() {
        $date = $this->date_available();
        if ( empty( $date ) ) return '';
        $ts = strtotime( $date );
        if ( ! $ts ) return $date;
        if ( $ts <= time() ) return __( 'Available Now', 'integrate-palace-properties' );
        return date_i18n( get_option( 'date_format' ), $ts );
    }

    // ─── Accommodation ──────────────────────────────────────────────

    public function bedrooms()   { return $this->meta( 'bedrooms', 'accommodation_bed_room' ); }
    public function bathrooms()  { return $this->meta( 'bathrooms', 'accommodation_bath_room' ); }
    public function ensuites()   { return $this->meta( 'ensuites' ); }
    public function cars()       { return $this->meta( 'cars', 'accommodation_automobile' ); }
    public function parking()    { return $this->meta( 'parking', 'other_parking' ); }

    // ─── Features ───────────────────────────────────────────────────

    public function property_class()    { return $this->meta( 'class', 'property_class' ); }
    public function year_built()        { return $this->meta( 'year_built', 'property_year_built' ); }
    public function stories()           { return $this->meta( 'stories' ); }
    public function furnishings()       { return $this->meta( 'furnishings' ); }
    public function new_construction()  { return $this->meta( 'new_construction' ); }
    public function amenities()         { return $this->meta( 'amenities' ); }
    public function floor_area()        { return $this->meta( 'floor_area' ); }
    public function land_area_sqm()     { return $this->meta( 'land_area_sqm' ); }
    public function land_area_hectares(){ return $this->meta( 'land_area_hectares' ); }

    public function pets_allowed()     { return (bool) $this->meta( 'pets_allowed', 'other_pets' ); }
    public function smokers_allowed()  { return (bool) $this->meta( 'smokers_allowed', 'property_smokers_allowed' ); }

    // ─── Links & Media ──────────────────────────────────────────────

    public function virtual_tour_url()     { return $this->meta( 'virtual_tour_url', 'property_virtual_tour_url' ); }
    public function web_link_url()         { return $this->meta( 'web_link_url' ); }
    public function geographic_location()  { return $this->meta( 'geographic_location', 'property_geographic_location' ); }
    public function advert_text()          { return $this->meta( 'advert_text' ); }
    public function feature_details()      { return $this->meta( 'feature_details' ); }
    public function header()               { return $this->meta( 'header' ); }

    /**
     * Get gallery image IDs.
     */
    public function gallery() {
        $gallery = get_post_meta( $this->post_id, 'integrate_palace_gallery', true );
        return is_array( $gallery ) ? $gallery : [];
    }

    /**
     * Get gallery image URLs with sizes.
     */
    public function gallery_images( $size = 'large' ) {
        $images = [];
        foreach ( $this->gallery() as $id ) {
            $url = wp_get_attachment_image_url( intval( $id ), $size );
            $thumb = wp_get_attachment_image_url( intval( $id ), 'thumbnail' );
            $full = wp_get_attachment_image_url( intval( $id ), 'full' );
            if ( $url ) {
                $images[] = [
                    'id'    => intval( $id ),
                    'url'   => $url,
                    'thumb' => $thumb ?: $url,
                    'full'  => $full ?: $url,
                    'alt'   => get_post_meta( intval( $id ), '_wp_attachment_image_alt', true ),
                ];
            }
        }
        return $images;
    }

    public function featured_image( $size = 'large' ) {
        $thumb_id = get_post_thumbnail_id( $this->post_id );
        if ( ! $thumb_id ) {
            return null;
        }
        $img = wp_get_attachment_image_src( $thumb_id, $size );
        if ( ! $img ) {
            return null;
        }
        return array(
            'url' => $img[0],
            'alt' => get_post_meta( $thumb_id, '_wp_attachment_image_alt', true ),
        );
    }

    // ─── Agent ──────────────────────────────────────────────────────

    public function agent_code()         { return $this->meta( 'agent_code', 'agent_code' ); }
    public function agent_name()         { return $this->meta( 'agent_full_name', 'agent_full_name' ); }
    public function agent_title()        { return $this->meta( 'agent_title', 'agent_title' ); }
    public function agent_email()        { return $this->meta( 'agent_email1', 'agent_email1' ); }
    public function agent_email2()       { return $this->meta( 'agent_email2', 'agent_email2' ); }
    public function agent_phone_mobile() { return $this->meta( 'agent_phone_mobile', 'agent_phone_mobile' ); }
    public function agent_phone_work()   { return $this->meta( 'agent_phone_work', 'agent_phone_work' ); }

    // ─── Map ────────────────────────────────────────────────────────

    public function has_map_coords() {
        $loc = $this->geographic_location();
        return ! empty( $loc ) && strpos( $loc, ':' ) !== false;
    }

    public function map_lat() {
        $loc = $this->geographic_location();
        $parts = explode( ':', $loc );
        return isset( $parts[0] ) ? floatval( $parts[0] ) : 0;
    }

    public function map_lng() {
        $loc = $this->geographic_location();
        $parts = explode( ':', $loc );
        return isset( $parts[1] ) ? floatval( $parts[1] ) : 0;
    }

    public function map_embed_url() {
        if ( $this->has_map_coords() ) {
            return 'https://maps.google.com/maps?q=' . $this->map_lat() . ',' . $this->map_lng() . '&z=15&output=embed';
        }
        $addr = urlencode( $this->full_address() );
        return 'https://maps.google.com/maps?q=' . $addr . '&z=15&output=embed';
    }

    // ─── Custom Fields ──────────────────────────────────────────────

    public function custom_fields() {
        $json = get_post_meta( $this->post_id, 'ipp_custom_fields', true );
        if ( empty( $json ) ) return [];
        $decoded = json_decode( $json, true );
        return is_array( $decoded ) ? $decoded : [];
    }

    // ─── Schema.org Structured Data ─────────────────────────────────

    public function schema_json_ld() {
        $schema = [
            '@context' => 'https://schema.org',
            '@type'    => 'RealEstateListing',
            'name'     => get_the_title( $this->post_id ),
            'url'      => get_permalink( $this->post_id ),
        ];

        if ( $this->rent() ) {
            $schema['offers'] = [
                '@type'         => 'Offer',
                'price'         => $this->rent(),
                'priceCurrency' => 'NZD',
            ];
        }

        if ( $this->full_address() ) {
            $schema['address'] = [
                '@type'           => 'PostalAddress',
                'streetAddress'   => trim( $this->address1() . ' ' . $this->address2() ),
                'addressLocality' => $this->address3(),
                'addressRegion'   => $this->region(),
                'postalCode'      => $this->postcode(),
            ];
        }

        if ( $this->has_map_coords() ) {
            $schema['geo'] = [
                '@type'     => 'GeoCoordinates',
                'latitude'  => $this->map_lat(),
                'longitude' => $this->map_lng(),
            ];
        }

        $img = $this->featured_image( 'full' );
        if ( $img ) {
            $schema['image'] = $img;
        }

        return '<script type="application/ld+json">' . wp_json_encode( $schema, JSON_UNESCAPED_SLASHES ) . '</script>';
    }
}
