<?php
/**
 * Dakidarts Numerology Core - Admin Settings Page
 *
 * Handles API key input, endpoint activation toggles, and saving settings.
 *
 * @package Dakidarts_Numerology_Core
 */

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

if ( ! class_exists( 'Dakidarts_Admin_Settings' ) ) {

    class Dakidarts_Admin_Settings {

        private $option_key = 'dakidarts_numerology_core_settings';
        private $rapidapi_host = 'https://the-numerology-api.p.rapidapi.com';
        private $gateway_host  = 'https://api.numerologyapi.com/api/v1';
        private $gateway_langs = [ 'en', 'fr', 'es', 'de', 'pt' ];

        public function __construct() {
            add_action( 'admin_post_dakidarts_save_settings', [ $this, 'save_settings' ] );
            add_action( 'admin_notices', [ $this, 'render_notices' ] );
        }

        /**
         * Render the settings HTML.
         */
        public function render() {
            $options   = get_option( $this->option_key, [] );
            $has_api_key = ! empty( $options['api_key'] );
            $route     = isset( $options['route'] ) ? sanitize_key( $options['route'] ) : 'rapidapi';
            $lang      = isset( $options['lang'] ) ? sanitize_key( $options['lang'] ) : 'en';
            $endpoints = Dakidarts_API::get_endpoints();
            $docs_link = 'https://docs.numerologyapi.com/';
            $gateway_key_link = 'https://dashboard.numerologyapi.com/login';
            $rapidapi_link = 'https://rapidapi.com/';
            ?>
            <div class="dakidarts-admin-page dakidarts-admin-settings">
                <div class="dakidarts-hero">
                    <div class="dakidarts-hero__content">
                        <div class="dakidarts-hero__eyebrow">
                            <span class="dakidarts-pill"><i class="fa-solid fa-sliders"></i> <?php esc_html_e( 'Core Settings', 'dakidarts-numerology-core' ); ?></span>
                            <span class="dakidarts-pill dakidarts-pill--outline"><i class="fa-solid fa-globe"></i> <?php esc_html_e( 'Multi-language ready', 'dakidarts-numerology-core' ); ?></span>
                        </div>
                        <h1><?php esc_html_e( 'Numerology API Configuration', 'dakidarts-numerology-core' ); ?></h1>
                        <p><?php esc_html_e( 'Choose your preferred API route, set your key, and activate the endpoints you want to expose via shortcodes and blocks.', 'dakidarts-numerology-core' ); ?></p>
                        <div class="dakidarts-hero__actions">
                            <a class="dakidarts-btn dakidarts-btn--primary" target="_blank" rel="noopener" href="<?php echo esc_url( $docs_link ); ?>">
                                <i class="fa-solid fa-book"></i> <?php esc_html_e( 'API Docs', 'dakidarts-numerology-core' ); ?>
                            </a>
                            <a class="dakidarts-btn dakidarts-btn--ghost" target="_blank" rel="noopener" href="<?php echo esc_url( $gateway_key_link ); ?>">
                                <i class="fa-solid fa-key"></i> <?php esc_html_e( 'Get Gateway Key', 'dakidarts-numerology-core' ); ?>
                            </a>
                        </div>
                    </div>
                    <div class="dakidarts-hero__meta">
                        <div class="dakidarts-stat">
                            <span class="dakidarts-stat__label"><?php esc_html_e( 'Gateway Base URL', 'dakidarts-numerology-core' ); ?></span>
                            <span class="dakidarts-stat__value">https://api.numerologyapi.com/api/v1</span>
                        </div>
                        <div class="dakidarts-stat">
                            <span class="dakidarts-stat__label"><?php esc_html_e( 'RapidAPI Base URL', 'dakidarts-numerology-core' ); ?></span>
                            <span class="dakidarts-stat__value">https://the-numerology-api.p.rapidapi.com</span>
                        </div>
                    </div>
                </div>

                <form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" class="dakidarts-form">
                    <?php wp_nonce_field( 'dakidarts_save_settings' ); ?>
                    <input type="hidden" name="action" value="dakidarts_save_settings" />

                    <div class="dakidarts-grid">
                        <div class="dakidarts-card">
                            <div class="dakidarts-card__header">
                                <h2><i class="fa-solid fa-cloud"></i> <?php esc_html_e( 'Gateway & Access', 'dakidarts-numerology-core' ); ?></h2>
                                <p><?php esc_html_e( 'Switch between RapidAPI and the NumerologyAPI Gateway. Gateway unlocks multi-language responses.', 'dakidarts-numerology-core' ); ?></p>
                            </div>

                            <div class="dakidarts-field">
                                <label class="dakidarts-label"><?php esc_html_e( 'API Route', 'dakidarts-numerology-core' ); ?></label>
                                <div class="dakidarts-radio-group">
                                    <label class="dakidarts-radio-card">
                                        <input type="radio" name="route" value="gateway" <?php checked( 'gateway', $route ); ?> />
                                        <span class="dakidarts-radio-card__title"><i class="fa-solid fa-network-wired"></i> <?php esc_html_e( 'NumerologyAPI Gateway', 'dakidarts-numerology-core' ); ?></span>
                                        <span class="dakidarts-radio-card__desc"><?php esc_html_e( 'Direct infrastructure, multilingual responses, and enterprise-grade reliability.', 'dakidarts-numerology-core' ); ?></span>
                                    </label>
                                    <label class="dakidarts-radio-card">
                                        <input type="radio" name="route" value="rapidapi" <?php checked( 'rapidapi', $route ); ?> />
                                        <span class="dakidarts-radio-card__title"><i class="fa-brands fa-empire"></i> <?php esc_html_e( 'RapidAPI', 'dakidarts-numerology-core' ); ?></span>
                                        <span class="dakidarts-radio-card__desc"><?php esc_html_e( 'Legacy route with English-only responses.', 'dakidarts-numerology-core' ); ?></span>
                                    </label>
                                </div>
                            </div>

                            <div class="dakidarts-field" data-route-field="gateway">
                                <label class="dakidarts-label" for="dakidarts_gateway_lang"><?php esc_html_e( 'Gateway Language', 'dakidarts-numerology-core' ); ?></label>
                                <select id="dakidarts_gateway_lang" name="lang">
                                    <?php foreach ( $this->gateway_langs as $lang_code ) : ?>
                                        <option value="<?php echo esc_attr( $lang_code ); ?>" <?php selected( $lang, $lang_code ); ?>>
                                            <?php echo esc_html( strtoupper( $lang_code ) ); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                                <p class="dakidarts-help"><?php esc_html_e( 'Language is applied as a query parameter for all Gateway requests.', 'dakidarts-numerology-core' ); ?></p>
                            </div>

                            <div class="dakidarts-field">
                                <label class="dakidarts-label" for="dakidarts_api_key"><?php esc_html_e( 'API Key', 'dakidarts-numerology-core' ); ?></label>
                                <input id="dakidarts_api_key" type="password" name="api_key" value=""
                                       placeholder="<?php echo $has_api_key ? esc_attr__( 'Enter new API Key to update', 'dakidarts-numerology-core' ) : esc_attr__( 'Enter API Key', 'dakidarts-numerology-core' ); ?>" />
                                <?php if ( $has_api_key ) : ?>
                                    <p class="dakidarts-help"><i class="fa-solid fa-lock"></i> <?php esc_html_e( 'API Key is stored securely. Leave blank to keep current key.', 'dakidarts-numerology-core' ); ?></p>
                                <?php endif; ?>
                            </div>

                            <div class="dakidarts-links">
                                <a class="dakidarts-link" target="_blank" rel="noopener" href="<?php echo esc_url( $gateway_key_link ); ?>">
                                    <i class="fa-solid fa-arrow-up-right-from-square"></i> <?php esc_html_e( 'Get Gateway API Key', 'dakidarts-numerology-core' ); ?>
                                </a>
                                <a class="dakidarts-link" target="_blank" rel="noopener" href="<?php echo esc_url( $rapidapi_link ); ?>">
                                    <i class="fa-solid fa-arrow-up-right-from-square"></i> <?php esc_html_e( 'RapidAPI Marketplace', 'dakidarts-numerology-core' ); ?>
                                </a>
                            </div>
                        </div>

                        <div class="dakidarts-card">
                            <div class="dakidarts-card__header">
                                <h2><i class="fa-solid fa-bolt"></i> <?php esc_html_e( 'Endpoints', 'dakidarts-numerology-core' ); ?></h2>
                                <p><?php esc_html_e( 'Toggle which Numerology endpoints should be active and available via shortcode.', 'dakidarts-numerology-core' ); ?></p>
                            </div>
                            <p class="dakidarts-help"><i class="fa-solid fa-circle-info"></i> <?php esc_html_e( 'All calculations are sent via POST to keep front-end forms fast and avoid page refreshes.', 'dakidarts-numerology-core' ); ?></p>
                            <div class="dakidarts-endpoint-list">
                                <?php foreach ( $endpoints as $key => $endpoint ) :
                                    $checked   = isset( $options['endpoints'][ $key ] ) ? checked( 1, $options['endpoints'][ $key ], false ) : '';
                                    $shortcode = '[dakidarts_numerology endpoint="' . esc_attr( $key ) . '"]';
                                    ?>
                                    <label class="dakidarts-toggle">
                                        <input class="dakidarts-endpoint-toggle" type="checkbox" name="endpoints[<?php echo esc_attr( $key ); ?>]" value="1" <?php echo esc_attr( $checked ); ?> data-endpoint="<?php echo esc_attr( $key ); ?>" />
                                        <span class="dakidarts-toggle__ui"></span>
                                        <span class="dakidarts-toggle__content">
                                            <span class="dakidarts-toggle__title"><?php echo esc_html( $endpoint['label'] ); ?></span>
                                            <span class="dakidarts-toggle__meta"><?php echo esc_html( $shortcode ); ?></span>
                                        </span>
                                    </label>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    </div>

                    <div class="dakidarts-card dakidarts-card--footer">
                        <button type="submit" class="button button-primary dakidarts-btn dakidarts-btn--primary dakidarts-save-btn">
                            <i class="fa-solid fa-floppy-disk"></i> <?php esc_html_e( 'Save Settings', 'dakidarts-numerology-core' ); ?>
                        </button>
                    </div>
                </form>
            </div>
            <?php
        }

        /**
         * Save settings handler.
         */
        public function save_settings() {
            if ( ! current_user_can( 'manage_options' ) ) {
                wp_die( esc_html__( 'You are not allowed to perform this action.', 'dakidarts-numerology-core' ) );
            }

            check_admin_referer( 'dakidarts_save_settings' );

            $options = get_option( $this->option_key, [] );
            $input   = [];
            $message = __( 'Settings saved successfully!', 'dakidarts-numerology-core' );
            $type    = 'success';

            // Save route
            $route = isset( $_POST['route'] ) ? sanitize_key( wp_unslash( $_POST['route'] ) ) : 'rapidapi';
            if ( ! in_array( $route, [ 'rapidapi', 'gateway' ], true ) ) {
                $route = 'rapidapi';
            }
            $input['route'] = $route;

            // Save language
            if ( $route === 'gateway' && isset( $_POST['lang'] ) ) {
                $lang = sanitize_key( wp_unslash( $_POST['lang'] ) );
                $input['lang'] = in_array( $lang, $this->gateway_langs, true ) ? $lang : 'en';
            } else {
                $input['lang'] = isset( $options['lang'] ) ? $options['lang'] : 'en';
            }

            // Save API key - only if new one provided
            if ( ! empty( $_POST['api_key'] ) ) {
                $api_key = sanitize_text_field( wp_unslash( $_POST['api_key'] ) );
                
                if ( $this->validate_api_key( $api_key, $route ) ) {
                    $input['api_key'] = Dakidarts_Helpers::encrypt( $api_key, DAKIDARTS_SECRET_KEY );
                    $message = __( 'Settings and API Key saved successfully!', 'dakidarts-numerology-core' );
                } else {
                    $message = __( 'Settings saved, but API Key validation failed. Please check your key.', 'dakidarts-numerology-core' );
                    $type    = 'error';
                    $input['api_key'] = isset( $options['api_key'] ) ? $options['api_key'] : '';
                }
            } else {
                // Keep existing API key
                $input['api_key'] = isset( $options['api_key'] ) ? $options['api_key'] : '';
            }

            // Save endpoints toggles
            $input['endpoints'] = [];
            $raw_endpoints = filter_input( INPUT_POST, 'endpoints', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY );
            if ( is_array( $raw_endpoints ) ) {
                foreach ( $raw_endpoints as $key => $value ) {
                    $input['endpoints'][ sanitize_key( $key ) ] = 1;
                }
            }

            update_option( $this->option_key, $input );

            set_transient( 'dakidarts_admin_notice', [ 'message' => $message, 'type' => $type ], 30 );

            wp_safe_redirect( admin_url( 'admin.php?page=dakidarts-numerology-settings' ) );
            exit;
        }

        /**
         * Validate the API key by making a request to the status endpoint.
         */
        private function validate_api_key( $api_key, $route ) {
            $url = ( $route === 'gateway' ) ? $this->gateway_host . '/health' : $this->rapidapi_host . '/status';

            $headers = ( $route === 'gateway' )
                ? [ 'X-API-Key' => $api_key ]
                : [
                    'X-RapidAPI-Key'  => $api_key,
                    'X-RapidAPI-Host' => 'the-numerology-api.p.rapidapi.com',
                ];

            $response = wp_remote_get( $url, [
                'headers' => $headers,
                'timeout' => 15,
            ] );

            if ( is_wp_error( $response ) ) {
                return false;
            }

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

            if ( $code >= 200 && $code < 300 ) {
                if ( isset( $data['status'] ) ) {
                    return in_array( strtolower( (string) $data['status'] ), [ 'api is online', 'ok', 'online', 'healthy' ], true );
                }

                return true;
            }

            return false;
        }

        /**
         * Render notices (popups) that disappear after 5s.
         */
        public function render_notices() {
            $notice = get_transient( 'dakidarts_admin_notice' );
            if ( ! $notice ) {
                return;
            }

            delete_transient( 'dakidarts_admin_notice' );

            $type = $notice['type'] === 'error' ? 'error' : 'success';
            $icon = $type === 'success' ? 'fa-circle-check' : 'fa-circle-xmark';
            ?>
            <div class="dakidarts-notice dakidarts-notice--<?php echo esc_attr( $type ); ?>">
                <span class="dakidarts-notice__icon"><i class="fa-solid <?php echo esc_attr( $icon ); ?>"></i></span>
                <span class="dakidarts-notice__message"><?php echo esc_html( $notice['message'] ); ?></span>
            </div>
            <?php
        }
    }
}
