<?php

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

function wnc_default_options() {
    return [
        'fallback_url' => 'https://wherenext.dev/getwherenext/',
        'button_label' => 'Send to Where Next',
        'button_icon' => 'journey',
        'button_bg_colour' => '#0f766e',
        'button_text_colour' => '#ffffff',
        'button_border_colour' => '#0f766e',
        'button_style' => 'filled',
        'button_size' => 'medium',
        'icon_size' => 'medium',

        'enabled_post_types'  => ['post', 'page'],
        'event_post_types'    => [],

        // Default field mappings
        'name_key' => 'post:title',
        'cover_image_key' => 'post:featured_image',

        // Custom field mappings
        'address_key' => '',
        'postcode_key' => '',
        'what3words_key' => '',
        'website_key' => '',
        'booking_url_key' => '',
        'parking_url_key' => '',
        'pricing_key' => '',
        'latitude_key' => '',
        'longitude_key' => '',
        'opening_times_key' => '',
        'parking_key' => '',
        'phone_key' => '',
        'category_key' => '',
        'membership_provider_key' => '',

        // Pricing
        'price_key' => '',
        'price_type_key' => '',
        'adult_price_key' => '',
        'child_price_key' => '',
        'family_price_key' => '',
        'carer_pricing_type_key' => '',
        'carer_price_key' => '',
        'parking_cost_key' => '',
        'price_notes_key' => '',
        'pricing_source_key' => '',
        'pricing_last_checked_key' => '',
        'pricing_confidence_key' => '',

        // Events / details
        'place_mode_key' => '',
        'event_start_date_key' => '',
        'event_end_date_key' => '',
        'indoor_outdoor_key' => '',
        'age_suitability_key' => '',
        'notes_key' => '',

        // Opening days
        'monday_key' => '',
        'tuesday_key' => '',
        'wednesday_key' => '',
        'thursday_key' => '',
        'friday_key' => '',
        'saturday_key' => '',
        'sunday_key' => '',

        // Badge
        'show_badge' => 0,
        'badge_variant' => 'colour',
        'badge_position' => 'manual',

        'archive_button_enabled' => 0,
        'archive_button_position' => 'below_excerpt',
        'archive_button_mode' => 'url',

        // Pro
        'pro_auto_place' => 0,
        'pro_auto_posts' => 0,
        'pro_auto_pages' => 0,
        'pro_auto_locations' => 1,
        'pro_auto_events' => 0,
        'pro_button_position' => 'inline',
        'pro_enable_visibility' => 0,
        'pro_enable_analytics' => 0,
        'pro_analytics_retention_days' => 365,
        'pro_mobile_only' => 0,
        'pro_desktop_only' => 0,
        'pro_show_desktop_qr' => 0,
    ];
}

function wnc_get_options() {
    $saved = get_option('wnc_options', []);
    return wp_parse_args(is_array($saved) ? $saved : [], wnc_default_options());
}

function wnc_is_mobile_device() {
    return function_exists('wp_is_mobile') && wp_is_mobile();
}

function wnc_get_available_meta_keys() {
    global $wpdb;

    $keys = $wpdb->get_col("
        SELECT DISTINCT meta_key
        FROM {$wpdb->postmeta}
        WHERE meta_key NOT LIKE '\_%'
        ORDER BY meta_key ASC
    ");

    return array_values(array_filter($keys));
}

function wnc_get_available_taxonomy_sources() {
    $taxonomies = get_taxonomies([
        'public' => true,
    ], 'objects');

    $sources = [];

    foreach ($taxonomies as $taxonomy => $object) {
        $sources[] = [
            'value' => 'tax:' . $taxonomy,
            'label' => $object->labels->singular_name ?: $object->label,
        ];
    }

    return $sources;
}

function wnc_get_field_map() {
    $options = wnc_get_options();

    return apply_filters('wnc_field_map', array_filter([
        // Core
        'name'                 => $options['name_key'],
        'address'              => $options['address_key'],
        'postcode'             => $options['postcode_key'],
        'category'             => $options['category_key'],
        'website'              => $options['website_key'],
        'coverImageUri'        => $options['cover_image_key'],

        // Location
        'bookingUrl'           => $options['booking_url_key'],
        'parkingUrl'           => $options['parking_url_key'],
        'what3words'           => $options['what3words_key'],
        'latitude'             => $options['latitude_key'],
        'longitude'            => $options['longitude_key'],
        'phone'                => $options['phone_key'],

        // Pricing
        'pricing'              => $options['pricing_key'],
        'priceType'            => $options['price_type_key'],
        'adultPrice'           => $options['adult_price_key'],
        'childPrice'           => $options['child_price_key'],
        'familyPrice'          => $options['family_price_key'],
        'carerPricingType'     => $options['carer_pricing_type_key'],
        'carerPrice'           => $options['carer_price_key'],
        'parkingCost'          => $options['parking_cost_key'],
        'priceNotes'           => $options['price_notes_key'],
        'pricingSource'        => $options['pricing_source_key'],
        'pricingLastChecked'   => $options['pricing_last_checked_key'],
        'pricingConfidence'    => $options['pricing_confidence_key'],

        // Membership
        'membershipProvider'   => $options['membership_provider_key'],

        // Events
        'placeMode'            => $options['place_mode_key'],
        'eventStartDate'       => $options['event_start_date_key'],
        'eventEndDate'         => $options['event_end_date_key'],

        // Details
        'openingTimes'         => $options['opening_times_key'],
        'indoorOutdoor'        => $options['indoor_outdoor_key'],
        'parking'              => $options['parking_key'],
        'ageSuitability'       => $options['age_suitability_key'],
        'notes'                => $options['notes_key'],

        // Opening days
        'monday'               => $options['monday_key'],
        'tuesday'              => $options['tuesday_key'],
        'wednesday'            => $options['wednesday_key'],
        'thursday'             => $options['thursday_key'],
        'friday'               => $options['friday_key'],
        'saturday'             => $options['saturday_key'],
        'sunday'               => $options['sunday_key'],
    ]));
}

function wnc_get_post_meta_value($post_id, $meta_key) {
    if (!$post_id || !$meta_key) {
        return '';
    }

    $value = get_post_meta($post_id, $meta_key, true);

    if (is_array($value)) {
        $value = implode(', ', array_filter($value));
    }

    return trim((string) $value);
}

function wnc_get_source_value($post_id, $source) {
    if (!$post_id || !$source) {
        return '';
    }

    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, 'large');
    }

    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) {
        return wnc_get_post_meta_value($post_id, substr($source, 5));
    }

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

    // Backwards compatibility for old saved mappings such as of5_address.
    return wnc_get_post_meta_value($post_id, $source);
}

function wnc_get_first_term_name($post_id, $taxonomy) {
    $terms = get_the_terms($post_id, $taxonomy);

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

    usort($terms, function ($a, $b) {
        return strcasecmp($a->name, $b->name);
    });

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

function wnc_price_to_number($value) {
    $value = html_entity_decode((string) $value);
    $value = preg_replace('/[^0-9.]/', '', $value);

    return $value !== '' ? $value : '';
}

function wnc_split_structured_rows($value) {
    $value = trim((string) $value);

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

    return preg_split('/\s*;\s*|\r\n|\r|\n/', $value);
}

function wnc_parse_pricing_table($pricing) {
    $out = [];

    if (!$pricing) {
        return $out;
    }

    $lines = wnc_split_structured_rows($pricing);

    foreach ($lines as $line) {
        $parts = array_map('trim', explode('|', $line));

        if (count($parts) < 2) {
            continue;
        }

        $ticket = strtolower($parts[0]);
        $price = wnc_price_to_number($parts[1]);

        if (!$price) {
            continue;
        }

        if (strpos($ticket, 'adult') !== false && empty($out['adultPrice'])) {
            $out['adultPrice'] = $price;
        }

        if (strpos($ticket, 'child') !== false && empty($out['childPrice'])) {
            $out['childPrice'] = $price;
        }

        if (strpos($ticket, 'family') !== false && empty($out['familyPrice'])) {
            $out['familyPrice'] = $price;
        }
    }

    if (!empty($out)) {
        $out['pricingSource'] = 'OF5';
        $out['pricingConfidence'] = 'high';
    }

    return $out;
}

function wnc_build_deep_link($post_id = 0) {
    $post_id = $post_id ?: get_the_ID();

    if (!$post_id) {
        return '';
    }

    $cover_image = get_the_post_thumbnail_url($post_id, 'large');

    $params = [
        'version' => '1.0',
        'name' => get_the_title($post_id),
        'source' => 'ourfamilyof5',
        'sourceUrl' => get_permalink($post_id),
        'placeMode' => 'place',
    ];

    if ($cover_image) {
        $params['coverImageUri'] = $cover_image;
    }

    $category = wnc_get_first_term_name($post_id, 'location_type');
    if ($category) {
        $params['category'] = $category;
    }

    $membership_provider = wnc_get_first_term_name($post_id, 'operator');
    if ($membership_provider) {
        $params['membershipProvider'] = $membership_provider;
    }

    foreach (wnc_get_field_map() as $app_field => $source) {
        $value = wnc_get_source_value($post_id, $source);

        if ($value !== '') {
            $params[$app_field] = $value;
        }
    }

    if (!empty($params['pricing'])) {
        $params = array_merge($params, wnc_parse_pricing_table($params['pricing']));
    }

    $params = array_filter($params, function ($value) {
        return $value !== '' && $value !== null;
    });

    return add_query_arg(
        $params,
        WNC_APP_SCHEME . '://' . WNC_APP_ROUTE
    );
}

function wnc_get_icon_url($icon) {
    if ($icon === 'family') {
        return WNC_URL . 'assets/family-pin.png';
    }

    if ($icon === 'journey') {
        return WNC_URL . 'assets/journey-pin.png';
    }

    return '';
}

function wnc_button_colour_values($colour, $style) {
    $colours = [
        'green' => ['bg' => '#0f766e', 'text' => '#ffffff', 'border' => '#0f766e', 'soft' => '#ccfbf1'],
        'blue' => ['bg' => '#2563eb', 'text' => '#ffffff', 'border' => '#2563eb', 'soft' => '#dbeafe'],
        'purple' => ['bg' => '#7c3aed', 'text' => '#ffffff', 'border' => '#7c3aed', 'soft' => '#ede9fe'],
        'dark' => ['bg' => '#111827', 'text' => '#ffffff', 'border' => '#111827', 'soft' => '#e5e7eb'],
        'white' => ['bg' => '#ffffff', 'text' => '#111827', 'border' => '#d1d5db', 'soft' => '#ffffff'],
    ];

    $c = $colours[$colour] ?? $colours['green'];

    if ($style === 'outline') {
        return [
            'background' => '#ffffff',
            'text' => $c['border'],
            'border' => $c['border'],
        ];
    }

    if ($style === 'soft') {
        return [
            'background' => $c['soft'],
            'text' => $c['border'],
            'border' => $c['soft'],
        ];
    }

    return [
        'background' => $c['bg'],
        'text' => $c['text'],
        'border' => $c['border'],
    ];
}
