<?php
/**
 * Create Memory Class
 *
 * @package SAAI
 */

namespace SAAI\Classes\Memory;

use SAAI\Abstracts\Abstract_Class;
use SAAI\Traits\Singleton_Trait;
use SAAI\Helpers\Connect;
use SAAI\Factories\Vite_App;
use SAAI\Helpers\Helper;
use SAAI\Classes\Plan_Manager;
use SAAI\REST\Chat\Chat_Widget_Settings;
use WC_Email;


defined( 'ABSPATH' ) || exit;

/**
 * Create Memory Class
 */
class Create_Memory extends Abstract_Class {

    use Singleton_Trait;

    const MEMORY_CREATED_OPTION      = 'saai_chat_ai_memory_created';
    const SHOW_SETUP_PROGRESS_OPTION = 'saai_show_setup_progress';
    const SETUP_EMAIL_SENT_OPTION    = 'saai_chat_setup_email_sent';

    /**
     * Run the class
     */
    public function run() {
        add_action( 'admin_notices', array( $this, 'display_setup_notice' ) );
        add_action( 'saai_admin_notices', array( $this, 'display_setup_notice' ) );
        add_action( 'wp_ajax_saai_start_chat_setup', array( $this, 'ajax_handle_start_setup' ) );
        add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
    }

    /**
     * Check if the store is eligible for StoreAgent Chat feature
     *
     * @return bool
     */
    public function is_eligible_for_chat() {
        $limit = Plan_Manager::instance()->get_plan_limit( 'vector_items' );
        return $limit > 0;
    }

    /**
     * Check if AI memory has been created
     *
     * @return bool
     */
    public function is_memory_created() {
        return get_option( self::MEMORY_CREATED_OPTION ) === 'yes';
    }

    /**
     * Check if we should show the setup notice
     *
     * @return bool
     */
    public function should_show_notice() {
        // Only show to admins.
        if ( ! current_user_can( 'manage_options' ) ) {
            return false;
        }

        // Don't show if store is not connected.
        if ( ! Connect::is_connected() ) {
            return false;
        }

        // Don't show if not eligible for chat.
        if ( ! $this->is_eligible_for_chat() ) {
            return false;
        }

        // Don't show if chat feature is disabled in settings.
        $chat_settings = Chat_Widget_Settings::get_chat_widget_settings();
        if ( ! $chat_settings['enabled'] ) {
            return false;
        }

        // Don't show if no post types are enabled for AI memory.
        $has_enabled_post_types = Helper::get_post_types_with_ai_memory_enabled();
        if ( empty( $has_enabled_post_types ) ) {
            return false;
        }

        // Don't show if memory is already created.
        if ( $this->is_memory_created() ) {
            return false;
        }

        return true;
    }

    /**
     * Handle the AJAX request to start chat setup
     */
    public function ajax_handle_start_setup() {
        check_ajax_referer( 'saai-start-chat-setup', 'nonce' );

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( array( 'message' => __( 'You do not have permission to perform this action.', 'storeagent-ai-for-woocommerce' ) ) );
        }

        // Create AI memory.
        $response = $this->create_ai_memory();
        if ( is_wp_error( $response ) ) {
            wp_send_json_error( array( 'message' => $response->get_error_message() ) );
        }

        // Save the options.
        update_option( self::MEMORY_CREATED_OPTION, 'yes' );
        update_option( self::SHOW_SETUP_PROGRESS_OPTION, 'yes' );

        $post_types = Helper::get_post_types_with_ai_memory_enabled();
        foreach ( $post_types as $post_type ) {
            Data_Upload::instance()->schedule_post_data_upload( $post_type );
        }

        wp_send_json_success( array( 'message' => __( 'StoreAgent Chat setup completed successfully.', 'storeagent-ai-for-woocommerce' ) ) );
    }

    /**
     * Create AI memory by calling the worker plugin endpoint
     *
     * @return true|WP_Error
     */
    protected function create_ai_memory() {
        $headers = array(
            'Content-Type'  => 'application/json',
            'X-Origin'      => wp_parse_url( get_home_url(), PHP_URL_HOST ),
            'Authorization' => 'Basic ' . base64_encode( Connect::get_consumer_key() . ':' . Connect::get_consumer_secret() ), // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
        );

        $response = wp_remote_post(
            Helper::get_storeagent_base_url( 'api' ) . '/storeagent/v1/memory/create',
            array(
                'headers' => $headers,
                'timeout' => 30,
            )
        );

        if ( is_wp_error( $response ) ) {
            return $response;
        }

        $body = json_decode( wp_remote_retrieve_body( $response ), true );
        $code = wp_remote_retrieve_response_code( $response );

        if ( $code > 299 ) {
            return new \WP_Error(
                'storeagent_create_ai_memory_error',
                isset( $body['message'] ) ? $body['message'] : __( 'Failed to create AI memory for store.', 'storeagent-ai-for-woocommerce' ),
                $body
            );
        }

        return true;
    }

    /**
     * Display the setup notice
     */
    public function display_setup_notice() {
        if ( ! $this->should_show_notice() ) {
            return;
        }

        include SAAI_TEMPLATES_DIR . 'admin/ai-memory/setup-ai-chat-admin-notice.php';
    }

    /**
     * Check if setup progress should be shown
     *
     * @return bool
     */
    public function should_show_setup_progress() {
        return $this->is_memory_created() && get_option( self::SHOW_SETUP_PROGRESS_OPTION ) === 'yes';
    }

    /**
     * Check if setup email has been sent
     *
     * @return bool
     */
    public function is_setup_email_sent() {
        return get_option( self::SETUP_EMAIL_SENT_OPTION ) === 'yes';
    }

    /**
     * Mark setup email as sent
     */
    public function mark_setup_email_sent() {
        update_option( self::SETUP_EMAIL_SENT_OPTION, 'yes' );
    }

        /**
         * Send setup completion email
         *
         * @param int $posts_uploaded Number of posts uploaded.
         * @return bool Whether email was sent successfully.
         */
    public function send_setup_completion_email( $posts_uploaded ) {
        $admin_email = get_option( 'admin_email' );
        $store_name  = get_bloginfo( 'name' );

        if ( empty( $admin_email ) ) {
            return false;
        }

        // initialize wC mailer.
        WC()->mailer();

        // create a new email.
        $email = new WC_Email();

        // set the email subject.
        $subject       = __( 'Your StoreAgent Chat is Ready!', 'storeagent-ai-for-woocommerce' );
        $email_heading = __( 'StoreAgent Chat Setup Complete', 'storeagent-ai-for-woocommerce' );

        // Load the HTML email template.
        ob_start();
        include SAAI_TEMPLATES_DIR . 'emails/setup-complete.php';
        $message = ob_get_clean();

        $headers = array(
            'Content-Type: text/html; charset=UTF-8',
            'From: ' . get_bloginfo( 'name' ) . ' <' . get_option( 'admin_email' ) . '>',
        );

        $check = $email->send(
            $admin_email,
            $subject,
            $message,
            $headers,
            array()
        );

        return $check;
    }

    /**
     * Enqueue scripts for the setup process
     */
    public function enqueue_scripts() {
        if ( $this->should_show_notice() ) {
            $script = new Vite_App(
                'saai-chat-setup',
                'src/vanilla/notice/chat-setup.ts',
                array( 'jquery' ),
                array(
                    'ajaxUrl' => admin_url( 'admin-ajax.php' ),
                    'nonce'   => wp_create_nonce( 'saai-start-chat-setup' ),
                ),
                'saaiChatSetup'
            );
            $script->enqueue();
        }
    }
}
