<?php
/**
 * Registers and enqueues responsive media queries CSS styles for Divi theme.
 */
if (!function_exists('pac_drh_media_queries_css')) {
    function pac_drh_media_queries_css()
    {
        $inline_styles = [];
        // Device-specific media queries
        $media_queries = [
            'desktop' => '@media (min-width:981px){%s}',
            'tablet' => '@media (min-width:768px) and (max-width:980px){%s}',
            'phone' => '@media (min-width:300px) and (max-width:767px){%s}',
            'desktop_tablet' => '@media screen and (min-width: 769px){%s}',
            'tablet_phone' => '@media screen and (min-width: 481px) and (max-width: 768px){%s}'
        ];
        foreach ($media_queries as $key => $query) {
            $style = et_get_option("pac_drh_{$key}_media_query");
            if (!empty($style)) {
                $inline_styles[] = sprintf($query, preg_replace('/\s+/', ' ', esc_html($style)));
            }
        }
        // Custom media queries
        foreach (pac_drh_custom_media_queries() as $value) {
            $min_width = et_get_option("pac_drh_cmq_min_$value");
            $max_width = et_get_option("pac_drh_cmq_max_$value");
            $css_code = et_get_option("pac_drh_cmq_css_$value");
            if (!empty($min_width) && !empty($max_width) && !empty($css_code)) {
                $inline_styles[] = sprintf(
                    '@media screen and (min-width: %s) and (max-width: %s){%s}',
                    esc_html($min_width),
                    esc_html($max_width),
                    preg_replace('/\s+/', ' ', esc_html($css_code))
                );
            }
        }
        if (!empty($inline_styles)) {
            wp_register_style('divi-responsive-helper-media-queries', false);
            wp_enqueue_style('divi-responsive-helper-media-queries');
            wp_add_inline_style('divi-responsive-helper-media-queries', implode(' ', array_unique($inline_styles)));
        }
    }

    add_action('wp_enqueue_scripts', 'pac_drh_media_queries_css');
}
