<?php
/**
 * Blog Over Alpha Color Control
 * 
 * Color picker with alpha/opacity support for Customizer
 *
 * @package Blog_Over
 */

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

if (!class_exists('WP_Customize_Control')) {
    return;
}

/**
 * Alpha Color Picker Control
 */
class blog_over_Alpha_Color_Control extends WP_Customize_Control
{
    /**
     * Control type
     *
     * @var string
     */
    public $type = 'blog-over-alpha-color';

    /**
     * Add support for palettes
     *
     * @var bool
     */
    public $show_palette = true;

    /**
     * Default palette colors
     *
     * @var array
     */
    public $palette = array(
        '#000000',
        '#ffffff',
        '#f44336',
        '#e91e63',
        '#9c27b0',
        '#673ab7',
        '#3f51b5',
        '#2196f3',
    );

    /**
     * Enqueue control styles and scripts
     */
    public function enqueue()
    {
        wp_enqueue_style('wp-color-picker');
        wp_enqueue_script('wp-color-picker');

        wp_enqueue_style(
            'blog-over-customizer-controls',
            get_template_directory_uri() . '/assets/css/customizer-controls.css',
            array('wp-color-picker'),
            Blog_Over_VERSION
        );

        wp_enqueue_script(
            'blog-over-alpha-color-picker',
            get_template_directory_uri() . '/assets/js/alpha-color-picker.js',
            array('jquery', 'wp-color-picker'),
            Blog_Over_VERSION,
            true
        );
    }

    /**
     * Render the control content
     */
    public function render_content()
    {
        ?>
        <div class="blog-over-alpha-color-wrapper">
            <?php if (!empty($this->label)): ?>
                <span class="customize-control-title"><?php echo esc_html($this->label); ?></span>
            <?php endif; ?>

            <?php if (!empty($this->description)): ?>
                <span class="description customize-control-description"><?php echo esc_html($this->description); ?></span>
            <?php endif; ?>

            <div class="blog-over-alpha-color-picker">
                <input type="text" class="blog-over-alpha-color-input" data-alpha-enabled="true"
                    data-default-color="<?php echo esc_attr($this->setting->default); ?>"
                    value="<?php echo esc_attr($this->value()); ?>" <?php $this->link(); ?> />
            </div>
        </div>
        <?php
    }
}

/**
 * Sanitize RGBA color values
 *
 * @param string $color Color value
 * @return string Sanitized color
 */
function blog_over_sanitize_alpha_color($color)
{
    if (empty($color)) {
        return '';
    }

    // Check for hex color
    if (preg_match('/^#([A-Fa-f0-9]{3}){1,2}$/', $color)) {
        return $color;
    }

    // Check for rgba
    if (preg_match('/^rgba?\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})(,\s*((0|1)(\.\d+)?))?\)$/', $color)) {
        return $color;
    }

    return '';
}
