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

    public static function init() {
        self::register_settings();
        add_action('update_option_integrate_palace_properties_username', [__CLASS__, 'settings_updated'], 10, 3);
        add_action('update_option_integrate_palace_properties_password', [__CLASS__, 'settings_updated'], 10, 3);
        add_action('update_option_integrate_palace_properties_subscription_key', [__CLASS__, 'settings_updated'], 10, 3);
        add_action('update_option_integrate_palace_properties_slug', [__CLASS__, 'settings_updated'], 10, 3);
    }

    public static function register_settings() {
        register_setting('integrate_palace_properties_configs', 'integrate_palace_properties_username', ['sanitize_callback' => 'sanitize_text_field']);
        register_setting('integrate_palace_properties_configs', 'integrate_palace_properties_password', ['sanitize_callback' => 'sanitize_text_field']);
        register_setting('integrate_palace_properties_configs', 'integrate_palace_properties_subscription_key', ['sanitize_callback' => 'sanitize_text_field']);
        register_setting('integrate_palace_properties_configs', 'integrate_palace_properties_slug', ['sanitize_callback' => 'sanitize_text_field']);

        add_settings_section(
            'integrate_palace_properties_settings_section',
            __('WP Palace Properties Settings', 'integrate-palace-properties'),
            null,
            'integrate_palace_properties_configs'
        );

        add_settings_field(
            'integrate_palace_properties_username',
            __('Palace API Username', 'integrate-palace-properties'),
            [__CLASS__, 'render_username_field'],
            'integrate_palace_properties_configs',
            'integrate_palace_properties_settings_section'
        );

        add_settings_field(
            'integrate_palace_properties_password',
            __('Palace API Password', 'integrate-palace-properties'),
            [__CLASS__, 'render_password_field'],
            'integrate_palace_properties_configs',
            'integrate_palace_properties_settings_section'
        );

        add_settings_field(
            'integrate_palace_properties_subscription_key',
            __('Subscription Key', 'integrate-palace-properties'),
            [__CLASS__, 'render_subscription_key_field'],
            'integrate_palace_properties_configs',
            'integrate_palace_properties_settings_section'
        );

        add_settings_field(
            'integrate_palace_properties_slug',
            __('Property Slug', 'integrate-palace-properties'),
            [__CLASS__, 'render_palace_property_slug'],
            'integrate_palace_properties_configs',
            'integrate_palace_properties_settings_section'
        );

        add_settings_field(
            'integrate_palace_properties_webhook_status',
            __('STATUS', 'integrate-palace-properties'),
            [__CLASS__, 'render_webhook_status_field'],
            'integrate_palace_properties_configs',
            'integrate_palace_properties_settings_section'
        );

        // ─── Advanced Section ────────────────────────────────────────────
        register_setting('integrate_palace_properties_configs', 'ipp_remove_data_on_uninstall', [
            'type'              => 'string',
            'sanitize_callback' => 'sanitize_text_field',
            'default'           => 'no',
        ]);

        add_settings_section(
            'ipp_advanced_section',
            __('Advanced', 'integrate-palace-properties'),
            null,
            'integrate_palace_properties_configs'
        );

        add_settings_field(
            'ipp_test_connection',
            __('Test Connection', 'integrate-palace-properties'),
            [__CLASS__, 'render_test_connection_field'],
            'integrate_palace_properties_configs',
            'ipp_advanced_section'
        );

        add_settings_field(
            'ipp_remove_data_on_uninstall',
            __('Remove Data on Uninstall', 'integrate-palace-properties'),
            [__CLASS__, 'render_remove_data_field'],
            'integrate_palace_properties_configs',
            'ipp_advanced_section'
        );

        // ─── Display Configuration Section ─────────────────────────────
        register_setting('integrate_palace_properties_configs', 'ipp_display_fields', [
            'type'              => 'array',
            'sanitize_callback' => [__CLASS__, 'sanitize_display_fields'],
            'default'           => self::get_default_display_fields(),
        ]);
        register_setting('integrate_palace_properties_configs', 'ipp_sync_archived', [
            'type'              => 'string',
            'sanitize_callback' => 'sanitize_text_field',
            'default'           => 'no',
        ]);
        register_setting('integrate_palace_properties_configs', 'ipp_sync_statuses', [
            'type'              => 'array',
            'sanitize_callback' => [__CLASS__, 'sanitize_sync_statuses'],
            'default'           => ['Active'],
        ]);

        add_settings_section(
            'ipp_display_config_section',
            __('Display Configuration', 'integrate-palace-properties'),
            [__CLASS__, 'render_display_section_description'],
            'integrate_palace_properties_configs'
        );

        add_settings_field(
            'ipp_display_fields',
            __('Property Details to Display', 'integrate-palace-properties'),
            [__CLASS__, 'render_display_fields'],
            'integrate_palace_properties_configs',
            'ipp_display_config_section'
        );

        add_settings_field(
            'ipp_sync_archived',
            __('Include Archived Properties', 'integrate-palace-properties'),
            [__CLASS__, 'render_sync_archived_field'],
            'integrate_palace_properties_configs',
            'ipp_display_config_section'
        );

        add_settings_field(
            'ipp_sync_statuses',
            __('Property Statuses to Sync', 'integrate-palace-properties'),
            [__CLASS__, 'render_sync_statuses_field'],
            'integrate_palace_properties_configs',
            'ipp_display_config_section'
        );
    }

    /**
     * All configurable display fields grouped by category.
     */
    public static function get_all_display_field_options() {
        return array(
            __('Basic Info', 'integrate-palace-properties') => array(
                'rent'            => __('Rent Amount', 'integrate-palace-properties'),
                'rental_period'   => __('Rental Period', 'integrate-palace-properties'),
                'date_available'  => __('Date Available', 'integrate-palace-properties'),
                'address'         => __('Address', 'integrate-palace-properties'),
                'suburb'          => __('Suburb', 'integrate-palace-properties'),
                'region'          => __('Region', 'integrate-palace-properties'),
                'postcode'        => __('Postcode', 'integrate-palace-properties'),
                'status'          => __('Property Status', 'integrate-palace-properties'),
            ),
            __('Accommodation', 'integrate-palace-properties') => array(
                'bedrooms'        => __('Bedrooms', 'integrate-palace-properties'),
                'bathrooms'       => __('Bathrooms', 'integrate-palace-properties'),
                'ensuites'        => __('Ensuites', 'integrate-palace-properties'),
                'cars'            => __('Car Spaces', 'integrate-palace-properties'),
                'parking'         => __('Parking Type', 'integrate-palace-properties'),
            ),
            __('Features', 'integrate-palace-properties') => array(
                'property_class'  => __('Property Class', 'integrate-palace-properties'),
                'year_built'      => __('Year Built', 'integrate-palace-properties'),
                'stories'         => __('Stories', 'integrate-palace-properties'),
                'floor_area'      => __('Floor Area', 'integrate-palace-properties'),
                'land_area'       => __('Land Area (sqm)', 'integrate-palace-properties'),
                'furnishings'     => __('Furnishings', 'integrate-palace-properties'),
                'new_construction' => __('New Construction', 'integrate-palace-properties'),
                'amenities'       => __('Amenities', 'integrate-palace-properties'),
            ),
            __('Rules & Policies', 'integrate-palace-properties') => array(
                'pets_allowed'    => __('Pets Allowed', 'integrate-palace-properties'),
                'smokers_allowed' => __('Smokers Allowed', 'integrate-palace-properties'),
            ),
            __('Links & Media', 'integrate-palace-properties') => array(
                'virtual_tour'    => __('Virtual Tour', 'integrate-palace-properties'),
                'web_link'        => __('Web Link', 'integrate-palace-properties'),
                'gallery'         => __('Photo Gallery', 'integrate-palace-properties'),
                'geographic_location' => __('Map / Location', 'integrate-palace-properties'),
            ),
            __('Agent Info', 'integrate-palace-properties') => array(
                'agent_name'      => __('Agent Name', 'integrate-palace-properties'),
                'agent_email'     => __('Agent Email', 'integrate-palace-properties'),
                'agent_phone'     => __('Agent Phone', 'integrate-palace-properties'),
            ),
            __('Advanced', 'integrate-palace-properties') => array(
                'management_type' => __('Management Type', 'integrate-palace-properties'),
                'market_value'    => __('Market Value', 'integrate-palace-properties'),
                'notes'           => __('Property Notes', 'integrate-palace-properties'),
                'custom_fields'   => __('Custom Fields', 'integrate-palace-properties'),
                'feature_details' => __('Feature Details', 'integrate-palace-properties'),
            ),
        );
    }

    public static function get_default_display_fields() {
        return array(
            'rent', 'rental_period', 'date_available', 'address', 'suburb', 'region',
            'bedrooms', 'bathrooms', 'cars', 'parking',
            'property_class', 'year_built', 'floor_area',
            'pets_allowed', 'smokers_allowed',
            'virtual_tour', 'gallery', 'geographic_location',
            'agent_name', 'agent_email', 'agent_phone',
        );
    }

    public static function sanitize_display_fields( $input ) {
        if ( ! is_array( $input ) ) return self::get_default_display_fields();
        return array_map( 'sanitize_key', $input );
    }

    public static function sanitize_sync_statuses( $input ) {
        if ( ! is_array( $input ) ) return array( 'Active' );
        return array_map( 'sanitize_text_field', $input );
    }

    public static function render_display_section_description() {
        echo '<p>' . esc_html__( 'Control which property details are displayed on your website and how properties are synced from Palace.', 'integrate-palace-properties' ) . '</p>';
    }

    public static function render_display_fields() {
        $saved = get_option( 'ipp_display_fields', self::get_default_display_fields() );
        $all_fields = self::get_all_display_field_options();

        echo '<div class="ipp-display-fields-grid" style="display:grid; grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); gap: 20px;">';
        foreach ( $all_fields as $group_label => $fields ) {
            echo '<fieldset style="border:1px solid #ccd0d4; padding:12px; border-radius:4px;">';
            echo '<legend style="font-weight:600; padding:0 6px;">' . esc_html( $group_label ) . '</legend>';
            foreach ( $fields as $key => $label ) {
                $checked = in_array( $key, $saved, true ) ? 'checked' : '';
                echo '<label style="display:block; margin-bottom:6px; cursor:pointer;">';
                echo '<input type="checkbox" name="ipp_display_fields[]" value="' . esc_attr( $key ) . '" ' . $checked . ' /> ';
                echo esc_html( $label );
                echo '</label>';
            }
            echo '</fieldset>';
        }
        echo '</div>';
        echo '<p class="description">' . esc_html__( 'Unchecked fields will be hidden from the frontend property pages.', 'integrate-palace-properties' ) . '</p>';
    }

    public static function render_sync_archived_field() {
        $value = get_option( 'ipp_sync_archived', 'no' );
        echo '<label>';
        echo '<input type="checkbox" name="ipp_sync_archived" value="yes" ' . checked( $value, 'yes', false ) . ' /> ';
        echo esc_html__( 'Also sync archived/inactive properties from Palace', 'integrate-palace-properties' );
        echo '</label>';
        echo '<p class="description">' . esc_html__( 'When enabled, both current and archived properties will be imported. Archived properties will be marked with the "Inactive" status taxonomy.', 'integrate-palace-properties' ) . '</p>';
    }

    public static function render_sync_statuses_field() {
        $saved = get_option( 'ipp_sync_statuses', array( 'Active' ) );
        $statuses = array( 'Active', 'Inactive' );
        foreach ( $statuses as $status ) {
            $checked = in_array( $status, $saved, true ) ? 'checked' : '';
            echo '<label style="display:inline-block; margin-right:16px;">';
            echo '<input type="checkbox" name="ipp_sync_statuses[]" value="' . esc_attr( $status ) . '" ' . $checked . ' /> ';
            echo esc_html( $status );
            echo '</label>';
        }
        echo '<p class="description">' . esc_html__( 'Choose which property statuses to sync from Palace API.', 'integrate-palace-properties' ) . '</p>';
    }

    public static function render_username_field() {
        $value = get_option('integrate_palace_properties_username', '');
        echo '<input type="text" name="integrate_palace_properties_username" value="' . esc_attr($value) . '" class="ipp-full-width" />';
    }

    public static function render_password_field() {
        $value = get_option('integrate_palace_properties_password', '');
        echo '<input type="password" name="integrate_palace_properties_password" value="' . esc_attr($value) . '" class="ipp-full-width" />';
    }

    public static function render_subscription_key_field() {
        $value = get_option('integrate_palace_properties_subscription_key', '');
        echo '<input type="password" name="integrate_palace_properties_subscription_key" value="' . esc_attr($value) . '" class="ipp-full-width" />';
    }

    public static function render_palace_property_slug() {
        $value = get_option('integrate_palace_properties_slug', '');
        echo '<input type="text" name="integrate_palace_properties_slug" value="' . esc_attr($value) . '" class="ipp-full-width" />';
    }

    public static function render_webhook_status_field() {
        $value = get_option('integrate_palace_properties_webhook_status', '');
        echo '<label>' . wp_kses_post($value) . '</label>';
    }

    public static function render_test_connection_field() {
        echo '<button type="button" id="ipp-test-connection" class="button">';
        echo '<span class="dashicons dashicons-admin-plugins" style="margin-top:3px;margin-right:4px;"></span>';
        echo esc_html__( 'Test Palace API Connection', 'integrate-palace-properties' );
        echo '</button>';
        echo ' <span id="ipp-test-result" style="margin-left:10px;"></span>';
        echo '<script>
        jQuery("#ipp-test-connection").on("click", function() {
            var $btn = jQuery(this), $result = jQuery("#ipp-test-result");
            $btn.prop("disabled", true);
            $result.text("Testing...").css("color", "#646970");
            jQuery.post(ajaxurl, {
                action: "ipp_test_connection",
                nonce: "' . esc_js( wp_create_nonce( 'ipp_admin_nonce' ) ) . '"
            }, function(response) {
                $btn.prop("disabled", false);
                if (response.success) {
                    var msg = response.data.message;
                    if (response.data.company) msg += " (" + response.data.company + ")";
                    $result.text(msg).css("color", "#155724");
                } else {
                    $result.text(response.data || "Connection failed").css("color", "#721c24");
                }
            }).fail(function() {
                $btn.prop("disabled", false);
                $result.text("Request failed").css("color", "#721c24");
            });
        });
        </script>';
    }

    public static function render_remove_data_field() {
        $value = get_option( 'ipp_remove_data_on_uninstall', 'no' );
        echo '<label>';
        echo '<input type="checkbox" name="ipp_remove_data_on_uninstall" value="yes" ' . checked( $value, 'yes', false ) . ' /> ';
        echo '<strong style="color:#dc3545;">' . esc_html__( 'Delete all property data when plugin is uninstalled', 'integrate-palace-properties' ) . '</strong>';
        echo '</label>';
        echo '<p class="description">' . esc_html__( 'When checked, all properties, images, taxonomies, and settings will be permanently deleted if you uninstall the plugin. Leave unchecked to preserve data.', 'integrate-palace-properties' ) . '</p>';
    }

    public static function settings_updated($old_value, $value, $option) {
        self::update_subscription();
        if ($option === 'integrate_palace_properties_slug') {
            unregister_post_type('palace-properties');
            $palace_properties = new IntegratePalace_Properties_Register_Properties();
            $palace_properties->register_palace_properties();
            flush_rewrite_rules();

        }
    }

    private static function update_subscription() {
        $username = get_option('integrate_palace_properties_username', '');
        $password = get_option('integrate_palace_properties_password', '');
        $subscription_key = get_option('integrate_palace_properties_subscription_key', '');
        $webhook_url = esc_url(rest_url('integrate-palace-properties/v1/webhook'));

        $api_base = defined( 'IPP_API_URL' ) ? IPP_API_URL : 'https://wp-palace.kiwibrain.co.nz';
        $response = wp_remote_post( $api_base . '/api/update-user', [
            'method'    => 'POST',
            'body'      => wp_json_encode([
                'palace_api_key'    => base64_encode(sanitize_text_field($username) . ":" . sanitize_text_field($password)),
                'wp_palace_blog_id' => get_option("integrate_palace-palace-unique-id"),
                'webhook_url'       => $webhook_url,
                'subscription_key'  => sanitize_text_field($subscription_key)
            ]),
            'headers'   => [
                'Content-Type' => 'application/json',
            ],
        ]);

        if (is_wp_error($response)) {
            error_log("Failed to call API: " . $response->get_error_message());
        } else {
            $body = wp_remote_retrieve_body($response);
            $data = json_decode($body, true);

            if (isset($data['subscription']['webhook_url'])) {
                $subscription_name = sanitize_text_field($data['subscription']['name'] ?? '');
                $properties_allowed = isset($data['subscription']['properties_allowed']) ? sanitize_text_field($data['subscription']['properties_allowed']) : '';
                $properties_allowed = ($properties_allowed == '-1') ? "unlimited" : $properties_allowed;

                update_option('integrate_palace_properties_webhook_url', esc_url_raw($data['subscription']['webhook_url']));
                update_option('integrate_palace_properties_webhook_status', "<span class='wh_connected'><i>Connected ($subscription_name) Max Properties: " . esc_html($properties_allowed) . "</i><span>");
                error_log("API call successful and webhook URL updated");
            } else {
                update_option('integrate_palace_properties_webhook_status', "<span class='wh_error'><i>Invalid Subscription Key</i><span>");
                error_log("API call successful but webhook URL not found in response");
            }
        }
    }
}
?>
