<?php

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

final class IComm_SM_Settings {

	public const OPTION_KEY = 'icomm_sm_settings_v1';

	/**
	 * @return array<string, mixed>
	 */
	public static function defaults(): array {
		return [
			'gsc_connected' => 0,
			'gsc_property' => '',
			'gsc_last_sync_at' => 0,
			'gsc_last_error' => '',
			'ga4_connected' => 0,
			'ga4_property_id' => '',
			'ga4_last_sync_at' => 0,
			'ga4_last_error' => '',
			'watch_keywords' => [],
			'client_report_email' => '',
			'client_report_enabled' => 0,
			'client_report_day' => 1,
			'agency_name' => '',
			'agency_logo_url' => '',
			'last_manual_sync_at' => 0,
			'alerts_enabled' => 0,
			'alerts_send_admin' => 1,
			'alerts_send_client' => 0,
			'alerts_drop_pct' => 30,
			'alerts_period_days' => 7,
			'alerts_min_clicks' => 20,
			'index_watch_enabled' => 0,
			'index_watch_max' => 5,
			'index_watch_urls' => [],
			'index_watch_last_skip' => 0,
			'inspect_saved_urls' => [],
			'inspect_limit' => 10,
			/** @var array<int, array<string,mixed>> Marked opportunity fixes for before/after tracking. */
			'opp_done' => [],
			/** Last niche / topic researched on Opportunities screen. */
			'last_niche_topic' => '',
		];
	}

	/**
	 * @return array<string, mixed>
	 */
	public static function get(): array {
		$raw = get_option(self::OPTION_KEY, []);
		if (!is_array($raw)) {
			$raw = [];
		}
		$s = array_merge(self::defaults(), $raw);
		if (!is_array($s['watch_keywords'])) {
			$s['watch_keywords'] = [];
		}
		if (!is_array($s['index_watch_urls'])) {
			$s['index_watch_urls'] = [];
		}
		if (!is_array($s['inspect_saved_urls'])) {
			$s['inspect_saved_urls'] = [];
		}
		if (!is_array($s['opp_done'])) {
			$s['opp_done'] = [];
		}
		$s['last_niche_topic'] = sanitize_text_field((string) ($s['last_niche_topic'] ?? ''));
		$s['inspect_limit'] = max(1, min(30, (int) ($s['inspect_limit'] ?? 10)));
		return $s;
	}

	/**
	 * @param array<string, mixed> $settings
	 */
	public static function save(array $settings): void {
		$merged = array_merge(self::defaults(), $settings);
		$kw = $merged['watch_keywords'];
		if (!is_array($kw)) {
			$kw = [];
		}
		$merged['watch_keywords'] = array_values(array_filter(array_map('strval', $kw)));
		update_option(self::OPTION_KEY, $merged, false);
	}

	public static function is_gsc_ready(): bool {
		$s = self::get();
		return !empty($s['gsc_connected']) && trim((string) $s['gsc_property']) !== '';
	}

	public static function is_ga4_ready(): bool {
		$s = self::get();
		return !empty($s['ga4_connected']) && trim((string) $s['ga4_property_id']) !== '';
	}
}
