<?php
/**
 * AI Product Review Summary - Single Product Page
 * 
 * @since 1.1.0
 */

// Direct load is not allowed
if ( ! defined( 'ABSPATH' ) ) {
	die();
}

require_once ALPUS_PLUGIN_FRAMEWORK_PATH . 'admin/options/class-plugin-options.php';

class Alpus_APRS_SP {
	/**
	 * The Constructor
     *
	 * @since 1.1.0
	 * @access public
	*/
	public function __construct() {
        $post_types = array( 'product_variation' );
        if ( ( 'post-new.php' == $GLOBALS['pagenow'] && isset( $_REQUEST['post_type'] ) && ! in_array( $_REQUEST['post_type'], $post_types ) ) || ( 'post.php' == $GLOBALS['pagenow'] && isset( $_REQUEST['post'] ) && ! in_array( get_post_type( $_REQUEST['post'] ), $post_types ) ) ) {
            add_filter( 'rwmb_meta_boxes', array( $this, 'add_meta_boxes' ) );
            // Backend JS & Styles
            add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_admin' ), 99 );
        }
        
        add_action( 'wp_ajax_alpus_aprs_sp_info', array( $this, 'get_current_status' ) );

        add_action( 'alpus_aprs_review_bg_generate', array( $this, 'generate_step' ), 1 );
	}

    public function add_meta_boxes() {
        if ( isset( $_REQUEST['post_type'] ) ) {
            $post_type = $_REQUEST['post_type'];
        } else if ( isset( $_REQUEST['post'] ) ) {
            $post_type = get_post_type( $_REQUEST['post'] );
        }
        $meta_boxes[] = array(
            'id'         => 'alpus-aprs-status',
            'title'      => esc_html__( 'AI Product Review Summary', 'alpus-aprs' ),
            'post_types' => array( $post_type ),
            'context'    => 'side',
            'priority'   => 'high',
            'fields'     => array(
                array(
                    'id'    => 'alpus-aprs-sp-status',
                    'class' => 'alpus-aprs-sp-status',
                    'type'  => 'heading',
                    'name'  => esc_html__( 'Current Status:', 'alpus-aprs' ),
                    'desc'  => '<span class="current">0</span> ' . esc_html__( 'of', 'alpus-aprs' ) . ' <span class="total">0</span> ' . esc_html__( 'Reviews are summarized.', 'alpus-aprs' ),
                ),
            ),
        );
        return $meta_boxes;
    }

    /**
     * Get Current Status
     * 
     * @since 1.1.0
     */
    public function get_current_status() {
        if ( ! empty( $_REQUEST['id'] ) ) {
            $id = (int) sanitize_text_field( $_REQUEST['id'] );
            $product = wc_get_product( $id );
    
            // Get Summarized Review IDs.
            $summarized_reivews = get_post_meta( $id, 'alpus_aprs_summarized_reviews', true );

            if ( ! empty( $summarized_reivews ) ) {
                $summarized_reivews = json_decode( $summarized_reivews, true );
            } else {
                $summarized_reivews = array();
            }
    
            // Get Total Product Reviews Count
            $total_reviews_count = $product->get_review_count();
    
            $result = array(
                'current' => count( $summarized_reivews ),
                'total'   => $total_reviews_count,
            );
    
            wp_send_json_success( $result );
        }

        die();
    }

    /**
     * Start Background Summary
     * 
     * Start running background process for summarizing remaining reviews.
     * 
     * @since 1.1.0
     * 
     * @param $id Product ID
     */
    static public function start_background_summary( $id ) {
        if ( false === as_has_scheduled_action( 'alpus_aprs_review_bg_generate' ) ) {
            update_option( 'alpus_aprs_bg_running_index', 0 );

            // Repeat generate step once in a day. - 86400 seconds
			as_schedule_recurring_action( strtotime( 'now' ), 86400, 'alpus_aprs_review_bg_generate', array(), '', true );
		}

        // Get Background Process Running Product IDs.
        $running_ids = get_option( 'alpus_aprs_bg_running_ids', array() );

        // If it is not included in running process.
        if ( false === in_array( $id, $running_ids ) ) {
            $running_ids[] = $id;

            // Update Background Process Running Product IDs.
            update_option( 'alpus_aprs_bg_running_ids', $running_ids );
        }
    }

    /**
     * Generate Step
     * 
     * @since 1.1.0
     */
    static public function generate_step() {
        // Get Background Running Product IDs.
        $running_ids = get_option( 'alpus_aprs_bg_running_ids', array() );

        // Get current index.
        $current_index = get_option( 'alpus_aprs_bg_running_index', 0 );

        $id = $running_ids[ $current_index ];

        $product = wc_get_product( $id );
    
        // Get Summarized Review IDs.
        $summarized_reivews = get_post_meta( $id, 'alpus_aprs_summarized_reviews', true );

        if ( ! empty( $summarized_reivews ) ) {
            $summarized_reivews = json_decode( $summarized_reivews, true );
        } else {
            $summarized_reivews = array();
        }

        // Get Total Product Reviews Count
        $total_reviews_count = $product->get_review_count();
                
        if ( 10 <= ( $total_reviews_count - count( $summarized_reivews ) ) ) {
            // Summarize remain 10 reviews
            $result = apply_filters( 'alpus_aprs_summarize_remain_reviews', false, $id, $summarized_reivews );
        }
     
        $next_index = ( $current_index + 1 ) % count( $running_ids );

        update_option( 'alpus_aprs_bg_running_index', $next_index );
    }

    /**
     * Enqueue JS & Styles for Backend.
     * 
     * @since 1.1.0
     * @access public
     */
    public function enqueue_admin() {
        wp_enqueue_style( 'alpus-aprs-sp-admin', ALPUS_APRS_URI . 'assets/css/alpus-aprs-sp-admin.min.css', array(), ALPUS_APRS_VERSION );

        // Single Product Admin JS
        wp_enqueue_script( 'alpus-aprs-sp-admin', ALPUS_APRS_URI . 'assets/js/alpus-aprs-sp-admin' . ALPUS_PLUGIN_JS_SUFFIX, array( 'jquery-core' ), ALPUS_APRS_VERSION );
        wp_localize_script( 'alpus-aprs-sp-admin', 'alpus_aprs_sp_admin_vars', array(
            'ajax_url' => esc_url( admin_url( 'admin-ajax.php' ) ),
            'nonce'    => wp_create_nonce( 'alpus-aprs-sp-admin' ),
        ) );
    }
}

new Alpus_APRS_SP;