<?php
/**
 * MindWebConcierge History & Conversation Handlers
 *
 * @package MindWebConcierge
 */

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

add_action( 'wp_ajax_mindweco_get_history', 'mindweco_get_history_ajax' );
add_action( 'wp_ajax_nopriv_mindweco_get_history', 'mindweco_get_history_ajax' );

function mindweco_format_remote_history_message( $message ) {
    if ( ! is_array( $message ) || empty( $message['content'] ) ) {
        return null;
    }

    $kind = isset( $message['kind'] ) ? sanitize_text_field( $message['kind'] ) : '';
    $role = isset( $message['role'] ) ? sanitize_text_field( $message['role'] ) : '';

    if ( 'operator_message' === $kind ) {
        $role = 'operator';
    } elseif ( 'conversation_question' === $kind || 'live_user_message' === $kind || 'user' === $role ) {
        $role = 'user';
    } elseif ( 'conversation_answer' === $kind || 'assistant' === $role ) {
        $role = 'bot';
    } else {
        $role = 'bot';
    }

    return array(
        'role'      => $role,
        'kind'      => $kind,
        'message'   => sanitize_textarea_field( $message['content'] ),
        'timestamp' => isset( $message['created_at'] ) ? sanitize_text_field( $message['created_at'] ) : '',
    );
}

function mindweco_get_remote_history_for_conversation( $conversation_id ) {
    $options  = get_option( 'mindweco_plugin_options', array() );
    $base_url = isset( $options['base_url'] ) ? untrailingslashit( esc_url_raw( $options['base_url'] ) ) : '';
    $token    = mindweco_decrypt_api_key( get_option( 'mindweco_plugin_access_token', '' ) );

    if ( empty( $base_url ) || empty( $token ) || empty( $conversation_id ) ) {
        return null;
    }

    $api_url = $base_url . '/operator/conversations/' . rawurlencode( $conversation_id ) . '/messages';
    $args = array(
        'timeout' => 15,
        'headers' => array(
            'Authorization' => 'Bearer ' . $token,
        ),
    );
    $response = wp_remote_get( $api_url, $args );

    if ( ! is_wp_error( $response ) && 401 === wp_remote_retrieve_response_code( $response ) && function_exists( 'mindweco_plugin_refresh_token' ) ) {
        $new_token = mindweco_plugin_refresh_token();
        if ( $new_token ) {
            $args['headers']['Authorization'] = 'Bearer ' . $new_token;
            $response = wp_remote_get( $api_url, $args );
        }
    }

    if ( is_wp_error( $response ) || 200 !== wp_remote_retrieve_response_code( $response ) ) {
        return null;
    }

    $raw = json_decode( wp_remote_retrieve_body( $response ), true );
    if ( ! is_array( $raw ) ) {
        return null;
    }

    $history = array();
    foreach ( $raw as $message ) {
        $formatted = mindweco_format_remote_history_message( $message );
        if ( $formatted ) {
            $history[] = $formatted;
        }
    }

    return $history;
}

function mindweco_get_history_ajax() {
    $nonce_value = isset( $_GET['nonce'] )
        ? sanitize_text_field( wp_unslash( $_GET['nonce'] ) )
        : '';
    if ( ! wp_verify_nonce( $nonce_value, 'mindweco_frontend_nonce' ) ) {
        wp_send_json_error( array( 'message' => 'Security check failed.' ) );
        return;
    }

    global $wpdb;

    $requested_conversation_id = isset( $_GET['conversation_id'] )
        ? sanitize_text_field( wp_unslash( $_GET['conversation_id'] ) )
        : '';
    $session_id = Mindweco_Session::get_frontend_session_id();

    if ( '' === $session_id && '' === $requested_conversation_id ) {
        wp_send_json_success( array() );
        return;
    }

    if ( '' !== $requested_conversation_id ) {
        $remote_history = mindweco_get_remote_history_for_conversation( $requested_conversation_id );
        if ( is_array( $remote_history ) && ! empty( $remote_history ) ) {
            wp_send_json_success( $remote_history );
            return;
        }
    }

    $conversation = null;
    $conversations = $wpdb->get_results(
        $wpdb->prepare(
            "SELECT * FROM {$wpdb->prefix}mindweco_conversations 
             WHERE cookie_id = %s AND is_cleared = 0
             ORDER BY created_at DESC",
            $session_id
        )
    );

    if ( empty( $conversations ) ) {
        wp_send_json_success( array() );
        return;
    }

    if ( '' !== $requested_conversation_id ) {
        foreach ( $conversations as $candidate_conversation ) {
            if ( $requested_conversation_id === $candidate_conversation->id ) {
                $conversation = $candidate_conversation;
                break;
            }
        }
    }

    if ( ! $conversation ) {
        $conversation = $conversations[0];
    }

    $results = $wpdb->get_results(
        $wpdb->prepare(
            "SELECT q.id AS question_id, q.question_text, q.created_at AS question_time, q.page_id,
                    r.id AS response_id, r.response_text, r.created_at AS response_time
             FROM {$wpdb->prefix}mindweco_questions q
             LEFT JOIN {$wpdb->prefix}mindweco_responses r ON q.id = r.question_id
             WHERE q.conversation_id = %s
             ORDER BY q.created_at ASC",
            $conversation->id
        ),
        ARRAY_A
    );

    $formatted_history = array();
    foreach ( $results as $row ) {
        if ( ! empty( $row['question_text'] ) ) {
            $formatted_history[] = array(
                'role'      => 'user',
                'message'   => $row['question_text'],
                'timestamp' => $row['question_time'],
                'page_id'   => $row['page_id'],
            );
        }
        if ( ! empty( $row['response_text'] ) ) {
            $formatted_history[] = array(
                'role'      => 'bot',
                'message'   => $row['response_text'],
                'timestamp' => $row['response_time'],
                'page_id'   => $row['page_id'],
            );
        }
    }

    wp_send_json_success( $formatted_history );
}

add_action( 'wp_ajax_mindweco_clear_history', 'mindweco_clear_history' );
add_action( 'wp_ajax_nopriv_mindweco_clear_history', 'mindweco_clear_history' );

function mindweco_clear_history() {
    global $wpdb;

    $nonce_value = isset( $_POST['nonce'] )
        ? sanitize_text_field( wp_unslash( $_POST['nonce'] ) )
        : '';
    if ( ! wp_verify_nonce( $nonce_value, 'mindweco_frontend_nonce' ) ) {
        wp_send_json_error( array(
            'message' => esc_html__( 'Security check failed.', 'mind-web-concierge' ),
        ) );
        return;
    }

    $session_id = Mindweco_Session::get_frontend_session_id();

    if ( '' === $session_id ) {
        wp_send_json_success( array(
            'message' => esc_html__( 'History cleared.', 'mind-web-concierge' ),
        ) );
        return;
    }

    $wpdb->update(
        $wpdb->prefix . 'mindweco_conversations',
        array( 'is_cleared' => 1 ),
        array(
            'cookie_id'  => $session_id,
            'is_cleared' => 0,
        ),
        array( '%d' ),
        array( '%s', '%d' )
    );

    wp_send_json_success( array(
        'message' => esc_html__( 'History cleared.', 'mind-web-concierge' ),
    ) );
}

add_action( 'wp', 'mindweco_schedule_cleanup' );
function mindweco_schedule_cleanup() {
    if ( ! wp_next_scheduled( 'mindweco_cleanup_transients' ) ) {
        wp_schedule_event( time(), 'daily', 'mindweco_cleanup_transients' );
    }
}

add_action( 'mindweco_cleanup_transients', 'mindweco_do_cleanup_transients' );
function mindweco_do_cleanup_transients() {
    global $wpdb;

    $expired = $wpdb->get_col(
        $wpdb->prepare(
            "SELECT REPLACE(option_name, '_transient_timeout_', '')
             FROM {$wpdb->options}
             WHERE option_name LIKE %s
             AND option_value < %d",
            '_transient_timeout_mindweco_session_%',
            time()
        )
    );

    if ( empty( $expired ) ) {
        return;
    }

    foreach ( $expired as $transient_name ) {
        delete_transient( $transient_name );
    }
}

add_action( 'wp_ajax_mindweco_get_history_from_api', 'mindweco_get_history_from_api_ajax' );
add_action( 'wp_ajax_nopriv_mindweco_get_history_from_api', 'mindweco_get_history_from_api_ajax' );
function mindweco_get_history_from_api_ajax() {
    mindweco_get_history_ajax();
}
