<?php

namespace WeDevs\Wpuf\Pro\AI_Review;

use WeDevs\Wpuf\Pro\AI_Review\Service;
use WeDevs\Wpuf\Pro\AI_Review\Scheduler;
use WeDevs\Wpuf\Pro\AI_Review\Helper;

/**
 * AI Post Review - Handles post submission review
 *
 * @since 4.2.5
 */
class Post_Review {

    /**
     * AI Service instance
     *
     * @var Service
     */
    private $ai_service;

    /**
     * AI Review Scheduler instance
     *
     * @var Scheduler
     */

    private $scheduler;

    /**
     * Constructor
     *
     * @since 4.2.5
     */
    public function __construct() {
        $this->ai_service = new Service();
        $this->scheduler  = new Scheduler();

        $this->init_hooks();
    }

    /**
     * Initialize hooks
     *
     * @since 4.2.5
     */
    private function init_hooks() {
        // Hook into post submission
        add_action( 'wpuf_add_post_after_insert', [ $this, 'review_post_on_submission' ], 20, 4 );

        // Hook into post update
        add_action( 'wpuf_edit_post_after_update', [ $this, 'review_post_on_update' ], 20, 4 );

        // Hook into TEC event creation (fires after TEC ORM saves all event data)
        add_action( 'wpuf_tec_after_create_event', [ $this, 'review_event_on_submission' ], 20, 6 );
    }

    /**
     * Review post on submission
     *
     * @since 4.2.5
     * @param int $post_id Post ID
     * @param int $form_id Form ID
     * @param array $form_settings Form settings
     * @param array $meta_vars Meta variables (already extracted from form submission)
     */
    public function review_post_on_submission( $post_id, $form_id, $form_settings, $meta_vars ) {
        // Pass meta_vars through so we don't need to re-query
        $this->process_review( $post_id, $form_settings, $meta_vars, 'submission' );
    }

    /**
     * Review post on update
     *
     * @since 4.2.5
     * @param int $post_id Post ID
     * @param int $form_id Form ID
     * @param array $form_settings Form settings
     * @param array $form_fields Form fields
     */
    public function review_post_on_update( $post_id, $form_id, $form_settings, $form_fields ) {
        // For updates, we'll need to extract meta vars from form fields
        // This is less efficient but updates are less frequent
        $this->process_review( $post_id, $form_settings, [], 'update' );
    }

    /**
     * Review event on TEC submission
     *
     * Handles Events Calendar submissions which bypass wp_insert_post and use
     * TEC's ORM API. This hook fires after all event data (dates, venue,
     * organizer) is fully persisted.
     *
     * @since 4.2.13
     *
     * @param int   $event_id      The created event post ID
     * @param array $args          The ORM arguments used to create the event
     * @param array $postarr       The original WordPress post array
     * @param array $meta_vars     The original meta variables from WPUF
     * @param int   $form_id       The WPUF form ID
     * @param array $form_settings The WPUF form settings
     */
    public function review_event_on_submission( $event_id, $args, $postarr, $meta_vars, $form_id, $form_settings ) {
        $this->process_review( $event_id, $form_settings, $meta_vars, 'submission' );
    }

    /**
     * Process AI review for a post
     *
     * @since 4.2.5
     * @param int $post_id Post ID
     * @param array $form_settings Form settings
     * @param array $meta_vars Meta variables (already extracted from form submission)
     * @param string $context Review context (submission/update)
     */
    private function process_review( $post_id, $form_settings, $meta_vars = [], $context = 'submission' ) {
        // Prevent duplicate reviews (e.g., both WPUF hook and TEC hook firing for the same event).
        // Uses a transient lock to handle the case where both hooks fire in the same request
        // before either has written the post meta status.
        $lock_key = 'wpuf_ai_review_lock_' . $post_id;

        if ( get_transient( $lock_key ) ) {
            return;
        }

        $existing_status = get_post_meta( $post_id, 'wpuf_ai_review_status', true );

        if ( in_array( $existing_status, [ 'pending', 'in_progress' ], true ) ) {
            return;
        }

        // Set a short-lived lock to prevent duplicate processing within the same request
        set_transient( $lock_key, true, 60 );

        // Use shared validation logic
        $validation = $this->ai_service->validate_review_request( $post_id, $form_settings );

        if ( ! $validation['valid'] ) {
            // Save failed review if AI service not configured
            if ( strpos( $validation['message'], 'not configured' ) !== false ) {
                Helper::save_failed_review( $post_id, $validation['message'] );
            }
            return;
        }

        // Fire before review action
        do_action( 'wpuf_ai_review_before', $post_id, $form_settings );

        // Schedule background review
        $this->schedule_background_review( $post_id, $form_settings, $meta_vars );
    }

    /**
     * Schedule background review
     *
     * @since 4.2.5
     * @param int $post_id Post ID
     * @param array $form_settings Form settings
     * @param array $meta_vars Meta variables (already extracted)
     */
    private function schedule_background_review( $post_id, $form_settings, $meta_vars = [] ) {
        // Schedule review with a short delay to allow post to be fully saved
        $scheduled = $this->scheduler->schedule_review( $post_id, $form_settings, $meta_vars, 10 ); // 10 seconds delay

        if ( $scheduled ) {
            // Save pending status
            Helper::save_pending_review( $post_id );
        } else {
            // Fallback: save failed status
            Helper::save_failed_review( $post_id, 'Unable to schedule background review' );
        }
    }


}
