<?php
if ( ! defined( 'ABSPATH' ) ) { exit; }
if ( class_exists( 'Truebe_Audit' ) ) { return; }

class Truebe_Audit {

	private static function table() {
		global $wpdb;
		return $wpdb->prefix . 'truebe_audit_log';
	}

	public static function install() {
		global $wpdb;
		$table   = self::table();
		$collate = $wpdb->get_charset_collate();

		$sql = "CREATE TABLE {$table} (
			id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
			seed_id BIGINT UNSIGNED NULL,
			question TEXT NULL,
			action VARCHAR(40) NOT NULL,
			approver VARCHAR(190) NOT NULL,
			created_at DATETIME NOT NULL,
			PRIMARY KEY (id),
			KEY seed_id (seed_id),
			KEY action (action),
			KEY created_at (created_at)
		) {$collate};";

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

	public static function log( $seed_id, $question, $action, $approver = '' ) {
		global $wpdb;
		if ( '' === $approver ) {
			$user     = wp_get_current_user();
			$approver = $user && $user->exists() ? $user->display_name : __( 'System', 'truebe-fact-based-ai-chatbot' );
		}
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- custom plugin table; $wpdb->insert() is the supported API and there is no object cache for this row.
		$wpdb->insert(
			self::table(),
			array(
				'seed_id'    => $seed_id ? absint( $seed_id ) : null,
				'question'   => sanitize_text_field( (string) $question ),
				'action'     => sanitize_key( $action ),
				'approver'   => sanitize_text_field( $approver ),
				'created_at' => current_time( 'mysql' ),
			)
		);
	}

	public static function get_page( $page = 1, $per_page = 25 ) {
		global $wpdb;
		$table  = self::table();
		$offset = max( 0, ( max( 1, (int) $page ) - 1 ) * $per_page );
		// phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, PluginCheck.Security.DirectDB.UnescapedDBParameter -- {$table} is built from $wpdb->prefix plus a fixed string (no user input); SQL identifiers cannot be passed as prepare() parameters. Custom plugin table, no core API or object cache.
		return $wpdb->get_results(
			$wpdb->prepare(
				"SELECT id, seed_id, question, action, approver, created_at
				 FROM {$table} ORDER BY id DESC LIMIT %d OFFSET %d",
				max( 1, (int) $per_page ),
				$offset
			),
			ARRAY_A
		);
		// phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, PluginCheck.Security.DirectDB.UnescapedDBParameter
	}

	public static function count() {
		global $wpdb;
		$table = self::table();
		// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, PluginCheck.Security.DirectDB.UnescapedDBParameter -- {$table} is built from $wpdb->prefix plus a fixed string (no user input). Custom plugin table, no core API or object cache.
		return (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$table}" );
	}

	public static function get_all_for_export() {
		global $wpdb;
		$table = self::table();
		// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, PluginCheck.Security.DirectDB.UnescapedDBParameter -- {$table} is built from $wpdb->prefix plus a fixed string (no user input). Custom plugin table, no core API or object cache.
		return $wpdb->get_results( "SELECT seed_id, question, action, approver, created_at FROM {$table} ORDER BY id DESC LIMIT 10000", ARRAY_A );
	}
}