<?php
if ( ! class_exists( 'ReduxFrameworkInstances' ) ) {
	return;
}

if(!function_exists('bixol_hex_to_rgba')){
    function bixol_hex_to_rgba($hex,$opacity = 1) {
        $hex = str_replace("#",null, $hex);
        $color = array();
        if(strlen($hex) == 3) {
            $color['r'] = hexdec(substr($hex,0,1).substr($hex,0,1));
            $color['g'] = hexdec(substr($hex,1,1).substr($hex,1,1));
            $color['b'] = hexdec(substr($hex,2,1).substr($hex,2,1));
            $color['a'] = $opacity;
        }
        else if(strlen($hex) == 6) {
            $color['r'] = hexdec(substr($hex, 0, 2));
            $color['g'] = hexdec(substr($hex, 2, 2));
            $color['b'] = hexdec(substr($hex, 4, 2));
            $color['a'] = $opacity;
        }
        $color = "rgba(".implode(', ', $color).")";
        return $color;
    }
}

class CSS_Generator {
	/**
     * scssc class instance
     *
     * @access protected
     * @var scssc
     */
    protected $scssc = null;

    /**
     * ReduxFramework class instance
     *
     * @access protected
     * @var ReduxFramework
     */
    protected $redux = null;

    /**
     * Debug mode is turn on or not
     *
     * @access protected
     * @var boolean
     */
    protected $dev_mode = true;

    /**
     * opt_name of ReduxFramework
     *
     * @access protected
     * @var string
     */
    protected $opt_name = '';

	/**
	 * Constructor
	 */
	function __construct() {
		$this->opt_name = bixol_get_opt_name();

		if ( empty( $this->opt_name ) ) {
			return;
		}
		$this->dev_mode = bixol_get_opt( 'dev_mode', '0' ) === '1' ? true : false;
		add_filter( 'ct_scssc_on', '__return_true' );
		add_action( 'init', array( $this, 'init' ) );
		add_action( 'wp_enqueue_scripts', array( $this, 'enqueue' ), 20 );
	}

	/**
	 * init hook - 10
	 */
	function init() {
		if ( ! class_exists( 'scssc' ) ) {
			return;
		}

		$this->redux = ReduxFrameworkInstances::get_instance( $this->opt_name );

		if ( empty( $this->redux ) || ! $this->redux instanceof ReduxFramework ) {
			return;
		}
		add_action( 'wp', array( $this, 'generate_with_dev_mode' ) );
		add_action( "redux/options/{$this->opt_name}/saved", function () {
			$this->generate_file_options();
		} );
	}

	function generate_with_dev_mode() {
		if ( $this->dev_mode === true ) {
			$this->generate_file_options();
			$this->generate_file();
		}
	}

	function generate_file_options() {
		$scss_dir = get_template_directory() . '/assets/scss/';
        $this->scssc = new scssc();
        $this->scssc->setImportPaths( $scss_dir );
        $_options = $scss_dir . 'variables.scss';
        $this->scssc->setFormatter( 'scss_formatter' );
        $this->redux->filesystem->execute( 'put_contents', $_options, array(
            'content' => preg_replace( "/(?<=[^\r]|^)\n/", "\r\n", $this->options_output() )
        ) );
	}

	/**
	 * Generate options and css files
	 */
	function generate_file() {
		$scss_dir = get_template_directory() . '/assets/scss/';
		$css_dir  = get_template_directory() . '/assets/css/';

		$this->scssc = new scssc();
		$this->scssc->setImportPaths( $scss_dir );

		$css_file = $css_dir . 'theme.css';

		$this->scssc->setFormatter( 'scss_formatter' );
		$this->redux->filesystem->execute( 'put_contents', $css_file, array(
			'content' => preg_replace( "/(?<=[^\r]|^)\n/", "\r\n", $this->scssc->compile( '@import "theme.scss"' ) )
		) );
	}

	protected function print_scss_opt_colors($variable,$param){
        if(is_array($variable)){
            $k = [];
            $v = [];
            foreach ($variable as $key => $value) {
                $k[] = str_replace('-', '_', $key);
                $v[] = 'var(--'.str_replace(['#',' '], [''],$key).'-color)';
            }
            if($param === 'key'){
                return implode(',', $k);
            }else{
                return implode(',', $v);
            }
            
        } else {
            return $variable;
        }
    }

	/**
	 * Output options to _variables.scss
	 *
	 * @access protected
	 * @return string
	 */
	protected function options_output() {
		$theme_colors                    = bixol_configs('theme_colors');
        $links                           = bixol_configs('link');
		ob_start();

		printf('$bixol_theme_colors_key:(%s);',$this->print_scss_opt_colors($theme_colors,'key'));
        printf('$bixol_theme_colors_val:(%s);',$this->print_scss_opt_colors($theme_colors,'val'));
        // color rgb only
        foreach ($theme_colors as $key => $value) {
            printf('$%1$s_color_hex: %2$s;', str_replace('-', '_', $key), $value['value']); 
        }
        // color
        foreach ($theme_colors as $key => $value) {
            printf('$%1$s_color: %2$s;', str_replace('-', '_', $key), 'var(--'.str_replace(['#',' '], [''],$key).'-color)' );
        }

        // color rgb only
        foreach ($theme_colors as $key => $value) {
            printf('$%1$s_color_hex: %2$s;', str_replace('-', '_', $key), $value['value']); 
        }
        // color
        foreach ($theme_colors as $key => $value) {
            printf('$%1$s_color: %2$s;', str_replace('-', '_', $key), 'var(--'.str_replace(['#',' '], [''],$key).'-color)' );
        }
         
        // link color
        foreach ($links as $key => $value) {
            printf('$link_%1$s: %2$s;', str_replace('-', '_', $key), 'var(--link-'.$key.')');
        }


		/* Font */
		$body_default_font = bixol_get_opt( 'body_default_font', 'Rubik' );
		if ( isset( $body_default_font ) ) {
			echo '
                $body_default_font: ' . esc_attr( $body_default_font ) . ';
            ';
		}

		$heading_default_font = bixol_get_opt( 'heading_default_font', 'Poppins' );
		if ( isset( $heading_default_font ) ) {
			echo '
                $heading_default_font: ' . esc_attr( $heading_default_font ) . ';
            ';
		}

		return ob_get_clean();
	}

	/**
	 * Hooked wp_enqueue_scripts - 20
	 * Make sure that the handle is enqueued from earlier wp_enqueue_scripts hook.
	 */
	function enqueue() {
		$css = $this->inline_css();
		if ( ! empty( $css ) ) {
			wp_add_inline_style( 'bixol-theme', $css );
		}
	}

	/**
	 * Generate inline css based on theme options
	 */
	protected function inline_css() {
		ob_start();

		/* Logo */
		$logo_maxh = bixol_get_opt( 'logo_maxh' );

		if ( ! empty( $logo_maxh['height'] ) && $logo_maxh['height'] != 'px' ) {
			printf( '#ct-header-wrap .ct-header-branding a img { max-height: %s !important; }', esc_attr( $logo_maxh['height'] ) );
		} ?>
        @media screen and (max-width: 1199px) {
		<?php
			$logo_maxh_sm = bixol_get_opt( 'logo_maxh_sm' );
			if ( ! empty( $logo_maxh_sm['height'] ) && $logo_maxh_sm['height'] != 'px' ) {
				printf( '#ct-header-wrap .ct-header-branding a img { max-height: %s !important; }', esc_attr( $logo_maxh_sm['height'] ) );
			} ?>
        }
        <?php /* End Logo */

		/* Menu */ ?>
		@media screen and (min-width: 1200px) {
		<?php  $main_menu_color = bixol_get_opt( 'main_menu_color' );
			if ( ! empty( $main_menu_color['regular'] ) ) {
				printf( '.ct-main-menu > li > a { color: %s !important; }', esc_attr( $main_menu_color['regular'] ) );
			}
			if ( ! empty( $main_menu_color['hover'] ) ) {
				printf( '.ct-main-menu > li > a:hover { color: %s !important; }', esc_attr( $main_menu_color['hover'] ) );
			}
			if ( ! empty( $main_menu_color['active'] ) ) {
				printf( '.ct-main-menu > li.current_page_item > a, .ct-main-menu > li.current-menu-item > a, .ct-main-menu > li.current_page_ancestor > a, .ct-main-menu > li.current-menu-ancestor > a { color: %s !important; }', esc_attr( $main_menu_color['active'] ) );
			}
			$sticky_menu_color = bixol_get_opt( 'sticky_menu_color' );
			if ( ! empty( $sticky_menu_color['regular'] ) ) {
				printf( '#ct-header.h-fixed .ct-main-menu > li > a { color: %s !important; }', esc_attr( $sticky_menu_color['regular'] ) );
			}
			if ( ! empty( $sticky_menu_color['hover'] ) ) {
				printf( '#ct-header.h-fixed .ct-main-menu > li > a:hover { color: %s !important; }', esc_attr( $sticky_menu_color['hover'] ) );
			}
			if ( ! empty( $sticky_menu_color['active'] ) ) {
				printf( '#ct-header.h-fixed .ct-main-menu > li.current_page_item > a, #ct-header.h-fixed .ct-main-menu > li.current-menu-item > a, #ct-header.h-fixed .ct-main-menu > li.current_page_ancestor > a, #ct-header.h-fixed .ct-main-menu > li.current-menu-ancestor > a { color: %s !important; }', esc_attr( $sticky_menu_color['active'] ) );
			}
			$sub_menu_color = bixol_get_opt( 'sub_menu_color' );
			if ( ! empty( $sub_menu_color['regular'] ) ) {
				printf( '#ct-header .ct-main-menu .sub-menu > li > a { color: %s !important; }', esc_attr( $sub_menu_color['regular'] ) );
			}
			if ( ! empty( $sub_menu_color['hover'] ) ) {
				printf( '#ct-header .ct-main-menu .sub-menu > li > a:hover { color: %s !important; }', esc_attr( $sub_menu_color['hover'] ) );
				printf( '#ct-header .ct-main-menu .sub-menu > li > a:before { background-color: %s !important; }', esc_attr( $sub_menu_color['hover'] ) );
			}
			if ( ! empty( $sub_menu_color['active'] ) ) {
				printf( '#ct-header .ct-main-menu .sub-menu > li.current_page_item > a, #ct-header .ct-main-menu .sub-menu > li.current-menu-item > a, #ct-header .ct-main-menu .sub-menu > li.current_page_ancestor > a, #ct-header .ct-main-menu .sub-menu > li.current-menu-ancestor > a { color: %s !important; }', esc_attr( $sub_menu_color['active'] ) );
				printf( '#ct-header .ct-main-menu .sub-menu > li.current_page_item > a:before, #ct-header .ct-main-menu .sub-menu > li.current-menu-item > a:before, #ct-header .ct-main-menu .sub-menu > li.current_page_ancestor > a:before, #ct-header .ct-main-menu .sub-menu > li.current-menu-ancestor > a:before { background-color: %s !important; }', esc_attr( $sub_menu_color['active'] ) );
			}
			$menu_icon_color = bixol_get_opt( 'menu_icon_color' );
			if ( ! empty( $menu_icon_color ) ) {
				printf( '.ct-main-menu .link-icon { color: %s !important; }', esc_attr( $menu_icon_color ) );
			}
			?>
		}
        @media screen and (max-width: 1199px) {
            <?php  $mobile_menu_color = bixol_get_opt( 'mobile_menu_color' );
                if ( ! empty( $mobile_menu_color['regular'] ) ) {
                    printf( 'body .ct-main-menu li a { color: %s !important; }', esc_attr( $mobile_menu_color['regular'] ) );
                }
                if ( ! empty( $mobile_menu_color['hover'] ) ) {
                    printf( 'body .ct-main-menu li a:hover { color: %s !important; }', esc_attr( $mobile_menu_color['hover'] ) );
                }
                if ( ! empty( $mobile_menu_color['active'] ) ) {
                    printf( '.ct-main-menu > li.current_page_item > a, .ct-main-menu > li.current-menu-item > a, .ct-main-menu > li.current_page_ancestor > a, .ct-main-menu > li.current-menu-ancestor > a { color: %s !important; }', esc_attr( $mobile_menu_color['active'] ) );
                }
            ?>
        }
		<?php /* End Menu */

		/* Page Title */
		$ptitle_bg = bixol_get_page_opt( 'ptitle_bg' );
		$custom_pagetitle = bixol_get_page_opt( 'custom_pagetitle', 'themeoption' );
		if ( $custom_pagetitle == 'show' && ! empty( $ptitle_bg['background-image'] ) ) {
			echo 'body .site #pagetitle.page-title {
                background-image: url(' . esc_attr( $ptitle_bg['background-image'] ) . ');
            }';
		}
		if ( $custom_pagetitle == 'show' && ! empty( $ptitle_bg['background-color'] ) ) {
			echo 'body .site #pagetitle.page-title {
                background-color: '. esc_attr( $ptitle_bg['background-color'] ) .';
            }';
		}

		/* Preset */
		$p_primary_color = bixol_get_page_opt( 'p_primary_color' );
		if ( !empty( $p_primary_color ) ) {
            echo '.ct-demo-color, .ct-fancy-box-layout3.style2 .item--icon i, .ct-latest-news1.style2 .item--title:hover,
            #ct-header-wrap .ct-topbar-layout3 .ct-topbar-intro, #ct-header-wrap .ct-topbar-layout3 .ct-topbar-social a:hover,
            #ct-header-wrap.ct-header-layout7 #ct-header .ct-main-menu .sub-menu li:hover > a, #ct-header-wrap.ct-header-layout7 #ct-header .ct-main-menu .sub-menu li.current_page_item > a, #ct-header-wrap.ct-header-layout7 #ct-header .ct-main-menu .sub-menu li.current-menu-item > a, 
            #ct-header-wrap.ct-header-layout7 #ct-header .ct-main-menu .sub-menu li.current_page_ancestor > a,
            .ct-heading .item--title cite, .ct-banner1.style4 .ct-counter-number-suffix, .ct-button-layout1 .btn.btn-label,
            .ct-portfolio-grid2 .item--category, .ct-pricing-layout1.style2 .ct-pricing-features-list i, .ct-text-editor mark,
            .ct-testimonial-carousel1.style2 .item--inner:hover .item-icon {
                color: '. esc_attr( $p_primary_color ) .';
            }';
            echo '.ct-service-grid3 .ct-load-more .btn, .ct-service-grid3 .grid-item-inner:hover .item--icon,
            .ct-pricing-single1 .pricing--icon, .ct-pricing-single1 .pricing--button .btn:hover, .ct-pricing-single1 .pricing--button .btn:focus,
            .ct-pricing-single1.item--highlight::before, .ct-dots-style2 .slick-dots li.slick-active button,
            #ct-header-wrap.ct-header-layout7 #ct-header .ct-main-menu > li > a::before,
            #ct-header-wrap.ct-header-layout7 .ct-main-menu .sub-menu li a::before,
            .revslider-initialised .ct-video-item.ct-style2::before,
            .revslider-initialised .btn.btn-icon-slider1:hover, .revslider-initialised .btn.btn-icon-slider1:focus,
            .ct-contact-form-layout1.style6 .wpcf7-form .wpcf7-submit, .ct-banner1.style4 .ct-banner-holder::before,
            .ct-service-carousel5 .item-readmore a, .ct-service-carousel5 .item-readmore a:hover, .ct-service-carousel5 .item-readmore a:focus,
            .ct-team-carousel2 .item--readmore .btn, .ct-pricing-layout1.style2 .ct-pricing-tab-title .ct-pricing-tab-item.active, 
            .ct-pricing-layout1.style2 .ct-pricing-item-inner.ct-pricing-featured .ct-pricing-price1,
            .ct-contact-form-layout1.style1 .btn.btn-plus .icon-abs, .ct-contact-form-layout1.style1 .btn.btn-plus .ct-align-icon-right, .ct-contact-form-layout1.style1 .btn.btn-plus .ct-align-icon-left,
            .ct-testimonial-carousel1.style2 .slick-dots li.slick-active button {
                background-color: '. esc_attr( $p_primary_color ) .';
            }';
            echo '.ct-pricing-single1 .pricing--button .btn:hover, .ct-pricing-single1 .pricing--button .btn:focus,
            .ct-service-carousel5 .grid-item-inner:hover .item--icon {
                border-color: '. esc_attr( $p_primary_color ) .';
            }';
            echo '.ct-pricing-layout1.style2 .ct-pricing-item-inner.ct-pricing-featured .ct-pricing-price1:after {
                border-color: '. esc_attr( $p_primary_color ) .' transparent transparent;
            }';
            echo '.ct-testimonial-carousel1.style2 .item--inner:hover .item--holder .item--svg .ct-path1 {
                fill: '. esc_attr( $p_primary_color ) .';
            }';
            
            ?>

            @media screen and (min-width: 1200px) { <?php
            	echo '#ct-header-wrap.ct-header-layout6 #ct-header {
	                background-color: '. esc_attr( $p_primary_color ) .';
	            }';
        	?> }

            @media screen and (max-width: 1199px) { <?php
            	
        	?> } <?php
		}
		$p_secondary_color = bixol_get_page_opt( 'p_secondary_color' );
		if ( !empty( $p_secondary_color ) ) {
            echo '#ct-header-wrap.ct-header-layout6 #ct-header .ct-header-button .btn,
            #ct-header-wrap.ct-header-layout6 #ct-header .ct-main-menu > li > a::before,
            .ct-icon1.style3 a:hover, .ct-icon1.style3 a:focus, .ct-fancy-box-layout3.style2 .ct-title-line::before,
            .ct-fancy-box-layout3.style2 .item--number, .ct-contact-form-layout1.style5 .wpcf7-form .wpcf7-submit, .ct-service-grid3 .ct-load-more .btn:hover,
            .ct-pricing-single1.item--highlight .pricing--button .btn, .ct-pricing-single1.item--highlight .pricing--button .btn,
            .revslider-initialised .btn.btn-icon-slider1, .ct-button-layout1 .btn.btn-label,
            .ct-pricing-layout1.style2 .ct-pricing-tab-title, 
            .ct-contact-form-layout1.style1 .btn.btn-plus {
                background-color: '. esc_attr( $p_secondary_color ) .';
            }';
            echo '.revslider-initialised .rs-layer b.h6-title-slider,
            .revslider-initialised .nav-number span, .ct-banner1.style4 .ct-banner-number,
            .ct-service-carousel5 .item--icon, .ct-service-carousel5 .item--title a:hover {
                color: '. esc_attr( $p_secondary_color ) .';
            }';
            echo '.ct-pricing-single1.item--highlight .pricing--button .btn, .ct-pricing-single1.item--highlight .pricing--button .btn,
            .ct-service-carousel5 .item--icon {
                border-color: '. esc_attr( $p_secondary_color ) .';
            }';
            echo '.ct-service-grid3 .ct-load-more .btn:hover, .ct-service-grid3 .ct-load-more .btn:focus,
            .ct-pricing-single1.item--highlight .pricing--button .btn, .ct-pricing-single1.item--highlight .pricing--button .btn {
                color: #001c8f;
            }';
            echo '.revslider-initialised .btn.btn-icon-slider1:hover, .revslider-initialised .btn.btn-icon-slider1:focus,
            .ct-contact-form-layout1.style6 .wpcf7-form .wpcf7-submit, .ct-service-carousel5 .item-readmore a, .ct-service-carousel5 .item-readmore a:hover, 
            .ct-service-carousel5 .item-readmore a:focus, .ct-team-carousel2 .item--readmore .btn,
            .ct-pricing-layout1.style2 .ct-pricing-tab-title .ct-pricing-tab-item.active,
            .ct-pricing-layout1.style2 .ct-pricing-item-inner.ct-pricing-featured .ct-pricing-price1,
            .ct-contact-form-layout1.style1 .btn.btn-plus .icon-abs, .ct-contact-form-layout1.style1 .btn.btn-plus .ct-align-icon-right, .ct-contact-form-layout1.style1 .btn.btn-plus .ct-align-icon-left {
                color: #000;
            }';
            echo '.ct-pricing-layout1.style2 .ct-pricing-item-inner.ct-pricing-featured .ct-pricing-price1 span {
                color: #6e6e6e;
            }';
            echo '.ct-pricing-layout1.style2 .ct-pricing-item-inner.ct-pricing-featured .ct-pricing-price1::before {
                border-color: transparent #715908 #715908 transparent;
            }';
            echo '.ct-testimonial-carousel1.style2 .item--inner:hover .item--holder .item--svg .ct-path2 {
                fill: '. esc_attr( $p_secondary_color ) .';
            }';
            
		}

		/* Custom Css */
		$custom_css = bixol_get_opt( 'site_css' );
		if ( ! empty( $custom_css ) ) {
			echo esc_attr( $custom_css );
		}

		return ob_get_clean();
	}
}

new CSS_Generator();