<?php
/**
 * Dynamic Style Generator
 *
 * Generates dynamic CSS for donation forms and progress bars based on backend settings.
 *
 * @package DonorCore\Frontend
 */

namespace DonorCore\Frontend;

defined( 'ABSPATH' ) || exit;

/**
 * Style Generator Class
 */
class Style_Generator {

	/**
	 * Initialize the style generator.
	 */
	public function __construct() {
		add_action( 'wp_enqueue_scripts', array( $this, 'generate_frontend_styles' ), 100 );
		add_action( 'enqueue_block_editor_assets', array( $this, 'generate_editor_styles' ), 100 );
	}

	/**
	 * Get default style settings.
	 *
	 * @return array
	 */
	public static function get_defaults() {
		return array(
			// Typography
			'donation_form_font_family'         => '-apple-system, BlinkMacSystemFont, \'Segoe UI\', Roboto, sans-serif',
			'donation_form_heading_size'        => '18',
			'donation_form_body_size'           => '18',
			'donation_form_button_font_size'    => '18',
			'donation_form_font_weight_heading' => '700',
			'donation_form_font_weight_body'    => '600',
			'donation_form_font_weight_button'  => '700',
			'donation_form_line_height'         => '1.6',

			// Colors
			'donation_form_primary_color'       => '#0073aa',
			'donation_form_secondary_color'     => '#005177',          
			'donation_form_bg_color'            => '#ffffff',
			'donation_form_text_color'          => '#2c3338',
			'donation_form_label_color'         => '#2c3338',
			'donation_form_border_color'        => '#dae1e7',
			'donation_form_input_bg_color'      => '#fcfcfc',
			'donation_form_input_focus_color'   => '#0073aa',

			// Spacing & Layout
			'donation_form_container_padding'   => '30',
			'donation_form_container_margin'    => '30',
			'donation_form_element_gap'         => '20',
			'donation_form_max_width'           => '600',

			// Borders & Shadows
			'donation_form_border_radius'       => '12',
			'donation_form_button_radius'       => '8',
			'donation_form_input_radius'        => '8',
			'donation_form_border_width'        => '1',
			'donation_form_shadow'              => 'medium', // none, light, medium, strong

			// Buttons
			'donation_form_button_padding_y'    => '18',
			'donation_form_button_padding_x'    => '16',
			'donation_form_button_hover_effect' => 'lift', // lift, darken, glow, none

			// Inputs & Amount Buttons
			'donation_form_input_padding'       => '12',
			'donation_form_amount_btn_padding'  => '12',
			'donation_form_amount_cols'         => '4',

			// Progress Bar Settings
			'progress_bar_primary_color'        => '#0073aa',
			'progress_bar_fill_color'           => '#0073aa',
			'progress_bar_bg_color'             => '#ffffff',
			'progress_bar_text_color'           => '#2c3338',
			'progress_bar_font_family'          => '-apple-system, BlinkMacSystemFont, \'Segoe UI\', Roboto, sans-serif',
			'progress_bar_heading_size'         => '20',
			'progress_bar_body_size'            => '14',
			'progress_bar_border_radius'        => '12',
			'progress_bar_height'               => '40',
			'progress_bar_container_padding'    => '30',
			'progress_bar_container_margin'     => '30',
			'progress_bar_max_width'            => '600',
			'progress_bar_shadow'               => 'medium',

			// Progress Bar Typography Weights
			'progress_bar_heading_font_weight'  => '600',
			'progress_bar_amount_font_weight'   => '600',
			'progress_bar_label_font_weight'    => '500',
			'progress_bar_percentage_font_weight' => '800',
			
			// Progress Bar Additional Typography
			'progress_bar_amount_font_size'     => '16',
			
			// Progress Bar Additional Colors
			'progress_bar_track_bg_color'       => '#eff1f3',
			'progress_bar_percentage_text_color' => '#ffffff',
		);
	}

	/**
	 * Get all settings with defaults.
	 *
	 * @return array
	 */
	public function get_settings() {
		$defaults = self::get_defaults();
		$saved    = array();

		// Fetch all settings with donorcore_ prefix and sanitize each option
		foreach ( array_keys( $defaults ) as $key ) {
			$raw_value     = get_option( 'donorcore_' . $key, $defaults[ $key ] );
			$saved[ $key ] = $this->sanitize_setting_value( $key, $raw_value, $defaults[ $key ] );
		}

		return array_merge( $defaults, $saved );
	}

	/**
	 * Sanitize individual setting values based on type/context.
	 *
	 * @param string $key     Setting key name.
	 * @param mixed  $value   Setting value.
	 * @param mixed  $default Default fallback value.
	 * @return string|int|float
	 */
	private function sanitize_setting_value( $key, $value, $default ) {
		// Colors
		if ( strpos( $key, 'color' ) !== false || strpos( $key, 'fill' ) !== false ) {
			if ( is_string( $value ) && ! empty( $value ) ) {
				$val = trim( $value );
				if ( preg_match( '/^#[0-9A-Fa-f]{3,8}$/', $val ) || preg_match( '/^rgba?\(/i', $val ) ) {
					return strtolower( $val );
				}
			}
			$sanitized_hex = sanitize_hex_color( $value );
			return $sanitized_hex ? $sanitized_hex : ( sanitize_hex_color( $default ) ?: $default );
		}

		// Font family
		if ( strpos( $key, 'font_family' ) !== false ) {
			if ( empty( $value ) || $value === 'system' ) {
				return '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif';
			}
			return stripslashes( sanitize_text_field( $value ) );
		}

		// Shadows
		if ( strpos( $key, 'shadow' ) !== false ) {
			$allowed = array( 'none', 'light', 'medium', 'strong' );
			return in_array( $value, $allowed, true ) ? $value : $default;
		}

		// Hover effect
		if ( $key === 'donation_form_button_hover_effect' ) {
			$allowed = array( 'lift', 'darken', 'glow', 'none' );
			return in_array( $value, $allowed, true ) ? $value : $default;
		}

		// Line height
		if ( $key === 'donation_form_line_height' ) {
			return floatval( $value ) > 0 ? floatval( $value ) : floatval( $default );
		}

		// Numeric values (sizes, paddings, margins, weights, gaps, radiuses, etc.)
		if ( is_numeric( $value ) ) {
			return absint( $value );
		}

		return sanitize_text_field( (string) $value );
	}

	/**
	 * Get shadow CSS based on intensity.
	 *
	 * @param string $intensity Shadow intensity (none, light, medium, strong).
	 * @return string
	 */
	private function get_shadow_css( $intensity ) {
		switch ( $intensity ) {
			case 'none':
				return 'none';
			case 'light':
				return '0 2px 6px rgba(0, 0, 0, 0.05)';
			case 'strong':
				return '0 6px 20px rgba(0, 0, 0, 0.15)';
			case 'medium':
			default:
				return '0 4px 12px rgba(0, 0, 0, 0.08)';
		}
	}

	/**
	 * Get clean font family CSS string.
	 *
	 * @param string $family Font family setting.
	 * @return string
	 */
	private function get_font_family_css( $family ) {
		if ( $family === 'system' || empty( $family ) ) {
			return '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif';
		}
		$clean = stripslashes( wp_strip_all_tags( $family ) );
		$clean = str_replace( array( '&#039;', '&quot;', '&amp;', '\\' ), array( "'", '"', '&', '' ), $clean );
		return trim( $clean );
	}

	/**
	 * Generate CSS variables from settings.
	 *
	 * @return string
	 */
	private function generate_css_variables() {
		$settings    = $this->get_settings();
		$font_family = $this->get_font_family_css( $settings['donation_form_font_family'] );
		$shadow      = $this->get_shadow_css( $settings['donation_form_shadow'] );

		$css = ":root {\n";
		$css .= "\t/* Typography */\n";
		$css .= "\t--dc-df-font-family: {$font_family};\n";
		$css .= "\t--dc-df-heading-size: " . absint( $settings['donation_form_heading_size'] ) . "px;\n";
		$css .= "\t--dc-df-body-size: " . absint( $settings['donation_form_body_size'] ) . "px;\n";
		$css .= "\t--dc-df-button-font-size: " . absint( $settings['donation_form_button_font_size'] ) . "px;\n";
		$css .= "\t--dc-df-font-weight-heading: " . absint( $settings['donation_form_font_weight_heading'] ) . ";\n";
		$css .= "\t--dc-df-font-weight-body: " . absint( $settings['donation_form_font_weight_body'] ) . ";\n";
		$css .= "\t--dc-df-font-weight-button: " . absint( $settings['donation_form_font_weight_button'] ) . ";\n";
		$css .= "\t--dc-df-line-height: " . floatval( $settings['donation_form_line_height'] ) . ";\n\n";

		$css .= "\t/* Colors */\n";
		$css .= "\t--dc-df-primary: " . sanitize_text_field( $settings['donation_form_primary_color'] ) . ";\n";
		$css .= "\t--dc-df-secondary: " . sanitize_text_field( $settings['donation_form_secondary_color'] ) . ";\n";
		$css .= "\t--dc-df-bg: " . sanitize_text_field( $settings['donation_form_bg_color'] ) . ";\n";
		$css .= "\t--dc-df-text: " . sanitize_text_field( $settings['donation_form_text_color'] ) . ";\n";
		$css .= "\t--dc-df-label: " . sanitize_text_field( $settings['donation_form_label_color'] ) . ";\n";
		$css .= "\t--dc-df-border: " . sanitize_text_field( $settings['donation_form_border_color'] ) . ";\n";
		$css .= "\t--dc-df-input-bg: " . sanitize_text_field( $settings['donation_form_input_bg_color'] ) . ";\n";
		$css .= "\t--dc-df-input-focus: " . sanitize_text_field( $settings['donation_form_input_focus_color'] ) . ";\n\n";

		$css .= "\t/* Spacing & Layout */\n";
		$css .= "\t--dc-df-padding: " . absint( $settings['donation_form_container_padding'] ) . "px;\n";
		$css .= "\t--dc-df-margin: " . absint( $settings['donation_form_container_margin'] ) . "px;\n";
		$css .= "\t--dc-df-gap: " . absint( $settings['donation_form_element_gap'] ) . "px;\n";
		$css .= "\t--dc-df-max-width: " . absint( $settings['donation_form_max_width'] ) . "px;\n\n";

		$css .= "\t/* Borders & Shadows */\n";
		$css .= "\t--dc-df-radius: " . absint( $settings['donation_form_border_radius'] ) . "px;\n";
		$css .= "\t--dc-df-button-radius: " . absint( $settings['donation_form_button_radius'] ) . "px;\n";
		$css .= "\t--dc-df-input-radius: " . absint( $settings['donation_form_input_radius'] ) . "px;\n";
		$css .= "\t--dc-df-border-width: " . absint( $settings['donation_form_border_width'] ) . "px;\n";
		$css .= "\t--dc-df-shadow: {$shadow};\n\n";

		$css .= "\t/* Buttons */\n";
		$css .= "\t--dc-df-button-padding-y: " . absint( $settings['donation_form_button_padding_y'] ) . "px;\n";
		$css .= "\t--dc-df-button-padding-x: " . absint( $settings['donation_form_button_padding_x'] ) . "px;\n\n";

		$css .= "\t/* Inputs & Amount Buttons */\n";
		$css .= "\t--dc-df-input-padding: " . absint( $settings['donation_form_input_padding'] ) . "px;\n";
		$css .= "\t--dc-df-amount-btn-padding: " . absint( $settings['donation_form_amount_btn_padding'] ) . "px;\n";
		$css .= "\t--dc-df-amount-cols: " . absint( $settings['donation_form_amount_cols'] ) . ";\n\n";

		return $css;
	}

	/**
	 * Generate Progress Bar CSS variables from settings.
	 *
	 * @return string
	 */
	private function generate_progress_bar_variables() {
		$settings    = $this->get_settings();
		$font_family = $this->get_font_family_css( $settings['progress_bar_font_family'] );
		$shadow      = $this->get_shadow_css( $settings['progress_bar_shadow'] );

		$css = "\t/* Progress Bar */\n";
		$css .= "\t--dc-pb-primary: " . sanitize_text_field( $settings['progress_bar_primary_color'] ) . ";\n";
		$css .= "\t--dc-pb-fill: " . sanitize_text_field( $settings['progress_bar_fill_color'] ) . ";\n";
		$css .= "\t--dc-pb-bg: " . sanitize_text_field( $settings['progress_bar_bg_color'] ) . ";\n";
		$css .= "\t--dc-pb-text: " . sanitize_text_field( $settings['progress_bar_text_color'] ) . ";\n";
		$css .= "\t--dc-pb-font-family: {$font_family};\n";
		$css .= "\t--dc-pb-heading-size: " . absint( $settings['progress_bar_heading_size'] ) . "px;\n";
		$css .= "\t--dc-pb-body-size: " . absint( $settings['progress_bar_body_size'] ) . "px;\n";
		$css .= "\t--dc-pb-radius: " . absint( $settings['progress_bar_border_radius'] ) . "px;\n";
		$css .= "\t--dc-pb-height: " . absint( $settings['progress_bar_height'] ) . "px;\n";
		$css .= "\t--dc-pb-padding: " . absint( $settings['progress_bar_container_padding'] ) . "px;\n";
		$css .= "\t--dc-pb-margin: " . absint( $settings['progress_bar_container_margin'] ) . "px;\n";
		$css .= "\t--dc-pb-max-width: " . absint( $settings['progress_bar_max_width'] ) . "px;\n";
		$css .= "\t--dc-pb-shadow: {$shadow};\n";
		$css .= "\t--dc-pb-heading-weight: " . absint( $settings['progress_bar_heading_font_weight'] ) . ";\n";
		$css .= "\t--dc-pb-amount-weight: " . absint( $settings['progress_bar_amount_font_weight'] ) . ";\n";
		$css .= "\t--dc-pb-label-weight: " . absint( $settings['progress_bar_label_font_weight'] ) . ";\n";
		$css .= "\t--dc-pb-percentage-weight: " . absint( $settings['progress_bar_percentage_font_weight'] ) . ";\n";
		$css .= "\t--dc-pb-amount-size: " . absint( $settings['progress_bar_amount_font_size'] ) . "px;\n";
		$css .= "\t--dc-pb-track-bg: " . sanitize_text_field( $settings['progress_bar_track_bg_color'] ) . ";\n";
		$css .= "\t--dc-pb-percentage-color: " . sanitize_text_field( $settings['progress_bar_percentage_text_color'] ) . ";\n\n";

		return $css;
	}

	/**
	 * Generate hover effect styles based on setting.
	 *
	 * @return string
	 */
	private function generate_hover_styles() {
		$settings = $this->get_settings();
		$effect   = $settings['donation_form_button_hover_effect'];

		$css = '';

		switch ( $effect ) {
			case 'lift':
				$css .= ".dc-donate-btn:hover,\n";
				$css .= ".dc-amount-btn:hover {\n";
				$css .= "\ttransform: translateY(-2px);\n";
				$css .= "\tbox-shadow: 0 6px 15px rgba(0, 115, 170, 0.3);\n";
				$css .= "}\n";
				break;

			case 'darken':
				$css .= ".dc-donate-btn:hover,\n";
				$css .= ".dc-amount-btn:hover {\n";
				$css .= "\tfilter: brightness(0.9);\n";
				$css .= "}\n";
				break;

			case 'glow':
				$css .= ".dc-donate-btn:hover,\n";
				$css .= ".dc-amount-btn:hover {\n";
				$css .= "\tbox-shadow: 0 0 20px var(--dc-df-primary);\n";
				$css .= "}\n";
				break;

			case 'none':
			default:
				// No hover effect
				break;
		}

		return $css;
	}

	/**
	 * Output styles for frontend.
	 */
	public function generate_frontend_styles() {
		$css  = $this->generate_css_variables();
		$css .= $this->generate_progress_bar_variables();
		$css .= "}\n\n"; // Properly close :root BEFORE adding hover rules
		$css .= $this->generate_hover_styles();

		// Register handle and attach inline style to ensure browser receives CSS
		wp_register_style( 'donor-core-dynamic-styles', false, array(), DONOR_CORE_VERSION );
		wp_enqueue_style( 'donor-core-dynamic-styles' );
		wp_add_inline_style( 'donor-core-dynamic-styles', wp_strip_all_tags( $css ) );
	}

	/**
	 * Output styles for block editor.
	 */
	public function generate_editor_styles() {
		$css  = $this->generate_css_variables();
		$css .= $this->generate_progress_bar_variables();
		$css .= "}\n\n"; // Properly close :root BEFORE adding hover rules
		$css .= $this->generate_hover_styles();

		wp_add_inline_style( 'wp-edit-blocks', wp_strip_all_tags( $css ) );
	}
}
