<?php

namespace EasyCriticalCSS;

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

class Individual_Settings {
	public static function get_settings_schema() {
		$global_settings = Admin_Settings::get_settings_schema();
		$labels          = [
			'critical_css_mode'      => ( Settings::get_global_mode() === 'auto' )
				? __( 'Auto', 'easy-critical-css' )
				: __( 'Manual', 'easy-critical-css' ),
			'secondary_css_behavior' => $global_settings['secondary_css_behavior']['options'][ Settings::get_global_secondary_behavior() ],
		];

		return [
			'activate_critical_css'      => [
				'label'   => __( 'Activate Critical CSS', 'easy-critical-css' ),
				'type'    => 'checkbox',
				'default' => true,
				'desc'    => __( 'Activate or pause Critical CSS for this page only.', 'easy-critical-css' ),
			],
			'critical_css_mode'          => [
				'label'   => __( 'Critical CSS Mode', 'easy-critical-css' ),
				'type'    => 'select',
				'options' => [
					// translators: %s is the currently selected setting.
					'default' => sprintf( __( 'Use global setting (%s)', 'easy-critical-css' ), $labels['critical_css_mode'] ),
					'auto'    => __( 'Auto (Requires API)', 'easy-critical-css' ),
					'manual'  => __( 'Manual', 'easy-critical-css' ),
				],
				'default' => 'default',
				'desc'    => __( 'Select how Critical CSS is generated for this page. Auto mode requires an API key, while Manual mode allows you to enter your own Critical CSS for this page.', 'easy-critical-css' ),
				'visible' => [
					'activate_critical_css' => true,
				],
			],
			'secondary_css_behavior'     => [
				'label'   => __( 'Secondary CSS Behavior', 'easy-critical-css' ),
				'type'    => 'select',
				'options' => [
					// translators: %s is the currently selected setting.
					'default'   => sprintf( __( 'Use global setting (%s)', 'easy-critical-css' ), $labels['secondary_css_behavior'] ),
					'secondary' => __( 'Strip unused CSS Rules', 'easy-critical-css' ),
					'remaining' => __( 'Keep all remaining CSS rules', 'easy-critical-css' ),
				],
				'default' => 'default',
				'desc'    => __( 'Choose what to do with the remaining CSS after extracting Critical CSS. Stripping unused rules provides the best performance.', 'easy-critical-css' ),
				'visible' => [
					'activate_critical_css' => true,
					'critical_css_mode'     => 'auto',
				],
			],
			'critical_css'               => [
				'label'   => [
					'auto'   => __( 'Default Critical CSS', 'easy-critical-css' ),
					'manual' => __( 'Manual Critical CSS', 'easy-critical-css' ),
				],
				'type'    => 'textarea',
				'default' => '',
				'desc'    => [
					'auto'   => __( 'This CSS is used as a fallback when no generated Critical CSS is available.', 'easy-critical-css' ),
					'manual' => __( 'This CSS will always be used when Manual mode is selected. Keep blank to use global Default Critical CSS setting.', 'easy-critical-css' ),
				],
				'visible' => [
					'activate_critical_css' => true,
				],
			],
			'manual_secondary_css'       => [
				'label'   => __( 'Manual Secondary CSS', 'easy-critical-css' ),
				'type'    => 'textarea',
				'default' => '',
				'desc'    => __( 'Enter the secondary CSS for this page. This CSS will load as a single file instead of all other CSS files on the page. There must be Manual Critical CSS for this setting to apply.', 'easy-critical-css' ),
				'visible' => [
					'activate_critical_css' => true,
					'critical_css_mode'     => 'manual',
				],
			],
			'forced_critical_selectors'  => [
				'label'   => __( 'Forced Critical CSS Selectors', 'easy-critical-css' ),
				'type'    => 'textarea',
				'default' => '',
				'desc'    => __( 'One selector per line. Example: .my-class or #my-id span. You can use regex patterns by placing them between slashes. Example: /.my-plugin-id-\d+/ (matches .my-plugin-id-1, .my-plugin-id-42, etc.) Keep blank to use global setting.', 'easy-critical-css' ),
				'visible' => [
					'activate_critical_css' => true,
					'critical_css_mode'     => 'auto',
				],
			],
			'forced_secondary_selectors' => [
				'label'   => __( 'Forced Secondary CSS Selectors', 'easy-critical-css' ),
				'type'    => 'textarea',
				'default' => '',
				'desc'    => __( 'One selector per line. Example: .my-class or #my-id span. You can use regex patterns by placing them between slashes. Example: /.my-plugin-id-\d+/ (matches .my-plugin-id-1, .my-plugin-id-42, etc.) Keep blank to use global setting.', 'easy-critical-css' ),
				'visible' => [
					'activate_critical_css'  => true,
					'critical_css_mode'      => 'auto',
					'secondary_css_behavior' => 'secondary',
				],
			],
			'excluded_css_files'         => [
				'label'   => [
					'auto'   => __( 'Excluded CSS Files', 'easy-critical-css' ),
					'manual' => __( 'Always Loaded CSS Files', 'easy-critical-css' ),
				],
				'type'    => 'textarea',
				'default' => '',
				'desc'    => [
					'auto'   => __( 'Enter one CSS file URL or partial match per line. Any matching file will be excluded from Critical CSS generation on this post. Excluded files will always load on the page. Keep blank to use global setting.', 'easy-critical-css' ),
					'manual' => __( 'Enter one CSS file URL or partial match per line. These files will always be loaded on the page. Keep blank to use global setting.', 'easy-critical-css' ),
				],
				'visible' => [
					'activate_critical_css' => true,
				],
			],
		];
	}

	public static function get_settings( $identifier ) {
		$generated = Critical_CSS::get_generated_css( $identifier );

		return ( ! empty( $generated['settings'] ) ) ? json_decode( $generated['settings'], true ) : [];
	}

	public static function save_settings( $identifier, $new_settings ) {
		$generated         = Critical_CSS::get_generated_css( $identifier );
		$existing_settings = ( ! empty( $generated['settings'] ) ) ? json_decode( $generated['settings'], true ) : [];
		$merged_settings   = array_merge( $existing_settings, $new_settings );

		$data = [ 'settings' => wp_json_encode( $merged_settings, JSON_UNESCAPED_UNICODE ) ];

		// If we have a post ID, save it.
		if ( is_numeric( $identifier ) ) {
			$data['post_id'] = (int) $identifier;
		} elseif ( preg_match( '/^[a-f0-9]{32}$/', $identifier ) ) {
			$data['url_hash'] = esc_attr( $identifier );
		} else {
			$data['page_url'] = esc_url_raw( $identifier );
		}

		// Make sure we have a good hash.
		$url_hash = ( ! empty( $generated['url_hash'] ) ) ? $generated['url_hash'] : Helpers::get_url_hash( $identifier );
		if ( ! empty( $url_hash ) ) {
			$data['url_hash'] = $url_hash;
		}

		Database::upsert_row( $data );
	}
}
