<?php

namespace Fotogenic_AI;

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

final class Settings_Page {
    private static ?Settings_Page $instance = null;
    private string $settings_page_hook = '';

    private function __construct() {}

    public static function instance(): Settings_Page {
        if ( null === self::$instance ) {
            self::$instance = new self();
        }

        return self::$instance;
    }

    public function init(): void {
        add_action( 'admin_menu', [ $this, 'register_menu' ], 20 );
        add_action( 'admin_init', [ $this, 'register_settings' ] );
        add_action( 'admin_enqueue_scripts', [ $this, 'enqueue_assets' ] );
    }

    public function enqueue_assets( string $hook_suffix ): void {
        if ( $hook_suffix !== $this->get_settings_page_hook() ) {
            return;
        }
        if ( ! class_exists( __NAMESPACE__ . '\\Modules_Registry' ) ) {
            Assets_Manifest::enqueue_style( 'fotogenic-ai-shared-ui-icons-css' );
			Assets_Manifest::enqueue_style( 'fotogenic-ai-direct-port-css' );
            Assets_Manifest::enqueue_style( 'fotogenic-ai-shared' );
            Assets_Manifest::enqueue_style( 'fotogenic-ai-settings' );
        }
    }

    public function get_settings_page_hook(): string {
        return $this->settings_page_hook;
    }

    public static function get_pricing_url(): string {
        return Auth_Session::instance()->get_pricing_url();
    }

    public static function get_account_url(): string {
        return Auth_Session::instance()->get_account_url();
    }

    public static function get_manage_credits_url(): string {
        return Auth_Session::instance()->get_manage_url();
    }

    public static function get_buy_credits_url(): string {
        return self::get_manage_credits_url();
    }

    public static function get_privacy_policy_url(): string {
        return (string) apply_filters( 'fotogenic_ai_privacy_policy_url', 'https://fotogenic.ai/privacy-policy/' );
    }

    public static function get_support_url(): string {
        return (string) apply_filters( 'fotogenic_ai_support_url', 'https://fotogenic.ai/contact' );
    }

    public static function get_website_url(): string {
        return (string) apply_filters( 'fotogenic_ai_website_url', 'https://fotogenic.ai' );
    }

    public static function get_web_app_url(): string {
        return (string) apply_filters( 'fotogenic_ai_web_app_url', 'https://app.fotogenic.ai/' );
    }

    public static function get_logo_url(): string {
        return ( defined( 'FOTOGENIC_AI_URL' ) ? FOTOGENIC_AI_URL : '' ) . 'assets/shared/img/fotogenic-logo.png';
    }

    public function register_menu(): void {
        $this->settings_page_hook = add_submenu_page(
            'fotogenic-studio',
            __( 'Fotogenic AI Settings', 'fotogenic-ai' ),
            __( 'Settings', 'fotogenic-ai' ),
            fotogenic_ai_minimum_cap(),
            'fotogenic-ai',
            [ $this, 'render_settings_page' ]
        );
    }

    public function register_settings(): void {
        $settings = Settings::instance();
        register_setting(
            'fotogenic_ai_settings',
            $settings->get_option_name(),
            [
                'type'              => 'array',
                'sanitize_callback' => [ $settings, 'sanitize_settings' ],
                'default'           => $settings->get_defaults(),
            ]
        );

        add_settings_section(
            'fotogenic_ai_account',
            __( 'Fotogenic AI account', 'fotogenic-ai' ),
            '__return_false',
            'fotogenic-ai'
        );

        add_settings_field(
            'auth_connection',
            '',
            [ $this, 'render_auth_connection_field' ],
            'fotogenic-ai',
            'fotogenic_ai_account',
            [
                'class' => 'fotogenic-ai-settings-row--auth',
            ]
        );

        add_settings_section(
            'fotogenic_ai_defaults',
            __( 'Default generation settings', 'fotogenic-ai' ),
            '__return_false',
            'fotogenic-ai'
        );

        add_settings_field(
            'custom_instructions',
            __( 'Global custom instructions', 'fotogenic-ai' ),
            [ $this, 'render_custom_instructions_field' ],
            'fotogenic-ai',
            'fotogenic_ai_defaults'
        );

        add_settings_section(
            'fotogenic_ai_toggles',
            __( 'Feature toggles', 'fotogenic-ai' ),
            '__return_false',
            'fotogenic-ai'
        );

        add_settings_field(
            'debug_logging',
            __( 'Debug logging', 'fotogenic-ai' ),
            [ $this, 'render_debug_logging_field' ],
            'fotogenic-ai',
            'fotogenic_ai_toggles'
        );

        add_settings_field(
            'delete_data_on_uninstall',
            __( 'Data deletion on uninstall', 'fotogenic-ai' ),
            [ $this, 'render_delete_data_on_uninstall_field' ],
            'fotogenic-ai',
            'fotogenic_ai_toggles'
        );
    }

    public function render_settings_page(): void {
        if ( ! fotogenic_ai_user_can_access() ) {
            wp_die( esc_html__( 'Sorry, you are not allowed to access this page.', 'fotogenic-ai' ) );
        }

        $settings              = Settings::instance();
        $option_name           = $settings->get_option_name();
        $options               = $settings->get_options();
		$auth_status           = Auth_Session::instance()->get_public_status();
		$auth_connected        = ! empty( $auth_status['connected'] );
		$debug_logging_enabled = ! empty( $options['debug_logging'] );
		$toolbar_view_model    = Studio_Toolbar_View_Model::build(
			fotogenic_ai_get_signed_navigation_query_args(),
			Studio_Targets_Manifest::get_targets(),
			Plugin::instance()->compat()->is_woocommerce_active(),
			'settings'
		);
		$credits_balance       = array_key_exists( 'balance', $auth_status ) && null !== $auth_status['balance']
            ? (float) $auth_status['balance']
            : null;

        require FOTOGENIC_AI_PATH . 'templates/settings/settings-page.php';
    }

    public function render_auth_connection_field(): void {
        $auth_status     = Auth_Session::instance()->get_public_status();
        $connected       = ! empty( $auth_status['connected'] );
        $account_email   = $connected ? (string) ( $auth_status['user']['email'] ?? '' ) : '';
        $account_url     = ! empty( $auth_status['accountUrl'] ) ? (string) $auth_status['accountUrl'] : self::get_account_url();
        $credits_url     = self::get_buy_credits_url();
        $credits_balance = array_key_exists( 'balance', $auth_status ) && null !== $auth_status['balance']
            ? (int) round( (float) $auth_status['balance'] )
            : null;
        ?>
        <div class="fotogenic-ai-settings-auth<?php echo $connected ? ' is-connected' : ' is-disconnected'; ?>" id="fotogenic-ai-auth-wrap">
            <div class="fotogenic-ai-settings-auth__overview">
                <div class="fotogenic-ai-settings-auth__identity">
                    <span class="fotogenic-ai-settings-auth__status">
                        <span class="fotogenic-ai-settings-auth__status-dot" aria-hidden="true"></span>
                        <strong class="fotogenic-ai-settings-auth__title" id="fotogenic-ai-auth-title">
                            <?php echo $connected ? esc_html__( 'Connected', 'fotogenic-ai' ) : esc_html__( 'Not connected', 'fotogenic-ai' ); ?>
                        </strong>
                    </span>
                    <small class="fotogenic-ai-settings-auth__email" id="fotogenic-ai-auth-email"<?php echo '' === $account_email ? ' hidden' : ''; ?>><?php echo esc_html( $account_email ); ?></small>
                </div>
                <span class="fotogenic-ai-settings-auth__separator" aria-hidden="true"></span>
                <span class="fotogenic-ai-settings-auth__credits">
                    <strong id="fotogenic-ai-settings-account-credits">
                        <?php
                        if ( $connected && null !== $credits_balance ) {
                            printf(
                                /* translators: %s: current credits balance. */
                                esc_html__( '%s credits', 'fotogenic-ai' ),
                                esc_html( number_format_i18n( $credits_balance ) )
                            );
                        } elseif ( $connected ) {
                            esc_html_e( 'Balance unknown', 'fotogenic-ai' );
                        } else {
                            esc_html_e( 'Connect to continue', 'fotogenic-ai' );
                        }
                        ?>
                    </strong>
                    <button type="button" class="fotogenic-ai-settings-auth__refresh" id="fotogenic-ai-credits-refresh" aria-label="<?php esc_attr_e( 'Refresh credits balance', 'fotogenic-ai' ); ?>"<?php echo $connected ? '' : ' hidden'; ?>>
                        <span class="fotogenic-ai-icon fotogenic-ai-icon--arrows-clockwise fotogenic-ai-icon--regular fotogenic-ai-icon--size-17" aria-hidden="true"></span>
                    </button>
                </span>
            </div>
            <div class="fotogenic-ai-settings-auth__actions">
                <button
                    type="button"
                    class="fotogenic-ai-settings-auth__primary"
                    id="fotogenic-ai-auth-login"
                    data-auth-action="<?php echo $connected ? 'topup' : 'login'; ?>"
                    data-topup-url="<?php echo esc_url( $credits_url ); ?>"
                >
                    <span
                        class="fotogenic-ai-icon fotogenic-ai-icon--<?php echo $connected ? 'credit-card' : 'sign-in'; ?> fotogenic-ai-icon--bold fotogenic-ai-icon--size-17"
                        data-fa-settings-auth-primary-icon
                        aria-hidden="true"
                    ></span>
                    <span data-auth-primary-label><?php echo $connected ? esc_html__( 'Top up', 'fotogenic-ai' ) : esc_html__( 'Connect', 'fotogenic-ai' ); ?></span>
                </button>
                <button
                    type="button"
                    class="fotogenic-ai-settings-auth__secondary"
                    id="fotogenic-ai-auth-manage"
                    data-account-url="<?php echo esc_url( $account_url ); ?>"
                    <?php echo $connected ? '' : ' disabled aria-disabled="true"'; ?>
                >
                    <span class="fotogenic-ai-icon fotogenic-ai-icon--user-circle fotogenic-ai-icon--regular fotogenic-ai-icon--size-18" aria-hidden="true"></span>
                    <?php esc_html_e( 'Manage account', 'fotogenic-ai' ); ?>
                </button>
            </div>
        </div>
        <?php
    }

    public function render_custom_instructions_field(): void {
        $options = Settings::instance()->get_options();
        ?>
        <textarea
            id="fotogenic-ai-settings-custom-instructions"
            name="<?php echo esc_attr( Settings::instance()->get_option_name() ); ?>[custom_instructions]"
            maxlength="5000"
            class="fotogenic-ai-field fotogenic-ai-field--textarea"
            aria-describedby="fotogenic-ai-settings-guidance-count"
            placeholder="<?php echo esc_attr__( 'Add product-first framing, campaign tone, or other useful direction.', 'fotogenic-ai' ); ?>"
        ><?php echo esc_textarea( $options['custom_instructions'] ); ?></textarea>
        <?php
    }

    public function render_debug_logging_field(): void {
        $options = Settings::instance()->get_options();
        ?>
        <input type="checkbox" id="fotogenic-ai-settings-debug-logging" name="<?php echo esc_attr( Settings::instance()->get_option_name() ); ?>[debug_logging]" value="1" <?php checked( $options['debug_logging'], 1 ); ?> />
        <?php
    }

    public function render_delete_data_on_uninstall_field(): void {
        $options = Settings::instance()->get_options();
        ?>
        <input type="checkbox" id="fotogenic-ai-settings-delete-data" name="<?php echo esc_attr( Settings::instance()->get_option_name() ); ?>[delete_data_on_uninstall]" value="1" <?php checked( $options['delete_data_on_uninstall'], 1 ); ?> />
        <?php
    }
}
