<?php

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

class WNC_Connect_Metabox {

    public static function init() {
    add_action('add_meta_boxes', [__CLASS__, 'add_metabox']);
    add_action('save_post', [__CLASS__, 'save_metabox']);
    add_action('admin_enqueue_scripts', [__CLASS__, 'enqueue_admin_assets']);
    add_action('wp_ajax_wnc_refresh_preview', [__CLASS__, 'ajax_refresh_preview']);
}

public static function enqueue_admin_assets($hook) {
    if (!in_array($hook, ['post.php', 'post-new.php'], true)) {
        return;
    }

    wp_enqueue_media();

    wp_add_inline_script('jquery-core', "
        jQuery(function($) {
            $(document).on('click', '.wnc-select-image', function(e) {
                e.preventDefault();

                var wrapper = $(this).closest('.wnc-image-picker');
                var input = wrapper.find('.wnc-image-input');
                var preview = wrapper.find('.wnc-image-preview');

                var frame = wp.media({
                    title: 'Select cover image',
                    button: { text: 'Use this image' },
                    multiple: false,
                    library: { type: 'image' }
                });

                frame.on('select', function() {
                    var attachment = frame.state().get('selection').first().toJSON();
                    input.val(attachment.url);
                    preview.html('<img src=\"' + attachment.url + '\" style=\"max-width:320px;height:auto;border-radius:8px;border:1px solid #ccd0d4;display:block;margin-bottom:10px;\">');
                });

                frame.open();
            });

            $(document).on('click', '.wnc-remove-image', function(e) {
                e.preventDefault();

                var wrapper = $(this).closest('.wnc-image-picker');
                wrapper.find('.wnc-image-input').val('');
                wrapper.find('.wnc-image-preview').html('');
            });
        });
        
        $(document).on('click', '#wnc-refresh-preview', function(e) {
    e.preventDefault();

    var button = $(this);
    var postId = $('#post_ID').val();

    button.prop('disabled', true).text('Refreshing...');

    $.post(ajaxurl, {
        action: 'wnc_refresh_preview',
        post_id: postId
    }).done(function(response) {
        if (response.success && response.data.html) {
            $('#wnc-generated-preview-wrap').html(response.data.html);
        }
    }).always(function() {
        button.prop('disabled', false).text('Refresh Preview');
    });
});
    ");
}

   public static function field_groups() {
    return [
        'Core Information' => [
            'name' => 'Place Name',
            'address' => 'Address',
            'postcode' => 'Postcode',
            'website' => 'Website',
            'bookingUrl' => 'Booking URL',
            'parkingUrl' => 'Pre-book Parking URL',
            'category' => 'Category',
            'coverImageUri' => 'Cover Image',
        ],

        'Pricing' => [
            'pricing' => 'Pricing Table / Summary',
            'adultPrice' => 'Adult Price',
            'childPrice' => 'Child Price',
            'familyPrice' => 'Family Price',
            'carerPricingType' => 'Carer Pricing Type',
            'carerPrice' => 'Carer Price',
            'parkingCost' => 'Parking Cost',
        ],

        'Membership' => [
            'membershipProvider' => 'Membership Provider',
        ],

        'Event Details' => [
            'placeMode' => 'Place Mode',
            'eventStartDate' => 'Event Start Date',
            'eventEndDate' => 'Event End Date',
        ],

        'Opening Times' => [
            'openingTimes' => 'Opening Times',
            'monday' => 'Monday',
            'tuesday' => 'Tuesday',
            'wednesday' => 'Wednesday',
            'thursday' => 'Thursday',
            'friday' => 'Friday',
            'saturday' => 'Saturday',
            'sunday' => 'Sunday',
        ],

        'Place Details' => [
            'indoorOutdoor' => 'Indoor / Outdoor',
            'facilities' => 'Facilities',
            'parking' => 'Parking Information',
            'ageSuitability' => 'Age Suitability',
        ],

        'Location & Contact' => [
            'what3words' => 'what3words',
            'latitude' => 'Latitude',
            'longitude' => 'Longitude',
            'phone' => 'Phone',
        ],
    ];
}

    public static function fields() {
        $fields = [];

        foreach (self::field_groups() as $group_fields) {
            foreach ($group_fields as $key => $label) {
                $fields[$key] = $label;
            }
        }

        return $fields;
    }

    public static function textarea_fields() {

    return [

        'pricing',

        'openingTimes',

        'parking',

    ];

}

    public static function add_metabox() {

    $screens = function_exists('wnc_get_enabled_post_types')
        ? wnc_get_enabled_post_types()
        : ['post', 'page'];

    if (empty($screens)) {
        return;
    }

    add_meta_box(
        'wnc_connect_metabox',
        'Where Next Connect Overrides',
        [__CLASS__, 'render_metabox'],
        $screens,
        'normal',
        'high'
    );
}

    public static function render_metabox($post) {
        wp_nonce_field('wnc_connect_save', 'wnc_connect_nonce');

        echo '<p><strong>Leave fields blank to use the mapped/default value.</strong></p>';
        echo '<p>Only enter a value here if this page needs to override the default Where Next Connect data.</p>';

        foreach (self::field_groups() as $group_label => $fields) {
            echo '<h3 style="margin-top:24px;padding-top:14px;border-top:1px solid #ccd0d4;">' . esc_html($group_label) . '</h3>';
            echo '<table class="form-table">';

            foreach ($fields as $key => $label) {
                self::render_field_row($post, $key, $label);
            }

            echo '</table>';
        }
        echo '<div id="wnc_generated_preview_wrap">';
        self::render_generated_preview($post);
        echo '</div>';
    }

    private static function render_field_row($post, $key, $label) {
        $meta_key = '_wnc_' . $key;
        $value = get_post_meta($post->ID, $meta_key, true);
        $default_value = self::get_default_value($post->ID, $key);

        echo '<tr>';
        echo '<th><label for="' . esc_attr($meta_key) . '">' . esc_html($label) . '</label></th>';
        echo '<td>';
        
        if ($key === 'coverImageUri') {
    self::render_image_field($value, $default_value);
} elseif (in_array($key, self::textarea_fields(), true)) {
        
            echo '<textarea style="width:100%;min-height:90px;" id="' . esc_attr($meta_key) . '" name="' . esc_attr($meta_key) . '" placeholder="' . esc_attr($default_value) . '">' . esc_textarea($value) . '</textarea>';
        } else {
            echo '<input style="width:100%;" type="text" id="' . esc_attr($meta_key) . '" name="' . esc_attr($meta_key) . '" value="' . esc_attr($value) . '" placeholder="' . esc_attr($default_value) . '">';
        }

        if ($key !== 'coverImageUri') {
    if (trim((string) $default_value) !== '') {
        echo '<p class="description"><strong>Default:</strong> ' . esc_html($default_value) . '</p>';
    } else {
        echo '<p class="description">No default value currently found.</p>';
    }
}
        echo '</td>';
        echo '</tr>';
    }

 private static function render_image_field($value, $default_value) {
    $preview = $value ?: $default_value;

    echo '<div class="wnc-image-picker">';

    echo '<div class="wnc-image-preview">';
    if ($preview) {
        echo '<img src="' . esc_url($preview) . '" style="max-width:320px;height:auto;border-radius:8px;border:1px solid #ccd0d4;display:block;margin-bottom:10px;">';
    }
    echo '</div>';

    echo '<input type="hidden"
        class="wnc-image-input"
        id="_wnc_coverImageUri"
        name="_wnc_coverImageUri"
        value="' . esc_attr($value) . '">';

    echo '<p>';
    echo '<button type="button" class="button wnc-select-image">'
        . esc_html($value ? 'Change Image' : 'Select Image') .
        '</button> ';
    echo '<button type="button" class="button wnc-remove-image">Remove Image</button>';
    echo '</p>';

    if ($value) {
        echo '<p class="description"><strong>Using override image.</strong></p>';
    } elseif ($default_value) {
        echo '<p class="description"><strong>Using default image.</strong></p>';
    } else {
        echo '<p class="description">No default image currently found.</p>';
    }

    echo '</div>';
}

    private static function get_default_value($post_id, $key) {
        $saved_override = get_post_meta($post_id, '_wnc_' . $key, true);

        if (class_exists('WNC_Connect_Tags')) {
            $data = WNC_Connect_Tags::get_data($post_id);
            $resolved_value = $data[$key] ?? '';

            if (
                trim((string) $saved_override) !== '' &&
                trim((string) $resolved_value) === trim((string) $saved_override)
            ) {
                return '';
            }

            return $resolved_value;
        }

        return '';
    }

private static function render_generated_preview($post) {
    if (!class_exists('WNC_Connect_Tags')) {
        return;
    }

    $data = WNC_Connect_Tags::get_data($post->ID);

    echo '<h3 style="margin-top:24px;padding-top:14px;border-top:1px solid #ccd0d4;">Generated Where Next Data</h3>';
    echo '<p><button type="button" class="button" id="wnc-refresh-preview">Refresh Preview</button></p>';
    echo '<p class="description">Save or update the post to refresh this preview.</p>';

    echo '<table class="widefat striped" style="margin-top:12px;">';
    echo '<thead><tr><th style="width:220px;">Tag</th><th>Value</th><th style="width:130px;">Status</th></tr></thead>';
    echo '<tbody>';

    foreach ($data as $key => $value) {
        $value = trim((string) $value);

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

        $override = get_post_meta($post->ID, '_wnc_' . $key, true);
        $status = trim((string) $override) !== '' ? 'Override' : 'Mapped';

        echo '<tr>';
        echo '<td><strong>' . esc_html($key) . '</strong><br><code>wherenext:' . esc_html($key) . '</code></td>';
        echo '<td>' . esc_html($value) . '</td>';
        echo '<td>' . esc_html($status) . '</td>';
        echo '</tr>';
    }

    echo '</tbody>';
    echo '</table>';

    echo '<h3 style="margin-top:24px;">Generated HTML</h3>';
    echo '<details>';
    echo '<summary style="cursor:pointer;font-weight:700;">Show generated meta tags</summary>';
    echo '<pre style="background:#111827;color:#f9fafb;padding:14px;border-radius:8px;white-space:pre-wrap;overflow:auto;margin-top:12px;">';

    foreach ($data as $key => $value) {
        $value = trim((string) $value);

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

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

    echo '</pre>';
    echo '</details>';
}
    public static function ajax_refresh_preview() {
    $post_id = isset($_POST['post_id']) ? absint($_POST['post_id']) : 0;

    if (!$post_id || !current_user_can('edit_post', $post_id)) {
        wp_send_json_error('Permission denied');
    }

    ob_start();
    self::render_generated_preview(get_post($post_id));
    $html = ob_get_clean();

    wp_send_json_success([
        'html' => $html,
    ]);
}
    public static function save_metabox($post_id) {
        if (!isset($_POST['wnc_connect_nonce']) || !wp_verify_nonce($_POST['wnc_connect_nonce'], 'wnc_connect_save')) {
            return;
        }

        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
            return;
        }

        if (!current_user_can('edit_post', $post_id)) {
            return;
        }

        foreach (self::fields() as $key => $label) {
            $meta_key = '_wnc_' . $key;

            if (!isset($_POST[$meta_key])) {
                continue;
            }

            if (in_array($key, self::textarea_fields(), true)) {
                $value = sanitize_textarea_field(wp_unslash($_POST[$meta_key]));
            } else {
                $value = sanitize_text_field(wp_unslash($_POST[$meta_key]));
            }

            if ($value === '') {
                delete_post_meta($post_id, $meta_key);
            } else {
                update_post_meta($post_id, $meta_key, $value);
            }
        }
    }
}
