<?php
/**
 * Author: Rymera Web Co.
 *
 * @package SAAI\Classes\Chat
 */

namespace SAAI\Classes\Chat;

use SAAI\Abstracts\Abstract_Class;
use SAAI\Traits\Singleton_Trait;

defined( 'ABSPATH' ) || exit;

/**
 * Chat_Session class for managing chat session data and AI response counts.
 *
 * @since 1.0.8
 */
class Chat_Session extends Abstract_Class {

    /**
     * Session data key for storing response count in WC session.
     *
     * @since 1.0.8
     */
    const SESSION_DATA_KEY = 'saai_response_data';

    /**
     * Order meta key for storing response count in order metadata.
     *
     * @since 1.0.8
     */
    const ORDER_META_KEY = '_saai_response_count';

    use Singleton_Trait;

    /**
     * Holds the class instance object.
     *
     * @since 1.0.8
     * @var Chat_Session $instance object
     */
    protected static $instance;

    /**
     * Run the class.
     *
     * @since 1.0.8
     * @return void
     */
    public function run() {
        // Hook to save response count when order is placed.
        add_action( 'woocommerce_checkout_order_processed', array( $this, 'save_response_count_to_order' ) );

        // Hook to increment response count when chat message is processed.
        add_action( 'saai_increment_response_count', array( $this, 'increment_response_count' ) );
    }

    /**
     * Increment the response count for the current session.
     *
     * @since 1.0.8
     * @param int $user_id The user ID (0 for guests).
     * @return void
     */
    public function increment_response_count( $user_id ) {
        // If WC session is not initialized, return.
        if ( ! WC()->session ) {
            return;
        }

        // Get current session data from WC session.
        // WC session automatically handles user separation, so we use a fixed key.
        $session_data = WC()->session->get( self::SESSION_DATA_KEY, array() );

        if ( ! is_array( $session_data ) ) {
            // If no session data exists, initialize it.
            $session_data = array(
                'response_count' => 1,
                'user_id'        => $user_id,
                'created_at'     => time(),
            );
        } else {
            // Increment the response count.
            $session_data['response_count'] = isset( $session_data['response_count'] ) ? $session_data['response_count'] + 1 : 1;
        }

        // Update the WC session with the new count.
        WC()->session->set( self::SESSION_DATA_KEY, $session_data );
    }

    /**
     * Get the current response count for the session.
     *
     * @since 1.0.8
     * @param int $user_id The user ID (0 for guests).
     * @return int Response count.
     */
    public function get_response_count( $user_id ) {
        // Get current session data from WC session.
        // WC session automatically handles user separation, so we use a fixed key.
        $session_data = WC()->session->get( self::SESSION_DATA_KEY, array() );

        if ( ! is_array( $session_data ) ) {
            return 0;
        }

        return isset( $session_data['response_count'] ) ? absint( $session_data['response_count'] ) : 0;
    }


    /**
     * Save the current session's response count to order metadata.
     *
     * @since 1.0.8
     * @param int $order_id The order ID.
     * @return void
     */
    public function save_response_count_to_order( $order_id ) {
        // Get the current user ID (0 for guests).
        $user_id = get_current_user_id();

        // Get the response count for this session.
        $response_count = $this->get_response_count( $user_id );

        // Only save if there are responses.
        if ( $response_count > 0 ) {
            // Update order metadata with the response count.
            update_post_meta( $order_id, self::ORDER_META_KEY, $response_count );

            // Clear the session data after successfully saving to order metadata.
            WC()->session->set( self::SESSION_DATA_KEY, array() );
        }
    }
}
