<?php
/**
 * AI Conversation Insights (Premium Module)
 *
 * @package Replyan_AI
 */

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

final class Replyan_Conversation_Insights {
	const OPTION_CATEGORIES = 'replyan_ai_conversation_categories';

	public function register_hooks(): void {
		add_action( 'wp_ajax_replyan_ai_save_categories', array( $this, 'ajax_save_categories' ) );
		add_action( 'wp_ajax_replyan_ai_get_categories', array( $this, 'ajax_get_categories' ) );
		add_action( 'wp_ajax_replyan_ai_get_insight', array( $this, 'ajax_get_insight' ) );
	}

	public static function get_categories(): array {
		$categories = get_option( self::OPTION_CATEGORIES, false );
		if ( false === $categories || ! is_array( $categories ) ) {
			// Initialize default categories
			$categories = array(
				array( 'id' => 'general_inquiry', 'name' => 'General Inquiry', 'enabled' => true ),
				array( 'id' => 'sales',           'name' => 'Sales',           'enabled' => true ),
				array( 'id' => 'support',         'name' => 'Support',         'enabled' => true ),
				array( 'id' => 'billing',         'name' => 'Billing',         'enabled' => true ),
				array( 'id' => 'complaint',       'name' => 'Complaint',       'enabled' => true ),
				array( 'id' => 'other',           'name' => 'Other',           'enabled' => true ),
			);
			update_option( self::OPTION_CATEGORIES, $categories );
		}
		return $categories;
	}

	public static function get_enabled_categories(): array {
		return array_filter( self::get_categories(), function ( $cat ) {
			return ! empty( $cat['enabled'] );
		} );
	}

	public static function save_categories( array $raw_categories ): array {
		$sanitized = array();
		$seen_names = array();

		foreach ( $raw_categories as $cat ) {
			if ( ! is_array( $cat ) ) {
				continue;
			}
			$name = isset( $cat['name'] ) ? trim( sanitize_text_field( wp_unslash( $cat['name'] ) ) ) : '';
			if ( '' === $name ) {
				continue;
			}

			$name_lower = strtolower( $name );
			if ( in_array( $name_lower, $seen_names, true ) ) {
				continue; // Prevent duplicates
			}
			$seen_names[] = $name_lower;

			$id = isset( $cat['id'] ) ? sanitize_text_field( wp_unslash( $cat['id'] ) ) : sanitize_title( $name );
			if ( '' === $id ) {
				$id = sanitize_title( $name );
			}

			$sanitized[] = array(
				'id'          => $id,
				'name'        => $name,
				'description' => isset( $cat['description'] ) ? sanitize_textarea_field( wp_unslash( $cat['description'] ) ) : '',
				'enabled'     => ! empty( $cat['enabled'] ),
				'badge_color' => isset( $cat['badge_color'] ) ? sanitize_hex_color( $cat['badge_color'] ) : '#1677ff',
			);
		}

		update_option( self::OPTION_CATEGORIES, $sanitized );
		return $sanitized;
	}

	public function ajax_get_categories(): void {
		check_ajax_referer( 'replyan_ai_admin_settings', 'nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( 'message' => 'Unauthorized' ), 403 );
		}

		wp_send_json_success( array( 'categories' => self::get_categories() ) );
	}

	public function ajax_save_categories(): void {
		check_ajax_referer( 'replyan_ai_admin_settings', 'nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( 'message' => 'Unauthorized' ), 403 );
		}

		// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized, WordPress.Security.ValidatedSanitizedInput.MissingUnslash
		$raw_categories = isset( $_POST['categories'] ) ? json_decode( wp_unslash( $_POST['categories'] ), true ) : array();

		if ( ! is_array( $raw_categories ) ) {
			wp_send_json_error( array( 'message' => 'Invalid data format' ), 400 );
		}

		$saved = self::save_categories( $raw_categories );

		wp_send_json_success( array( 'categories' => $saved ) );
	}

	public function ajax_get_insight(): void {
		check_ajax_referer( 'replyan_ai_admin_messages', 'nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( 'message' => 'Unauthorized' ), 403 );
		}

		$session_id = isset( $_POST['session_id'] ) ? sanitize_text_field( wp_unslash( $_POST['session_id'] ) ) : '';

		if ( empty( $session_id ) ) {
			wp_send_json_error( array( 'message' => 'Missing session_id' ), 400 );
		}

		global $wpdb;
		$table_name = $wpdb->prefix . 'replyan_ai_conversation_insights';

		// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter
		$insight = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$table_name} WHERE session_id = %s", $session_id ), ARRAY_A );
		// phpcs:enable

		wp_send_json_success( array( 'insight' => $insight ) );
	}

	/**
	 * Create or update the conversation insights table.
	 */
	public static function create_table(): void {
		global $wpdb;

		$charset_collate = $wpdb->get_charset_collate();
		$table_name      = $wpdb->prefix . 'replyan_ai_conversation_insights';

		$sql = "CREATE TABLE {$table_name} (
			id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
			session_id VARCHAR(64) NOT NULL,
			category TEXT,
			purpose TEXT,
			sentiment VARCHAR(50),
			sentiment_score DECIMAL(3,2),
			emotion VARCHAR(50),
			priority VARCHAR(50),
			summary TEXT,
			created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
			updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
			PRIMARY KEY (id),
			UNIQUE KEY session_id (session_id)
		) {$charset_collate};";

		require_once ABSPATH . 'wp-admin/includes/upgrade.php';
		dbDelta( $sql );
	}

	/**
	 * Save or update a conversation insight record for a session (UPSERT).
	 *
	 * @param string $session_id The unique session identifier.
	 * @param array  $data       Associative array of insights data.
	 * @return int|false Number of rows affected, or false on error.
	 */
	public static function save_or_update( string $session_id, array $data ) {
		global $wpdb;

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

		$table_name = $wpdb->prefix . 'replyan_ai_conversation_insights';
		$current_time = current_time( 'mysql' );

		// sanitize incoming data
		$category        = isset( $data['category'] ) ? sanitize_textarea_field( $data['category'] ) : '';
		$purpose         = isset( $data['purpose'] ) ? sanitize_textarea_field( $data['purpose'] ) : '';
		$sentiment       = isset( $data['sentiment'] ) ? sanitize_text_field( $data['sentiment'] ) : '';
		$sentiment_score = isset( $data['sentiment_score'] ) ? floatval( $data['sentiment_score'] ) : null;
		$emotion         = isset( $data['emotion'] ) ? sanitize_text_field( $data['emotion'] ) : '';
		$priority        = isset( $data['priority'] ) ? sanitize_text_field( $data['priority'] ) : '';
		$summary         = isset( $data['summary'] ) ? sanitize_textarea_field( $data['summary'] ) : '';

		// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
		$replaced = $wpdb->replace(
			$table_name,
			array(
				'session_id'      => $session_id,
				'category'        => $category,
				'purpose'         => $purpose,
				'sentiment'       => $sentiment,
				'sentiment_score' => $sentiment_score,
				'emotion'         => $emotion,
				'priority'        => $priority,
				'summary'         => $summary,
				'updated_at'      => $current_time,
			),
			array(
				'%s', // session_id
				'%s', // category
				'%s', // purpose
				'%s', // sentiment
				'%f', // sentiment_score
				'%s', // emotion
				'%s', // priority
				'%s', // summary
				'%s', // updated_at
			)
		);
	}
}
