<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class Arcai_Settings {

	const OPTION = 'arcai_settings';

	public static function defaults() {
		return array(
			'api_key'         => '',
			'chat_model'      => 'gpt-4o-mini',
			'embedding_model' => 'text-embedding-3-small',
			'post_types'      => array( 'post' ),
			'daily_cap'       => 5.0,
			'rate_limit'      => 20,
			'bubble_enabled'  => 1,
			'bubble_color'    => '#1a1a2e',
			'greeting'        => __( 'Hi! Ask me anything about our articles.', 'archivist-ai' ),
			'require_login'   => 0,
		);
	}

	public static function all() {
		$saved = get_option( self::OPTION, array() );
		return wp_parse_args( is_array( $saved ) ? $saved : array(), self::defaults() );
	}

	public static function get( $key ) {
		$settings = self::all();
		return isset( $settings[ $key ] ) ? $settings[ $key ] : null;
	}

	public static function sanitize( $input ) {
		$defaults = self::defaults();
		$clean    = array();

		$clean['api_key']         = isset( $input['api_key'] ) ? trim( sanitize_text_field( $input['api_key'] ) ) : '';
		$clean['chat_model']      = isset( $input['chat_model'] ) && '' !== trim( $input['chat_model'] ) ? sanitize_text_field( $input['chat_model'] ) : $defaults['chat_model'];
		$clean['embedding_model'] = isset( $input['embedding_model'] ) && '' !== trim( $input['embedding_model'] ) ? sanitize_text_field( $input['embedding_model'] ) : $defaults['embedding_model'];

		$clean['post_types'] = array();
		if ( ! empty( $input['post_types'] ) && is_array( $input['post_types'] ) ) {
			foreach ( $input['post_types'] as $type ) {
				$type = sanitize_key( $type );
				if ( post_type_exists( $type ) ) {
					$clean['post_types'][] = $type;
				}
			}
		}
		if ( empty( $clean['post_types'] ) ) {
			$clean['post_types'] = $defaults['post_types'];
		}

		$clean['daily_cap']      = isset( $input['daily_cap'] ) ? max( 0, (float) $input['daily_cap'] ) : $defaults['daily_cap'];
		$clean['rate_limit']     = isset( $input['rate_limit'] ) ? max( 1, absint( $input['rate_limit'] ) ) : $defaults['rate_limit'];
		$clean['bubble_enabled'] = empty( $input['bubble_enabled'] ) ? 0 : 1;
		$clean['bubble_color']   = isset( $input['bubble_color'] ) ? sanitize_hex_color( $input['bubble_color'] ) : $defaults['bubble_color'];
		if ( ! $clean['bubble_color'] ) {
			$clean['bubble_color'] = $defaults['bubble_color'];
		}
		$clean['greeting'] = isset( $input['greeting'] ) ? sanitize_text_field( $input['greeting'] ) : $defaults['greeting'];

		$current                = self::all();
		$clean['require_login'] = arcai_is_pro()
			? ( empty( $input['require_login'] ) ? 0 : 1 )
			: (int) $current['require_login'];

		return $clean;
	}
}
