<?php
    /**
     * This file handles all ajax related to this theme
     * 
     * @package Blog Bee
     * @since 1.0.0
     */
    namespace BBE;

    use WP_Query;
    use WP_Ajax_Upgrader_Skin;
    use Plugin_Upgrader;
    use BBE\Widgets\Post_List_And_Grid as Post_List_And_Grid;
    use BBE\Customizer\Theme_Defaults as Theme_Defaults;

    use function get_search_query;
    use function esc_html__;
    use function add_action;
    use function check_ajax_referer;
    use function sanitize_text_field;
    use function wp_send_json_error;
    use function wp_send_json_success;
    use function wp_reset_postdata;
    use function the_post_thumbnail;
    use function has_post_thumbnail;
    use function esc_url;
    use function get_permalink;
    use function the_title;
    use function wp_create_nonce;

    if( ! class_exists( __NAMESPACE__ . '\\Ajax_Manager' ) ){
        /**
         * Ajax_Manager class
         */
        class Ajax_Manager {
            /**
             * Hooks
             * 
             * @since 1.0.0
             */
            private $hooks = [];

            /**
             * Ajax hooks
             * 
             * @since 1.0.0
             */
            private $ajax_hooks = [ 'wp_ajax_', 'wp_ajax_nopriv_' ];

            /**
             * Set hooks
             * 
             * @since 1.0.0
             */
            public function set_hooks() {
                $this->hooks[] = 'header_search_ajax';
                $this->hooks[] = 'search_filter_ajax_call';
                $this->hooks[] = 'plugin_active_install_ajax_call';
                $this->hooks[] = 'admin_notice_dismiss_ajax_call';
                $this->hooks[] = 'get_nonce';
                $this->hooks[] = 'web_stories_ajax_call';
            }

            /**
             * Constructor
             * 
             * @since 1.0.0
             */
            public function __construct() {
                $this->set_hooks();
                $this->register_hooks();
            }

            /**
             * Register hooks
             * 
             * @since 1.0.0
             */
            private function register_hooks() {
                foreach( $this->hooks as $hook ) {
                    foreach( $this->ajax_hooks as $ajax_hook ) {
                        add_action( $ajax_hook . $hook, [ $this, $hook ] );
                    }
                }
            }

            /**
             * Json error
             * 
             * @since 1.0.0
             */
            private function json_error( $message = '' ) {
                if( ! $message ) $message = esc_html__( 'Sorry! Something went wrong.', 'blog-bee' );
                $error_json = [
                    'message'   =>  esc_html( $message )
                ];
                return wp_send_json_error( $error_json, 500 );
            }

            /**
             * Json success
             * 
             * @since 1.0.0
             */
            private function json_success( $message, $extra_args = [] ) {
                $success_json = [
                    'message'   =>  $message
                ];
                if( ! empty( $extra_args ) && is_array( $extra_args ) ) {
                    $success_json = array_merge( $success_json, $extra_args );
                }
                return wp_send_json_success( $success_json, 200 );
            }

            /**
             * Header search ajax call
             * 
             * @since 1.0.0
             */
            public function header_search_ajax() {
                check_ajax_referer( 'blog-bee-security-nonce', '_wpnonce' );

                $search_query = isset( $_POST[ 'search_query' ] ) ? sanitize_text_field( $_POST[ 'search_query' ] ) : '';

                if( ! $search_query ) $this->json_error();

                $query_instance = Query_Manager::fine_tune_query_attrs( [
                    'posts_per_page'	=>	absint( Theme_Defaults::get_theme_option( 'live_search_count' ) ),
                    's'	=>	$search_query
                ], true );

                if( $query_instance->have_posts() ) {

                    ob_start();

                    while( $query_instance->have_posts() ) {

                        $query_instance->the_post();

                        Query_Manager::get_opening_article_tag();

                            if( has_post_thumbnail() && Theme_Defaults::get_theme_option( 'live_search_show_featured_image' ) ) :

                                Query_Manager::get_opening_figure_tag();

                                    Query_Manager::get_featured_image( 'thumbnail', [ 'post_format' => false ] );

                                Query_Manager::get_closing_figure_tag();

                            endif;

                            echo '<div class="entry-content">';

                                Query_Manager::get_title();

                                echo '<div class="entry-meta">';

                                    Query_Manager::get_date();

                                    Query_Manager::get_author();

                                echo '</div>';

                            echo '</div>';

                        Query_Manager::get_closing_article_tag();

                    }

                    wp_reset_postdata();

                    $this->json_success( ob_get_clean(), [ 'continue' => true ] );

                } else {

                    $this->json_success( '', [ 'continue' => false ] );

                }
            }

            /**
             * Search page ajax call
             * 
             * @since 1.0.0
             */
            function search_filter_ajax_call() {
                check_ajax_referer( 'blog-bee-security-nonce', '_wpnonce' );

                $query_args = ( isset( $_POST[ 'query' ] ) ) ? $_POST[ 'query' ] : [];
                $clicked_button = ( isset( $_POST[ 'clickedButton' ] ) ) ? $_POST[ 'clickedButton' ] : 'load-more';
                $date_query_enabled = false;
                if( isset( $query_args[ 'before' ] ) ) {
                    $query_args[ 'date_query' ][ 'before' ] = $query_args[ 'before' ];
                    $date_query_enabled = true;
                }
                if( isset( $query_args[ 'after' ] ) ) {
                    $query_args[ 'date_query' ][ 'after' ] = $query_args[ 'after' ];
                    $date_query_enabled = true;
                }
                if( $date_query_enabled ) {
                    $query_args[ 'date_query' ][ 'relation' ] = 'OR';
                    $query_args[ 'date_query' ][ 'inclusive' ] = true;
                }
                unset( $query_args[ 'before' ] );
                unset( $query_args[ 'after' ] );
                $query_args[ 'posts_per_page' ] =  get_option( 'posts_per_page' );
                $instance = Query_Manager::fine_tune_query_attrs( $query_args, true );

                if( $instance->have_posts() ) {

                    ob_start();

                    while( $instance->have_posts() ) {

                        $instance->the_post();

                        get_template_part( 'template-parts/content', '' );
                        
                    }

                    wp_reset_postdata();

                    $this->json_success( ob_get_clean(), [ 'continue' => true ] );

                } else {

                    $this->json_success( '', [ 'continue' => false ] );

                }
            }

            /**
             * Activate or install plugins
             *
             * @since 1.0.0
             */
            public function plugin_active_install_ajax_call() {
                check_ajax_referer( 'blog-bee-admin-nonce', '_wpnonce' );
                if( ! current_user_can( 'install_plugins' ) || ! current_user_can( 'activate_plugins' ) ) {
                    $this->json_error( 'You dont have permission to perform this action' );
                }

                $status = isset( $_POST[ 'status' ] ) ? sanitize_text_field( $_POST[ 'status' ] ) : '';
                $link = isset( $_POST[ 'link' ] ) ? esc_url( $_POST[ 'link' ] ) : '';
                $file_path = isset( $_POST[ 'filePath' ] ) ? sanitize_text_field( $_POST[ 'filePath' ] ) : '';

                if( $status === 'enable' ) {

                    if( $file_path ) {
                        activate_plugin( $file_path, '', false, true );
                        $this->json_success( esc_html__( 'Plugin activated', 'blog-bee' ), [ 'continue' => false ] );
                    }

                } elseif( $status === 'deploy' ) {

                    $download_link = esc_url( $link );
                    // Include required libs for installation
                    require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
                    require_once ABSPATH . 'wp-admin/includes/class-wp-ajax-upgrader-skin.php';
                    require_once ABSPATH . 'wp-admin/includes/class-plugin-upgrader.php';

                    $skin = new WP_Ajax_Upgrader_Skin();
                    $upgrader = new Plugin_Upgrader( $skin );
                    $upgrader->install( $download_link );

                    if( $file_path ) {
                        activate_plugin( $file_path, '', false, true );
                        $this->json_success( esc_html__( 'Plugin activated', 'blog-bee' ), [ 'continue' => false ] );
                    }
                    
                } else {
                    $message = esc_html__( 'Error while trying to install or active the plugin.', 'blog-bee' );
                    $this->json_success( $message, [ 'continue' => false ] );
                }

            }

            /**
             * Admin notice dismiss ajax
             * 
             * @since 1.0.0
             */
            public function admin_notice_dismiss_ajax_call() {
                check_ajax_referer( 'blog-bee-notice-nonce', '_wpnonce' );
                update_option( 'blog_bee_welcome_notice_dismiss', true );
                $this->json_success( esc_html__( 'Welcome Notice Dismissed', 'blog-bee' ), [ 'continue' => false ] );
            }

            /**
             * Admin notice dismiss ajax
             * 
             * @since 1.0.0
             */
            public function get_nonce() {
                wp_send_json_success( [
                    'nonce' => wp_create_nonce( 'blog-bee-security-nonce' )
                ] );
            }

            /**
             * Add stories to web stories according to current active story
             * 
             * @since 1.0.0
             */
            public function web_stories_ajax_call() {
                check_ajax_referer( 'blog-bee-security-nonce', '_wpnonce' );
                $story_ids = ( isset( $_POST[ 'storyIds' ] ) ) ? $_POST[ 'storyIds' ] : '';
                if( ! $story_ids ) $this->json_error();
                $query_args = [
                    'post_type'	=>	'post',
                    'post_status'	=>	'publish',
                    'no_found_rows'	=>	true
                ];
                $content_toggles = Theme_Defaults::get_theme_option( 'web_stories_content_toggles_in_slider' );
                $default_content_toggles = Theme_Defaults::get_defaults( 'web_stories_content_toggles_in_slider' );
                $title = isset( $content_toggles[ 'title' ] ) ? $content_toggles[ 'title' ] : $default_content_toggles[ 'title' ];
                $category = isset( $content_toggles[ 'category' ] ) ? $content_toggles[ 'category' ] : $default_content_toggles[ 'category' ];
                $author = isset( $content_toggles[ 'author' ] ) ? $content_toggles[ 'author' ] : $default_content_toggles[ 'author' ];
                $date = isset( $content_toggles[ 'date' ] ) ? $content_toggles[ 'date' ] : $default_content_toggles[ 'date' ];

                $post_per_page = Theme_Defaults::get_theme_option( 'web_stories_max_inner_stories' );
                $query_args[ 'posts_per_page' ] = absint( $post_per_page );
                $success_flag = false;
                ob_start();
                foreach( $story_ids as $cat_id ) :
                    $query_args[ 'category__in' ] = ( int ) $cat_id;
                    $query_instance = Query_Manager::fine_tune_query_attrs( $query_args, true );
                    if( $query_instance->have_posts() ) :
                        $success_flag = true;
                        echo '<div class="inner-story">';
    
                            echo '<div class="inner-story-wrap" data-id="', esc_attr( $cat_id ) ,'">';
    
                                while( $query_instance->have_posts() ) : $query_instance->the_post();
                                    ?>
                                        <div class="story-item<?php if( ! has_post_thumbnail() ) echo ' no-thumb'; ?>">
    
                                            <div class="story-cover-wrap">
    
                                                <figure class="story-cover">
    
                                                    <?php 
                                                        // thumbnail
                                                        the_post_thumbnail( 'post-thumbnail', [
                                                            'loading'	=>	'lazy',
                                                            'alt'	=>	the_title_attribute( [ 'echo' => false ] )
                                                        ]);
    
                                                    ?>
    
                                                </figure>
    
                                            </div>
    
                                            <?php
    
                                                echo '<div class="entry-inner">';
                                                        
                                                    // categories
                                                    if( $category ) Query_Manager::get_categories();
    
                                                    // title
                                                    if( $title ) Query_Manager::get_title();
    
                                                    // Meta
                                                    if( $date || $author ) :
    
                                                        echo '<div class="entry-meta">';
            
                                                            // author
                                                            if( $author ) Query_Manager::get_author();
            
                                                            // date
                                                            if( $date ) Query_Manager::get_date();
            
                                                        echo '</div>';
                                                        
                                                    endif;
    
                                                echo '</div>';
    
                                            ?>
    
                                        </div>
    
                                    <?php
                                endwhile;
    
                            echo '</div>';
    
                        echo '</div>';
                        wp_reset_postdata();
                    else :
                        continue;
                    endif;
                endforeach;
                if( $success_flag ) :
                    $this->json_success( ob_get_clean(), [ 'continue' => false ] );
                else:
                    $this->json_error();
                endif;
            }
        }
        new Ajax_Manager();
    }