<?php

// Generate safe path
function endless_addons_safe_path($path){
    $path = str_replace(['//', '\\\\'], ['/', '\\'], $path);

    return str_replace(['/', '\\'], DIRECTORY_SEPARATOR, $path);
}

/**
 * Create a global css file
 */
function endless_addons_create_upload_css_file() {
    // if folder not exists, create new folder
    if (!file_exists(ENDLESS_ADDONS_ASSET_PATH)) {
        wp_mkdir_p(ENDLESS_ADDONS_ASSET_PATH);
    }

    // naming asset file
    $uid = 'endless-addons-demo-style';
    $ext = 'css';
    $file_name = $uid . '.min.' . $ext;

    // output asset string
    $output = '';
    global $config;
    $elements = $config['elements'];
    foreach($elements as $element){
        foreach($element as $widgets){
            if($widgets['status'] == true){
                foreach($widgets['css'] as $files){
                    foreach($files as $css_path){
                        $output .= file_get_contents(endless_addons_safe_path($css_path));
                    }
                }
            }
        }
    }

    // minify css
    $css = preg_replace('/\/\*((?!\*\/).)*\*\//', '', $output);
    $css = preg_replace('/\s{2,}/', ' ', $css);
    $css = preg_replace('/\s*([:;{}])\s*/', '$1', $css);
    $output = preg_replace('/;}/', '}', $css);

    // write to file
    file_put_contents(endless_addons_safe_path(ENDLESS_ADDONS_ASSET_PATH . DIRECTORY_SEPARATOR . $file_name), $output);
}

$actual_link = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
if ( strpos($actual_link, '?page=endless-addons-plugin-options&tab=tab_widgets') != false ){
    endless_addons_create_upload_css_file();
}
