<?php
/**
 * Settings helper class.
 *
 * @package Pendid_AI_Studio
 */

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

/**
 * Manages plugin settings storage.
 */
class Pendid_AI_Studio_Settings {

	/**
	 * Option name used for plugin settings.
	 *
	 * @var string
	 */
	const OPTION_NAME = 'pendid_ai_studio_settings';

	/**
	 * Returns settings with defaults applied.
	 *
	 * @return array<string, string>
	 */
	public function get_settings() {
		$settings = get_option( self::OPTION_NAME, array() );

		if ( ! is_array( $settings ) ) {
			$settings = array();
		}

		return array_merge( $this->get_default_settings(), $this->sanitize_settings( $settings ) );
	}

	/**
	 * Returns the stored access token.
	 *
	 * @return string
	 */
	public function get_access_token() {
		$settings = $this->get_settings();

		return $settings['access_token'];
	}

	/**
	 * Determines whether the plugin has stored connection data.
	 *
	 * @return bool
	 */
	public function is_connected() {
		return '' !== $this->get_access_token();
	}

	/**
	 * Updates plugin settings.
	 *
	 * @param array<string, mixed> $settings Settings to store.
	 * @return bool
	 */
	public function update_settings( $settings ) {
		if ( ! is_array( $settings ) ) {
			$settings = array();
		}

		$settings = array_merge( $this->get_settings(), $this->sanitize_settings( $settings ) );

		return update_option( self::OPTION_NAME, $settings, false );
	}

	/**
	 * Clears stored connection data.
	 *
	 * @return bool
	 */
	public function disconnect() {
		return update_option( self::OPTION_NAME, $this->get_default_settings(), false );
	}

	/**
	 * Returns default settings.
	 *
	 * @return array<string, string>
	 */
	private function get_default_settings() {
		return array(
			'access_token'       => '',
			'account_email'      => '',
			'account_plan'       => '',
			'account_plan_title' => '',
			'connected_at'       => '',
		);
	}

	/**
	 * Sanitizes supported settings.
	 *
	 * @param array<string, mixed> $settings Settings to sanitize.
	 * @return array<string, string>
	 */
	private function sanitize_settings( $settings ) {
		$sanitized = array();
		$defaults  = $this->get_default_settings();

		foreach ( $defaults as $key => $default_value ) {
			if ( ! array_key_exists( $key, $settings ) ) {
				continue;
			}

			if ( is_scalar( $settings[ $key ] ) ) {
				$value = (string) $settings[ $key ];
			} else {
				$value = $default_value;
			}

			if ( 'account_email' === $key ) {
				$sanitized[ $key ] = sanitize_email( $value );
				continue;
			}

			$sanitized[ $key ] = sanitize_text_field( $value );
		}

		return $sanitized;
	}
}
