<?php
/**
 * Settings Manager
 *
 * Handles plugin settings registration and sanitization.
 */

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

class Tiriri_Settings {

    /**
     * Initialize settings
     */
    public function init() {
        add_action( 'admin_init', array( $this, 'register_settings' ) );
    }

    /**
     * Register plugin settings
     */
    public function register_settings() {
        register_setting(
            'tiriri_settings_group',
            'tiriri_settings',
            array(
                'type'              => 'array',
                'sanitize_callback' => array( $this, 'sanitize_settings' ),
                'default'           => array(),
            )
        );
    }

    /**
     * Sanitize settings before save
     */
    public function sanitize_settings( $input ) {
        $sanitized = array();

        // Chatbot disclosure
        $sanitized['chatbot_disclosure_enabled'] = ! empty( $input['chatbot_disclosure_enabled'] );
        $sanitized['chatbot_disclosure_text'] = sanitize_text_field( $input['chatbot_disclosure_text'] ?? '' );

        $position = sanitize_text_field( $input['chatbot_disclosure_position'] ?? 'before_chat' );
        $sanitized['chatbot_disclosure_position'] = in_array( $position, array( 'before_chat', 'after_chat', 'top' ), true ) ? $position : 'before_chat';

        $style = sanitize_text_field( $input['chatbot_disclosure_style'] ?? 'banner' );
        $sanitized['chatbot_disclosure_style'] = in_array( $style, array( 'banner', 'tooltip', 'inline' ), true ) ? $style : 'banner';

        // Content labeling
        $sanitized['content_labeling_enabled'] = ! empty( $input['content_labeling_enabled'] );

        // Script scanning
        $sanitized['scan_third_party_scripts'] = ! empty( $input['scan_third_party_scripts'] );

        // Language
        $language = sanitize_text_field( $input['disclosure_language'] ?? 'auto' );
        $allowed_languages = array( 'auto', 'en', 'de', 'fr', 'es', 'it', 'nl', 'pt', 'pl', 'ro', 'sv', 'da', 'fi', 'el', 'cs', 'hu', 'bg', 'hr', 'sk', 'sl', 'et', 'lv', 'lt', 'mt', 'ga' );
        $sanitized['disclosure_language'] = in_array( $language, $allowed_languages, true ) ? $language : 'auto';

        return $sanitized;
    }

    /**
     * Get a specific setting
     */
    public static function get( $key, $default = null ) {
        $settings = get_option( 'tiriri_settings', array() );
        return isset( $settings[ $key ] ) ? $settings[ $key ] : $default;
    }
}
