<?php
defined('ABSPATH') || exit;

class Willro_Reviews_Admin_Menu {

    const OPTION_KEY = 'willro_reviews_api_key';
    const OPTION_SHOW_ATTRIBUTION = 'willro_reviews_show_attribution';

    private $menu_hook = '';

    public function __construct() {
        add_action( 'admin_menu', [ $this, 'add_menu' ] );
        add_action( 'admin_init', [ $this, 'register_settings' ] );
        add_action( 'admin_enqueue_scripts', [ $this, 'enqueue_admin_assets' ] );
        add_action( 'wp_ajax_willro_test_api', [ $this, 'test_api_connection' ] );
    }

    public function add_menu() {
        $this->menu_hook = add_menu_page(
            __( 'Willro Reviews', 'willro-reviews' ),
            __( 'Willro Reviews', 'willro-reviews' ),
            'manage_options',
            'willro-reviews',
            [ $this, 'settings_page' ],
            'dashicons-star-filled',
            56
        );
    }

    public function register_settings() {
        register_setting(
            'willro_reviews_settings',
            self::OPTION_KEY,
            [
                'sanitize_callback' => 'sanitize_text_field',
            ]
        );

        register_setting(
            'willro_reviews_settings',
            self::OPTION_SHOW_ATTRIBUTION,
            [
                'sanitize_callback' => 'absint',
                'default'           => 0,
            ]
        );

    }


    public function enqueue_admin_assets( $hook_suffix ) {
        if ( empty( $this->menu_hook ) || $hook_suffix !== $this->menu_hook ) {
            return;
        }

        wp_enqueue_script(
            'willro-reviews-admin',
            WILLRO_REVIEWS_URL . 'assets/js/admin.js',
            [ 'jquery' ],
            WILLRO_REVIEWS_VERSION,
            true
        );

        wp_localize_script( 'willro-reviews-admin', 'WillroReviewsAdmin', [
            'ajaxUrl'        => admin_url( 'admin-ajax.php' ),
            'nonce'          => wp_create_nonce( 'willro_test_api_nonce' ),
            'testingText'    => __( 'Testing connection…', 'willro-reviews' ),
            'ajaxFailedText' => __( 'AJAX request failed.', 'willro-reviews' ),
        ] );
    }

    public function settings_page() {
        ?>
        <div class="wrap">
            <h1><?php echo esc_html__( 'Willro Reviews Settings', 'willro-reviews' ); ?></h1>

            <form method="post" action="options.php">
                <?php
                settings_fields('willro_reviews_settings');
                do_settings_sections('willro_reviews_settings');
                ?>

                <table class="form-table">
                    <tr>
                        <th scope="row"><?php echo esc_html__( 'API Key', 'willro-reviews' ); ?></th>
                        <td>
                            <input
                                type="text"
                                name="<?php echo esc_attr( self::OPTION_KEY ); ?>"
                                value="<?php echo esc_attr( get_option( self::OPTION_KEY ) ); ?>"
                                class="regular-text"
                                autocomplete="off"
                            />
                        </td>
                    </tr>

                    <tr>
                        <th scope="row"><?php echo esc_html__( 'Show attribution', 'willro-reviews' ); ?></th>
                        <td>
                            <label>
                                <input
                                    type="hidden"
                                    name="<?php echo esc_attr( self::OPTION_SHOW_ATTRIBUTION ); ?>"
                                    value="0"
                                />
                                <input
                                    type="checkbox"
                                    name="<?php echo esc_attr( self::OPTION_SHOW_ATTRIBUTION ); ?>"
                                    value="1"
                                    <?php checked( (int) get_option( self::OPTION_SHOW_ATTRIBUTION, 0 ), 1 ); ?>
                                />
                                <?php echo esc_html__( 'Display the Willro attribution/logo block in the front-end templates.', 'willro-reviews' ); ?>
                            </label>
                        </td>
                    </tr>
                </table>

                <?php submit_button( __( 'Save API Key', 'willro-reviews' ) ); ?>
            </form>

            <hr>

            <h2><?php echo esc_html__( 'Test API Connection', 'willro-reviews' ); ?></h2>

            <button class="button button-secondary" id="willro-test-api">
                <?php echo esc_html__( 'Test Connection', 'willro-reviews' ); ?>
            </button>

            <p id="willro-api-result" style="margin-top:10px;"></p>
        </div>
        <?php
    }

    public function test_api_connection() {

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error(
                [ 'message' => __( 'Unauthorized.', 'willro-reviews' ) ],
                403
            );
        }

        $nonce = '';
        if ( isset( $_POST['nonce'] ) ) {
            $nonce = sanitize_text_field( wp_unslash( $_POST['nonce'] ) );
        }

       

        $api_key = get_option(self::OPTION_KEY);

        if ( empty($api_key) ) {
            wp_send_json_error([
                'message' => __( 'API key not set.', 'willro-reviews' )
            ]);
        }

        $url = WILLRO_REVIEWS_API_URL . '/info';
        $timeout = (int) apply_filters( 'willro_reviews_http_timeout', 30 );
        if ( $timeout < 5 ) {
            $timeout = 5;
        }
        
        $response = wp_remote_get( $url, [
            'headers' => [
                'x-api-key' => $api_key,
            ],
            'timeout' => $timeout,
            'redirection' => 5,
        ] );

        if ( is_wp_error($response) ) {
            wp_send_json_error([
                'message' => sprintf(
                    /* translators: %s: error message. */
                    __( 'Connection failed: %s', 'willro-reviews' ),
                    $response->get_error_message()
                )
            ]);
        }

        $code = wp_remote_retrieve_response_code($response);
        $body = wp_remote_retrieve_body( $response );
        $json = json_decode( $body, true );

        if ( $code === 200 && is_array( $json ) ) {
            $business_name = '';
            $business_website = '';

            if ( isset( $json['businessName'] ) ) {
                $business_name = (string) $json['businessName'];
            }
            if ( isset( $json['website'] ) ) {
                $business_website = (string) $json['website'];
            }

            $payload = [
                'message' => __( 'API connected successfully!', 'willro-reviews' ),
            ];

            if ( ! empty( $business_name ) ) {
                $payload['message'] = sprintf(
                    /* translators: %s: business name. */
                    __( 'API connected successfully! Connected to %s.', 'willro-reviews' ),
                    $business_name
                );

                if ( ! empty( $business_website ) ) {
                    $payload['linkUrl']  = 'https://willro.com/review/' . rawurlencode( $business_website );
                    $payload['linkText'] = $business_name;
                }
            }

            wp_send_json_success( $payload );
        }

        if ( in_array($code, [401, 403], true) ) {
            wp_send_json_error([
                'message' => __( 'Invalid API key.', 'willro-reviews' )
            ]);
        }

        wp_send_json_error([
            'message' => sprintf(
                /* translators: %d: HTTP status code. */
                __( 'API error (HTTP %d).', 'willro-reviews' ),
                (int) $code
            )
        ]);
    }
}
