<?php

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

class AIEO_Admin_Color {

	
	public static function enqueue() {
		wp_enqueue_style( 'wp-color-picker' );
		wp_enqueue_script( 'wp-color-picker' );

		$ver = defined( 'AIEO_VERSION' ) ? AIEO_VERSION : '1.0';
		$uri = defined( 'AIEO_URI' ) ? AIEO_URI : plugin_dir_url( dirname( __FILE__ ) . '/../ai-eshop-optimizer.php' );

		wp_enqueue_script( 'aieo-color-picker', $uri . 'assets/js/aieo-color-picker.js', array( 'jquery', 'wp-color-picker' ), $ver, true );
		wp_enqueue_style( 'aieo-color-picker', $uri . 'assets/css/aieo-color-picker.css', array( 'wp-color-picker' ), $ver );
	}

	
	public static function sanitize( $val ) {
		$val = trim( (string) $val );
		if ( '' === $val ) {
			return '';
		}
		if ( 'transparent' === strtolower( $val ) ) {
			return 'transparent';
		}
		
		if ( preg_match( '/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/', $val ) ) {
			return $val;
		}
		
		
		if ( preg_match( '/^rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(?:,\s*(\d+(?:\.\d+)?|\.\d+)\s*)?\)$/i', $val, $m ) ) {
			$r = min( 255, (int) $m[1] );
			$g = min( 255, (int) $m[2] );
			$b = min( 255, (int) $m[3] );
			if ( isset( $m[4] ) && '' !== $m[4] ) {
				$a = (float) $m[4];
				if ( $a < 0 ) { $a = 0; }
				if ( $a > 1 ) { $a = 1; }
				return 'rgba(' . $r . ',' . $g . ',' . $b . ',' . rtrim( rtrim( sprintf( '%.2f', $a ), '0' ), '.' ) . ')';
			}
			return 'rgb(' . $r . ',' . $g . ',' . $b . ')';
		}
		return '';
	}
}
