<?php
/**
 * Notes (Premium Module)
 *
 * @package Replyan_AI
 */

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

final class Replyan_AI_Notes {
	public function register_hooks(): void {
		add_action( 'wp_ajax_replyan_ai_get_notes', array( $this, 'get_notes' ) );
		add_action( 'wp_ajax_replyan_ai_add_note', array( $this, 'add_note' ) );
	}

	/**
	 * Create the notes table.
	 */
	public static function create_table(): void {
		global $wpdb;
		$charset_collate = $wpdb->get_charset_collate();
		$table           = $wpdb->prefix . 'replyan_ai_notes';

		$sql = "CREATE TABLE {$table} (
			id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
			session_id VARCHAR(64) NOT NULL,
			author VARCHAR(255) NOT NULL,
			text LONGTEXT NOT NULL,
			created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
			PRIMARY KEY  (id),
			KEY session_id (session_id),
			KEY created_at (created_at)
		) {$charset_collate};";

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

	/**
	 * Get notes for a session.
	 *
	 * @param string $session_id Session identifier.
	 * @return array
	 */
	public static function db_get_notes( string $session_id ): array {
		global $wpdb;
		$table = $wpdb->prefix . 'replyan_ai_notes';
		// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
		$notes = $wpdb->get_results(
			$wpdb->prepare( "SELECT * FROM {$table} WHERE session_id = %s ORDER BY created_at ASC", $session_id ),
			ARRAY_A
		);
		// phpcs:enable

		return $notes ?: array();
	}

	/**
	 * Add a note for a session.
	 *
	 * @param string $session_id Session identifier.
	 * @param string $author     Author name.
	 * @param string $text       Note text.
	 * @return array|false The saved note array or false.
	 */
	public static function db_add_note( string $session_id, string $author, string $text ) {
		global $wpdb;
		$table      = $wpdb->prefix . 'replyan_ai_notes';
		$created_at = current_time( 'mysql' );

		// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
		$inserted = $wpdb->insert(
			$table,
			array(
				'session_id' => $session_id,
				'author'     => $author,
				'text'       => $text,
				'created_at' => $created_at,
			)
		);
		// phpcs:enable

		if ( $inserted ) {
			return array(
				'id'         => $wpdb->insert_id,
				'session_id' => $session_id,
				'author'     => $author,
				'text'       => $text,
				'created_at' => $created_at,
			);
		}

		return false;
	}

	public function get_notes(): 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 = sanitize_text_field( wp_unslash( $_POST['session_id'] ?? '' ) );
		if ( empty( $session_id ) ) {
			wp_send_json_error( array( 'message' => 'Missing session' ) );
		}

		$notes = self::db_get_notes( $session_id );
		wp_send_json_success( array( 'notes' => $notes ) );
	}

	public function add_note(): 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 = sanitize_text_field( wp_unslash( $_POST['session_id'] ?? '' ) );
		$content    = sanitize_textarea_field( wp_unslash( $_POST['content'] ?? '' ) );

		if ( empty( $session_id ) || empty( $content ) ) {
			wp_send_json_error( array( 'message' => 'Missing data' ) );
		}

		$current_user = wp_get_current_user();
		$author = $current_user->exists() ? $current_user->display_name : 'Agent';

		$note = self::db_add_note( $session_id, $author, $content );
		if ( $note ) {
			wp_send_json_success( $note );
		} else {
			wp_send_json_error( array( 'message' => 'Failed to save note' ) );
		}
	}
}
