<?php
    /**
     * Manage cache
     * 
     * @package Blog Bee
     * @since 1.0.0
     */
    namespace BBE;
    use BBE\Customizer\Section\Section as Section;
    use BBE\Customizer\Theme_Defaults as Theme_Defaults;

    use function add_action;
    use function get_transient;
    use function set_transient;
    use function wp_parse_url;
    use function add_query_arg;
    use function wp_remote_get;
    use function is_wp_error;
    use function wp_remote_retrieve_body;

    if( ! class_exists( __NAMESPACE__ . '\\Cache_Manager' ) ) {
        /**
         * Cache_Manager class
         */
        class Cache_Manager {
            /**
             * Instance
             * 
             * @since 1.0.0
             */
            private static $instance = null;

            /**
             * Youtube api key
             * 
             * @since 1.0.0
             */
            private $api_key = '';

            /**
             * Instance getter
             * 
             * @since 1.0.0
             */
            public static function get_instance(): Cache_Manager {
                if( self::$instance === null ) {
                    self::$instance = new self();
                }
                return self::$instance;
            }

            /**
             * Constructor
             */
            public function __construct() {
                /**
                 * Hook executes after value of a control changes
                 */
                add_action( 'customize_save_after', [ $this, 'clear_transient' ] );
                /**
                 * Hooks executes after value of a control changes and customizer resets
                 */
                add_action( "updated_option", [ $this, 'clear_transient' ] );
                /**
                 * Set transient on init
                 */
                add_action( 'init', function(){
                    self::get_dynamic_css();
                    self::get_plugins_details();
                } );
            }

            /**
             * Clear transient
             * 
             * @since 1.0.0
             */
            public function clear_transient() {
                delete_transient( 'bbe_dynamic_css' );
            }
            
            /**
             * Generate color preset variables
             * 
             * @param string $control_id The setting id
             * @param string $type color type
             * @since 1.0.0
             */
            private static function generate_color_preset_variables( $control_id, $type ) {
                $solid_presets = Theme_Defaults::get_theme_option( $control_id );
                $solid_active = isset( $solid_presets[ 'active' ] ) ? $solid_presets[ 'active' ] : false;
                $solid_palettes = isset( $solid_presets[ 'palettes' ] ) ? $solid_presets[ 'palettes' ] : [];

                $css = [];
                if( $solid_active && ! empty( $solid_palettes ) && is_array( $solid_palettes ) ) {
                    $preset = $solid_palettes[ $solid_active ];
                    if( ! empty( $preset ) && is_array( $preset ) ) {
                        foreach( $preset as $index => $color ) {
                            $css[] = '--bbe-' . $type . '-preset-' . ( $index + 1 ) . ':' . $color;
                        }
                    }
                }
                return 'body{' . implode( ';', $css ) . '}';
            }

            /**
             * MARK: Dynamic css
             * 
             * @since 1.0.0
             */
            public static function get_dynamic_css() {
                $cached = get_transient( 'bbe_dynamic_css' );

                if( $cached !== false ) {
                    return $cached;
                }

                $dynamic_css = [];
                $all_sections = Section::get_all_registered_sections();
                foreach( $all_sections as $section ) {
                    $dynamic_css[] = implode( "\n", $section::get_instance()->render_dynamic_css() );
                }

                if( $dynamic_css ) {
                    $css = self::generate_color_preset_variables( 'solid_color_palette', 'solid' );
                    $css .= self::generate_color_preset_variables( 'gradient_color_palette', 'gradient' );
                    $css .= implode( ' ', $dynamic_css );
                } else {
                    $css = '';
                }
                set_transient( 'bbe_dynamic_css', $css, HOUR_IN_SECONDS );
                return $css;
            }

            /**
             * MARK: Recommended Plugins
             * Function to get plugins details using REST API
             * 
             * @since 1.0.0
             */
            public static function get_plugins_details() {
                $transient_key = 'bbe_admin_recommended_plugins_' . wp_get_theme()->get( 'Version' );
                $cached = get_transient( $transient_key );
                if( $cached !== false ) {
                    return $cached;
                }

                $plugins_to_add_args = [
                    [
                        'author'    =>  'elemntor',
                        'slug'  =>  [ 'elementor' ],
                        'directory' =>  [
                            'elementor'    =>  'elementor'
                        ],
                        'file'  =>  [
                            'elementor' =>  'elementor.php'
                        ]
                    ],
                    [
                        'author'    =>  'blazethemes',
                        'slug'  =>  [ 'news-kit-elementor-addons' ],
                        'directory' =>  [ 
                            'news-kit-elementor-addons'  =>  'news-kit-elementor-addons'
                        ],
                        'file'  =>  [ 
                            'news-kit-elementor-addons'  =>  'news-kit-elementor-addons.php',
                        ],
                        'dependency'    =>  [
                            'news-kit-elementor-addons' =>  'elementor'
                        ]
                    ],
                    [
                        'author'    =>  'blazethemes',
                        'slug'  =>  [ 'blaze-demo-importer' ],
                        'directory' =>  [ 
                            'blaze-demo-importer'  =>  'blaze-demo-importer'
                        ],
                        'file'  =>  [ 
                            'blaze-demo-importer'  =>  'blaze-demo-importer.php',
                        ]
                    ]
                ];
                $plugin_information = [];
                if( empty( array_column( $plugins_to_add_args, 'author' ) ) || count( array_column( $plugins_to_add_args, 'author' ) ) <= 0 ) return [];   // guard
                if( empty( $plugins_to_add_args ) || ! is_array( $plugins_to_add_args ) ) return [];   // guard
                
                foreach( $plugins_to_add_args as $plugin ) {
                    $base_url = 'https://api.wordpress.org/plugins/info/1.2/?action=query_plugins&request[author]='. $plugin[ 'author' ];
                    $response = wp_remote_get( $base_url );
                    
                    if( ! is_array( $response ) || is_wp_error( $response ) ) continue;
                    
                    $body = json_decode( $response[ 'body' ], true ); // use the content

                    if( empty( $body[ 'plugins' ] ) || ! is_array( $body[ 'plugins' ] ) ) continue;

                    foreach( $body[ 'plugins' ] as $body_key => $body_value ) {

                        if( ! in_array( $body_value[ 'slug' ], $plugin[ 'slug' ] ) ) continue;
                        

                        $body_value[ 'directory' ] = $plugin[ 'directory' ][ $body_value[ 'slug' ] ];
                        $body_value[ 'file' ] = $plugin[ 'file' ][  $body_value[ 'slug' ] ];
                        if( array_key_exists( 'dependency', $plugin ) ) $body_value[ 'dependency' ] = $plugin[ 'dependency' ][ $body_value[ 'slug' ] ];
                        $plugin_information[ $body_value[ 'slug' ] ] = $body_value;
                    }
                }
                set_transient( $transient_key, $plugin_information, HOUR_IN_SECONDS );
                return $plugin_information;
            }
        }
        Cache_Manager::get_instance();
    }