<?php

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

class WNC_Connect_Tags {

    public static function init() {
        add_action('wp_head', [__CLASS__, 'output_tags'], 5);
    }

    public static function output_tags() {
        if (!is_singular()) {
            return;
        }

        global $post;

        if (!$post) {
            return;
        }

        if (function_exists('wnc_is_enabled_post_type') && !wnc_is_enabled_post_type($post->post_type)) {
            return;
        }

        $tags = self::get_data($post->ID);

        echo "\n<!-- Where Next Connect v1.0 -->\n";

        foreach ($tags as $key => $value) {
            self::meta($key, $value);
        }

        echo "<!-- /Where Next Connect -->\n";
    }

    public static function get_data($post_id) {
        return [
            'version' => '1.0',

            // Import/source
            'source' => 'ourfamilyof5',
            'sourceUrl' => get_permalink($post_id),

            // Core
            'name' => self::value($post_id, 'name', get_the_title($post_id)),
            'address' => self::value($post_id, 'address'),
            'postcode' => self::value($post_id, 'postcode'),
            'category' => self::value($post_id, 'category', self::get_category_name($post_id)),
            'website' => self::value($post_id, 'website'),
            'coverImageUri' => self::value(
                $post_id,
                'coverImageUri',
                get_the_post_thumbnail_url($post_id, 'full')
            ),

            // Location / links
            'bookingUrl' => self::value($post_id, 'bookingUrl'),
            'parkingUrl' => self::value($post_id, 'parkingUrl'),
            'what3words' => self::value($post_id, 'what3words'),
            'latitude' => self::value($post_id, 'latitude'),
            'longitude' => self::value($post_id, 'longitude'),
            'phone' => self::value($post_id, 'phone'),

            // Pricing
            'pricing' => self::value($post_id, 'pricing'),
            'priceType' => self::value($post_id, 'priceType'),
            'adultPrice' => self::value($post_id, 'adultPrice'),
            'childPrice' => self::value($post_id, 'childPrice'),
            'familyPrice' => self::value($post_id, 'familyPrice'),
            'carerPricingType' => self::value($post_id, 'carerPricingType'),
            'carerPrice' => self::value($post_id, 'carerPrice'),
            'parkingCost' => self::value($post_id, 'parkingCost'),
            'priceNotes' => self::value($post_id, 'priceNotes'),
            'pricingSource' => self::value($post_id, 'pricingSource'),
            'pricingLastChecked' => self::value($post_id, 'pricingLastChecked'),
            'pricingConfidence' => self::value($post_id, 'pricingConfidence'),

            // Memberships
            'membershipProvider' => self::value(
                $post_id,
                'membershipProvider',
                self::get_first_term_name($post_id, 'operator')
            ),

            // Events
            'placeMode' => self::value(
                $post_id,
                'placeMode',
                function_exists('wnc_is_event_post_type') && wnc_is_event_post_type(get_post_type($post_id)) ? 'event' : 'place'
            ),
            'eventStartDate' => self::value($post_id, 'eventStartDate'),
            'eventEndDate' => self::value($post_id, 'eventEndDate'),

            // Opening hours
            'openingTimes' => self::value($post_id, 'openingTimes'),
            'monday' => self::value($post_id, 'monday'),
            'tuesday' => self::value($post_id, 'tuesday'),
            'wednesday' => self::value($post_id, 'wednesday'),
            'thursday' => self::value($post_id, 'thursday'),
            'friday' => self::value($post_id, 'friday'),
            'saturday' => self::value($post_id, 'saturday'),
            'sunday' => self::value($post_id, 'sunday'),

            // Details
'indoorOutdoor' => self::value($post_id, 'indoorOutdoor'),
'facilities' => self::value(
    $post_id,
    'facilities',
    self::get_term_slugs($post_id, 'facility')
),
'parking' => self::value($post_id, 'parking'),
'ageSuitability' => self::value($post_id, 'ageSuitability'),
'notes' => self::value($post_id, 'notes'),
        ];
    }

    private static function value($post_id, $key, $fallback = '') {
        $manual = get_post_meta($post_id, '_wnc_' . $key, true);
        $manual = self::normalise_value($manual);

        if ($manual !== '') {
            return $manual;
        }

        $mapped = self::normalise_value(self::mapped_value($post_id, $key));

        if ($mapped !== '') {
            return $mapped;
        }

        return self::normalise_value($fallback);
    }

    private static function mapped_value($post_id, $key) {
        if (!class_exists('WNC_Connect_Settings')) {
            return '';
        }

        $mapping = WNC_Connect_Settings::get_mapping();

        if (empty($mapping[$key])) {
            return '';
        }

        $source = $mapping[$key];

        if ($source === 'post:title') {
            return get_the_title($post_id);
        }

        if ($source === 'post:permalink') {
            return get_permalink($post_id);
        }

        if ($source === 'post:featured_image') {
            return get_the_post_thumbnail_url($post_id, 'full');
        }

        if ($source === 'post:excerpt') {
            return get_the_excerpt($post_id);
        }

        if ($source === 'post:content') {
            return wp_strip_all_tags(get_post_field('post_content', $post_id));
        }

        if (strpos($source, 'meta:') === 0) {
            $meta_key = substr($source, 5);
            return get_post_meta($post_id, $meta_key, true);
        }

        if (strpos($source, 'tax:') === 0) {
            $taxonomy = substr($source, 4);
            return self::get_first_term_name($post_id, $taxonomy);
        }

        return '';
    }

    private static function normalise_value($value) {
        if (is_array($value)) {
            $value = implode(', ', array_filter(array_map('trim', $value)));
        }

        return trim((string) $value);
    }

    private static function meta($key, $value) {
        $value = self::normalise_value($value);

        if ($value === '') {
            return;
        }

        if (in_array(strtolower($value), ['0', 'none', 'null'], true)) {
            return;
        }

        if (in_array($key, ['openingTimes', 'pricing', 'priceNotes', 'parking'], true)) {
            $value = str_replace(["\r\n", "\r", "\n"], ';', $value);
            $value = preg_replace('/\s*\|\s*/', '|', $value);
            $value = preg_replace('/;{2,}/', ';', $value);
            $value = trim($value, '; ');
        }

        printf(
            '<meta name="wherenext:%s" content="%s">' . "\n",
            esc_attr($key),
            esc_attr($value)
        );
    }

    private static function get_category_name($post_id) {
        $location_type = self::get_first_term_name($post_id, 'location_type');

        if ($location_type) {
            return $location_type;
        }

        return self::get_first_term_name($post_id, 'category');
    }
    
    private static function get_term_slugs($post_id, $taxonomy) {
    $terms = get_the_terms($post_id, $taxonomy);

    if (empty($terms) || is_wp_error($terms)) {
        return '';
    }

    $slugs = [];

    foreach ($terms as $term) {
        if (!empty($term->slug)) {
            $slugs[] = $term->slug;
        }
    }

    sort($slugs);

    return implode('|', $slugs);
}

    private static function get_first_term_name($post_id, $taxonomy) {
        $terms = get_the_terms($post_id, $taxonomy);

        if (!empty($terms) && !is_wp_error($terms)) {
            usort($terms, function ($a, $b) {
                return strcasecmp($a->name, $b->name);
            });

            return $terms[0]->name ?? '';
        }

        return '';
    }
}
