<?php
/**
 * Answyr Chat — module wiring.
 *
 * KB + codebase-grounded deflection widget on the shared core. Anything the chat
 * can't resolve escalates into a Desk ticket (transcript attached).
 *
 * Ported from ~/K3Office/Projects/simplyconf/code/simplychat/.
 *
 * @package Answyr
 */

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

// The chat log store is premium-only (@fs_premium_only) — absent from the free
// build, so load it defensively.
$answyr_chat_store = __DIR__ . '/class-chat-store.php';
if ( is_readable( $answyr_chat_store ) ) {
	require_once $answyr_chat_store;
}
require_once __DIR__ . '/class-chat-endpoint.php';
require_once __DIR__ . '/class-chat-widget.php';

final class Answyr_Chat_Module extends Answyr_Module {

	/** Daily cron that prunes chat-log rows past the retention window. */
	private const PRUNE_HOOK = 'answyr_chat_log_prune';

	public function id(): string {
		return 'chat';
	}

	public function label(): string {
		return __( 'Chat', 'answyr' );
	}

	public function register(): void {
		( new Answyr_Chat_Endpoint() )->register();
		( new Answyr_Chat_Widget() )->register();

		// The rest is chat-log (Pro) plumbing — only when the premium store is present.
		if ( ! class_exists( 'Answyr_Chat_Store' ) ) {
			return;
		}

		// Apply any pending schema upgrades (adds the log table without reactivation).
		if ( is_admin() ) {
			Answyr_Chat_Store::maybe_upgrade();
		}

		// Retention: prune old transcripts daily (default 90 days; 0 = keep forever).
		add_action( self::PRUNE_HOOK, array( $this, 'prune_log' ) );
		if ( ! wp_next_scheduled( self::PRUNE_HOOK ) ) {
			wp_schedule_event( time() + HOUR_IN_SECONDS, 'daily', self::PRUNE_HOOK );
		}
	}

	/** Enforce the chat-log retention window. */
	public function prune_log(): void {
		if ( ! class_exists( 'Answyr_Chat_Store' ) ) {
			return;
		}
		$days = (int) Answyr_Settings::get( 'chat_log_retention_days', 90 );
		if ( $days > 0 ) {
			Answyr_Chat_Store::prune( $days );
		}
	}
}
