<?php
/**
 * WeCodeArt Framework.
 *
 * WARNING: This file is part of the core WeCodeArt Framework. DO NOT edit this file under any circumstances.
 * Please do all modifications in the form of a child theme.
 *
 * @package 	WeCodeArt Framework
 * @subpackage 	Support\Styles\Property\FontFamily
 * @copyright   Copyright (c) 2025, WeCodeArt Framework
 * @since 		6.6.6
 * @version		6.6.6
 */

namespace WeCodeArt\Support\Styles\Sanitize\Property;

defined( 'ABSPATH' ) || exit;

use WeCodeArt\Support\Styles\Sanitize\Property;

/**
 * Output for CSS properties.
 */
class Color extends Property {
	/**
	 * Modifies the value.
	 *
	 * @access protected
	 */
	protected function process_value() {
		$processed = ''; 

		if ( $this->value ) {
			// Is CSS Variable or RGB
            $is_var = ( strpos( $this->value, 'var(' ) !== false || strpos( $this->value, 'rgb(' ) !== false );
        
            if ( $is_var ) {
                $processed = filter_var( $this->value, FILTER_SANITIZE_STRING );
                
                $this->value = $processed;

                return;
            }
        
            // Is this an rgba color or a hex?
            $mode = ( strpos( $this->value, 'rgba(' ) !== false ) ? 'rgba' : 'hex';
        
            if ( 'rgba' === $mode ) {
                $processed = $this->as_rgba( $this->value );
            } else {
                $processed = $this->as_hex( $this->value );
            }
		}
		
		$this->value = $processed;
	}

    /**
	 * Sanitize rgba color.
	 *
	 * @since   5.0.0
	 * @param 	string $value Color in rgba format.
	 *
	 * @return 	string
	 */
	protected function as_rgba( string $value = '' ): string {
		$red   = 'rgba(0,0,0,0)';
		$green = 'rgba(0,0,0,0)';
		$blue  = 'rgba(0,0,0,0)';
		$alpha = 'rgba(0,0,0,0)'; // If empty or an array return transparent
		
		if ( empty( $value ) || is_array( $value ) ) {
			return '';
		}

		// By now we know the string is formatted as an rgba color so we need to further sanitize it.
		$value = str_replace( ' ', '', $value );
		sscanf( $value, 'rgba(%d,%d,%d,%f)', $red, $green, $blue, $alpha );

		return 'rgba(' . $red . ',' . $green . ',' . $blue . ',' . $alpha . ')';
	}
	
	/**
	 * Sanitize hex color.
	 *
	 * @since   5.0.0
	 * @param 	string $value Color in hex format.
	 *
	 * @return 	string
	 */
	protected function as_hex( string $value = '' ): string {
		return sanitize_hex_color( $value );
	}
}