<?php

class SAVEAMSU_Settings {

    const OPTION_KEY = 'saveamsu_settings';

    public static function init() {
        add_action( 'admin_menu', array( __CLASS__, 'add_menu' ) );
        add_action( 'admin_init', array( __CLASS__, 'register_settings' ) );
    }

    public static function add_menu() {
        add_options_page(
            __( 'Save & Summarize', 'save-summarize-ai-digest-for-saved-articles' ),
            __( 'Save & Summarize', 'save-summarize-ai-digest-for-saved-articles' ),
            'manage_options',
            SAVEAMSU_SETTINGS_PAGE_SLUG,
            array( __CLASS__, 'render_settings_page' )
        );
    }

    public static function register_settings() {
        register_setting( 'saveamsu_settings_group', self::OPTION_KEY, array(
            'sanitize_callback' => array( __CLASS__, 'sanitize' ),
        ) );

        add_settings_section(
            'saveamsu_main_section',
            __( 'Save & Summarize Settings', 'save-summarize-ai-digest-for-saved-articles' ),
            '__return_false',
            SAVEAMSU_SETTINGS_PAGE_SLUG
        );

        add_settings_field(
            'api_key',
            __( 'OpenAI API Key (optional)', 'save-summarize-ai-digest-for-saved-articles' ),
            array( __CLASS__, 'field_api_key' ),
            SAVEAMSU_SETTINGS_PAGE_SLUG,
            'saveamsu_main_section'
        );

        add_settings_field(
            'enable_digest',
            __( 'Enable Weekly Digest', 'save-summarize-ai-digest-for-saved-articles' ),
            array( __CLASS__, 'field_enable_digest' ),
            SAVEAMSU_SETTINGS_PAGE_SLUG,
            'saveamsu_main_section'
        );

        add_settings_field(
            'email_subject',
            __( 'Digest Email Subject', 'save-summarize-ai-digest-for-saved-articles' ),
            array( __CLASS__, 'field_email_subject' ),
            SAVEAMSU_SETTINGS_PAGE_SLUG,
            'saveamsu_main_section'
        );

        add_settings_field(
            'email_intro',
            __( 'Digest Email Intro Text', 'save-summarize-ai-digest-for-saved-articles' ),
            array( __CLASS__, 'field_email_intro' ),
            SAVEAMSU_SETTINGS_PAGE_SLUG,
            'saveamsu_main_section'
        );
    }

    public static function get_settings() {
        $defaults = array(
            'api_key'       => '',
            'enable_digest' => 1,
            'email_subject' => __( 'Your Saved Articles Digest', 'save-summarize-ai-digest-for-saved-articles' ),
            'email_intro'   => __( 'Here is your weekly summary of saved articles.', 'save-summarize-ai-digest-for-saved-articles' ),
        );

        $settings = get_option( self::OPTION_KEY, null );

        if ( null === $settings ) {
            $legacy_settings = get_option( 'ss_settings', null );

            if ( null !== $legacy_settings ) {
                $settings = $legacy_settings;
                update_option( self::OPTION_KEY, $legacy_settings );
            } else {
                $settings = array();
            }
        }

        return wp_parse_args( $settings, $defaults );
    }

    public static function sanitize( $input ) {
        $output                     = self::get_settings();
        $output['api_key']          = isset( $input['api_key'] ) ? trim( $input['api_key'] ) : '';
        $output['enable_digest']    = ! empty( $input['enable_digest'] ) ? 1 : 0;
        $output['email_subject']    = sanitize_text_field( $input['email_subject'] ?? '' );
        $output['email_intro']      = wp_kses_post( $input['email_intro'] ?? '' );
        return $output;
    }

    public static function field_api_key() {
        $settings = self::get_settings();
        ?>
        <input type="password" name="<?php echo esc_attr( self::OPTION_KEY ); ?>[api_key]"
               value="<?php echo esc_attr( $settings['api_key'] ); ?>" size="50" />
        <p class="description">
            <?php esc_html_e( 'Optional. Used to generate AI summaries. Plugin works without it.', 'save-summarize-ai-digest-for-saved-articles' ); ?>
        </p>
        <?php
    }

    public static function field_enable_digest() {
        $settings = self::get_settings();
        ?>
        <label>
            <input type="checkbox" name="<?php echo esc_attr( self::OPTION_KEY ); ?>[enable_digest]"
                   value="1" <?php checked( $settings['enable_digest'], 1 ); ?> />
            <?php esc_html_e( 'Send weekly digest emails to users with saved posts.', 'save-summarize-ai-digest-for-saved-articles' ); ?>
        </label>
        <?php
    }

    public static function field_email_subject() {
        $settings = self::get_settings();
        ?>
        <input type="text" name="<?php echo esc_attr( self::OPTION_KEY ); ?>[email_subject]"
               value="<?php echo esc_attr( $settings['email_subject'] ); ?>" size="60" />
        <?php
    }

    public static function field_email_intro() {
        $settings = self::get_settings();
        ?>
        <textarea name="<?php echo esc_attr( self::OPTION_KEY ); ?>[email_intro]" rows="4" cols="60"><?php
            echo esc_textarea( $settings['email_intro'] );
        ?></textarea>
        <?php
    }

    public static function render_settings_page() {
        ?>
        <div class="wrap">
            <form method="post" action="options.php">
                <?php
                settings_fields( 'saveamsu_settings_group' );
                do_settings_sections( SAVEAMSU_SETTINGS_PAGE_SLUG );
                submit_button();
                ?>
            </form>
        </div>
        <?php
    }
}
