<?php
/**
 * This file is part of the Wisewand WordPress plugin.
 *
 * @package Wisewand
 * @since 1.0.0
 * @license GPL-2.0-or-later
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
 */
namespace Wisewand\Utils;

// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class Options {

	private $cache = array();

	public function get( $option_name, $default = null ) {
		if ( ! isset( $this->cache[ $option_name ] ) ) {
			$this->cache[ $option_name ] = get_option( $option_name, $default );
		}
		return $this->cache[ $option_name ];
	}

	public function set( $option_name, $value ) {
		$this->cache[ $option_name ] = $value;
		return update_option( $option_name, $value );
	}

	public function delete( $option_name ) {
		unset( $this->cache[ $option_name ] );
		return delete_option( $option_name );
	}

	public function get_security_settings() {
		return array(
			'hmac_secret'          => $this->get( 'wisewand_hmac_secret', '' ),
			'timestamp_skew'       => $this->get( 'wisewand_timestamp_skew', 300 ),
			'ip_whitelist'         => $this->get( 'wisewand_ip_whitelist', '' ),
			'rate_limit_enabled'   => $this->get( 'wisewand_rate_limit_enabled', true ),
			'rate_limit_requests'  => $this->get( 'wisewand_rate_limit_requests', 60 ),
			'rate_limit_window'    => $this->get( 'wisewand_rate_limit_window', 600 ),
			'enable_app_passwords' => $this->get( 'wisewand_enable_app_passwords', false ),
		);
	}

	public function get_content_settings() {
		return array(
			'allowed_post_types'     => $this->get( 'wisewand_allowed_post_types', array( 'post', 'page' ) ),
			'default_post_status'    => $this->get( 'wisewand_default_post_status', 'draft' ),
			'fallback_author'        => $this->get( 'wisewand_fallback_author', 1 ),
			'auto_create_categories' => $this->get( 'wisewand_auto_create_categories', true ),
			'auto_create_tags'       => $this->get( 'wisewand_auto_create_tags', true ),
			'allow_slug_override'    => $this->get( 'wisewand_allow_slug_override', true ),
		);
	}

	public function get_media_settings() {
		return array(
			'max_size'               => $this->get( 'wisewand_media_max_size', 5242880 ),
			'timeout'                => $this->get( 'wisewand_media_timeout', 10 ),
			'allowed_mime_types'     => $this->get(
				'wisewand_allowed_mime_types',
				array(
					'image/jpeg',
					'image/png',
					'image/webp',
					'image/gif',
					'audio/mpeg',
					'audio/wav',
				)
			),
			'download_inline_images' => $this->get( 'wisewand_download_inline_images', true ),
			'allowed_domains'        => $this->get( 'wisewand_allowed_domains', '' ),
			'add_audio_player'       => $this->get( 'wisewand_add_audio_player', true ),
			'audio_player_position'  => $this->get( 'wisewand_audio_player_position', 'top' ),
			'remove_h1_tags'         => $this->get( 'wisewand_remove_h1_tags', true ),
			// Optional override for smart SSRF protection (auto-detection is default)
			'allow_internal_urls'    => $this->get( 'wisewand_allow_internal_media_urls', null ),
		);
	}

	public function get_seo_settings() {
		return array(
			'mode'         => $this->get( 'wisewand_seo_mode', 'auto' ),
			'meta_mapping' => $this->get( 'wisewand_seo_meta_mapping', array() ),
		);
	}

	public function get_wpml_settings() {
		return array(
			'enabled'      => $this->get( 'wisewand_wpml_enabled', false ),
			'lang_mapping' => $this->get( 'wisewand_wpml_lang_mapping', array() ),
			'default_lang' => $this->get( 'wisewand_wpml_default_lang', '' ),
		);
	}

	public function get_logging_settings() {
		return array(
			'enabled'        => $this->get( 'wisewand_logging_enabled', true ),
			'debug_mode'     => $this->get( 'wisewand_debug_mode', false ),
			'max_entries'    => $this->get( 'wisewand_log_max_entries', 200 ),
			'retention_days' => $this->get( 'wisewand_log_retention_days', 30 ),
		);
	}

	public function get_pull_settings() {
		return array(
			'api_key'  => $this->get( 'wisewand_pull_api_key', '' ),
			'base_url' => $this->get( 'wisewand_pull_base_url', 'https://api.wisewand.ai/v1' ),
			'timeout'  => $this->get( 'wisewand_pull_timeout', 3600 ),
		);
	}


	public function get_custom_fields_whitelist() {
		return $this->get( 'wisewand_custom_fields_whitelist', array() );
	}

	public function get_openai_settings() {
		return array(
			'api_key'                => $this->get( 'wisewand_openai_api_key', '' ),
			'category_matching_mode' => $this->get( 'wisewand_category_matching_mode', 'auto' ), // auto, strict, fallback
		);
	}

	public function is_yoast_active() {
		return defined( 'WPSEO_VERSION' );
	}

	public function is_rankmath_active() {
		return defined( 'RANK_MATH_VERSION' );
	}

	public function is_seopress_active() {
		return defined( 'SEOPRESS_VERSION' );
	}

	public function is_wpml_active() {
		return defined( 'ICL_SITEPRESS_VERSION' );
	}


	public function is_polylang_active() {
		return function_exists( 'pll_languages_list' );
	}

	/**
	 * Get author ID for a language with proper fallback chain
	 *
	 * Fallback order:
	 * 1. Language-specific author (wisewand_default_author_{lang})
	 * 2. General fallback author (wisewand_fallback_author)
	 * 3. First available author from get_users()
	 * 4. Current user (last resort)
	 *
	 * @param string $lang Language code (en, fr, de, es, it, pt, etc.)
	 * @return int Author ID
	 */
	public function get_author_for_language( $lang = 'en' ) {
		// Normalize language code to 2-letter lowercase
		$lang = strtolower( substr( $lang, 0, 2 ) );

		// Try language-specific author
		$author_id = $this->get( "wisewand_default_author_{$lang}", null );

		if ( $author_id && $this->is_valid_author( $author_id ) ) {
			return intval( $author_id );
		}

		// Try general fallback author
		$fallback_id = $this->get( 'wisewand_fallback_author', null );

		if ( $fallback_id && $this->is_valid_author( $fallback_id ) ) {
			return intval( $fallback_id );
		}

		// Last resort: First available author (fixed: 'who' deprecated since WP 5.9)
		$users = get_users(
			array(
				'capability' => 'edit_posts',
				'number'     => 1,
				'orderby'    => 'ID',
				'order'      => 'ASC',
			)
		);

		if ( ! empty( $users ) ) {
			return $users[0]->ID;
		}

		// Ultimate fallback: Current user
		return get_current_user_id();
	}

	/**
	 * Check if user ID is a valid author
	 *
	 * @param int $user_id User ID
	 * @return bool True if valid author
	 */
	private function is_valid_author( $user_id ) {
		if ( ! $user_id ) {
			return false;
		}

		$user = get_user_by( 'id', intval( $user_id ) );

		if ( ! $user ) {
			return false;
		}

		// Check if user can create posts (is an author/editor/admin)
		return user_can( $user, 'edit_posts' );
	}
}
