<?php
/**
 * Checks if custom breakpoints are enabled.
 * @return bool
 */
if (!function_exists('pac_drh_is_custom_breakpoints_enabled')):
    function pac_drh_is_custom_breakpoints_enabled(): bool
    {
        $is_custom_breakpoint_enabled = false;
        $options = get_option('et_divi');
        if (!empty($options['pac_drh_custom_breakpoint_1'])
            || !empty($options['pac_drh_custom_breakpoint_2'])) {
            $is_custom_breakpoint_enabled = true;
        }

        return $is_custom_breakpoint_enabled;
    }
endif;
/**
 * Filters and modifies WordPress stylesheets, handling custom file naming and caching.
 * @return void
 */
if (!function_exists('pac_drh_filter_wp_styles')):
    function pac_drh_filter_wp_styles()
    {
        if (!pac_drh_is_custom_breakpoints_enabled()) {
            return;
        }
        global $wp_filesystem;
        $wp_styles = wp_styles();
        $tpl_dir_uri = trailingslashit(get_template_directory_uri());
        $tpl_dir = trailingslashit(get_template_directory());
        $stylesheets_to_remove = [
            $tpl_dir_uri.'style.css' => 'style.css',
            $tpl_dir_uri.'style.dev.css' => 'style.dev.css',
            $tpl_dir_uri.'style-cpt.css' => 'style-cpt.css',
            $tpl_dir_uri.'style.min.css' => 'style.min.css',
            $tpl_dir_uri.'style-static.min.css' => 'style-static.min.css',
            $tpl_dir_uri.'style-static-rtl.min.css' => 'style-static-rtl.min.css',
            $tpl_dir_uri.'style-static-cpt.min.css' => 'style-static-cpt.min.css',
            $tpl_dir_uri.'style-static-cpt-rtl.min.css' => 'style-static-cpt-rtl.min.css',
            $tpl_dir_uri.'style-rtl.min.css' => 'style-rtl.min.css',
            $tpl_dir_uri.'style-cpt.min.css' => 'style-cpt.min.css',
            $tpl_dir_uri.'style-cpt-rtl.min.css' => 'style-cpt-rtl.min.css'
        ];
        $registered_styles = array_intersect_key($wp_styles->registered, array_combine($wp_styles->queue, $wp_styles->queue));
        foreach ($registered_styles as $handle => $style) {
            if (in_array($handle, ['divi-style-inline', 'divi-style-parent-inline'], true)) {
                $original_filename = 'style'.(et_builder_should_wrap_styles() ? '-cpt' : '').(is_rtl() ? '-rtl' : '').'.min.css';
                $new_filename = pac_drh_get_filename($original_filename);
                $css_path = $tpl_dir.$new_filename;
                if (!$wp_filesystem->exists($css_path)) {
                    pac_drh_generate_css($original_filename);
                }
                //$style->extra['after'][0] = file_get_contents($css_path);
                $style->extra['after'][0] = $wp_filesystem->get_contents($css_path);
                break;

            }
            if (isset($stylesheets_to_remove[$style->src])) {
                $original_filename = $stylesheets_to_remove[$style->src];
                $new_filename = pac_drh_get_filename($original_filename);
                $style->src = path_join($tpl_dir_uri, $new_filename);
                $css_path = $tpl_dir.$new_filename;
                if (!$wp_filesystem->exists($css_path)) {
                    pac_drh_generate_css($original_filename);
                }
                $style->ver = filemtime($css_path);
                break;
            }
        }
    }

    add_action('wp_print_styles', 'pac_drh_filter_wp_styles', 1);
endif;
/**
 * Filters Divi dynamic CSS, renaming files and regenerating styles with custom breakpoint settings.
 * @return void
 */
if (!function_exists('pac_drh_filter_dynamic_assets')):
    function pac_drh_filter_dynamic_assets()
    {
        if (!pac_drh_is_custom_breakpoints_enabled()) {
            return;
        }
        if (!class_exists('ET_Dynamic_Assets')) {
            return;
        }
        $dynamic_assets = ET_Dynamic_Assets::init();
        if ($dynamic_assets) {
            $files = $dynamic_assets->get_dynamic_assets_files();
            if ($files) {
                $cache_dir = et_core_cache_dir();
                foreach ($files as $file) {
                    if (substr($file, -7, 3) !== '-ds' && strpos($file, $cache_dir->url) === 0) {
                        //if (!isset($real_cache_dir_path)) {
                        $wp_content_dir = realpath(WP_CONTENT_DIR);
                        $real_cache_dir_path = realpath($cache_dir->path);
                        if (strpos($real_cache_dir_path, $wp_content_dir) !== 0) {
                            return;
                        }
                        $relative_cache_dir_path = '../..'.substr($real_cache_dir_path, strlen($wp_content_dir));
                        $file = substr($file, strlen($cache_dir->url));
                        pac_drh_generate_css($relative_cache_dir_path.$file, $real_cache_dir_path.substr($file, 0, -4).'-ds'.substr($file, -4), false);
                        wp_delete_file($real_cache_dir_path.$file);
                        //}
                    }
                }
            }
        }
    }

    add_action('wp_enqueue_scripts', 'pac_drh_filter_dynamic_assets', 1);
endif;
/**
 * Generates a custom CSS file with optional breakpoints and appends additional CSS if required.
 *
 * @param string $original_filename
 * @param string|null $new_filename
 * @param bool $include_switch_css
 *
 * @return void
 */
if (!function_exists('pac_drh_generate_css')):
    function pac_drh_generate_css($original_filename, $new_filename = null, $include_switch_css = true)
    {
        global $wp_filesystem;
        $original_filename = trailingslashit(get_template_directory()).$original_filename;
        if (!$new_filename) {
            $new_filename = pac_drh_get_filename($original_filename);
        }
        //$css = file_get_contents($original_filename);
        $css = $wp_filesystem->get_contents($original_filename);
        $options = get_option('et_divi');
        $from = [];
        $to = [];
        $breakpoints = [981, 768, 1406, 1099, 981, 801, 480, 381];
        foreach ($breakpoints as $breakpoint_index => $breakpoint) {
            $key = 'pac_drh_custom_breakpoint_'.($breakpoint_index + 1);
            if (!empty($options[$key]) && is_numeric($options[$key])) {
                $option_value = $options[$key];
                $from[] = '(min-width:'.$breakpoint.'px)';
                $to[] = '(min-width:'.$option_value.'px)';
                $from[] = '(min-width: '.$breakpoint.'px)';
                $to[] = '(min-width: '.$option_value.'px)';
                $from[] = '(max-width:'.($breakpoint - 1).'px)';
                $to[] = '(max-width:'.($option_value - 1).'px)';
                $from[] = '(max-width: '.($breakpoint - 1).'px)';
                $to[] = '(max-width: '.($option_value - 1).'px)';
            }
        }
        if (!empty($from)) {
            $css = str_ireplace($from, $to, $css);
        }
        if ($include_switch_css) {
            $switch_css_file = __DIR__.'/style.css';
            if ($wp_filesystem->exists($switch_css_file)) {
                //$css .= "\n\n".file_get_contents($switch_css_file);
                $css .= "\n\n".$wp_filesystem->get_contents($switch_css_file);
            }

        }
        $css = '/*! The following theme stylesheet was modified by the Divi Responsive Helper - '.current_time('r').' */'."\n".$css;
        //file_put_contents($new_filename, $css);
        $wp_filesystem->put_contents($new_filename, $css);
    }
endif;
/**
 * Deletes plugin-specific CSS files and clears cache on option update.
 *
 * @param array $previous_options
 * @param array $current_options
 */
if (!function_exists('pac_drh_on_update_options')):
    function pac_drh_on_update_options($previous_options, $current_options)
    {
        $tpl_dir = get_template_directory();
        $plugin_version = PAC_DRH_PLUGIN_VERSION;
        $files = [
            'style',
            'style.dev',
            'style-cpt',
            'style.min',
            'style-static.min',
            'style-static-rtl.min',
            'style-static-cpt.min',
            'style-static-cpt-rtl.min',
            'style-rtl.min',
            'style-cpt.min',
            'style-cpt-rtl.min'
        ];
        foreach ($files as $file) {
            $file_path = path_join($tpl_dir, $file.'.pac-drh-'.$plugin_version.'.css');
            if (file_exists($file_path)) {
                wp_delete_file($file_path);
            }
        }
        // Delete Cache Dir
        $cache_dir = et_core_cache_dir();
        $cache_dir->wpfs->rmdir($cache_dir->path, true);

    }

    add_action('update_option_et_divi', 'pac_drh_on_update_options', 10, 2);
    add_action('et_epanel_update_option', 'pac_drh_on_update_options', 10, 2);
endif;
/**
 * Modifies a filename by adding a version suffix before the extension.
 *
 * @param string $original_filename
 *
 * @return string
 */
if (!function_exists('pac_drh_get_filename')):
    function pac_drh_get_filename($original_filename): string
    {
        return substr($original_filename, 0, -4).'.pac-drh-'.PAC_DRH_PLUGIN_VERSION.substr($original_filename, -4);

    }
endif;


