<?php
/**
 * Pro: Audit log.
 *
 * @package TradeSchoolManagerPro
 */

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

/*
 * Manages plugin-owned custom tables ($wpdb->prefix . 'tsm_*'). Direct
 * queries are required; interpolation uses table-name literals only;
 * parameters go through $wpdb->prepare() placeholders. Hooks use the
 * registered `tsm`/`tsmp` prefix.
 */
// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery
// phpcs:disable WordPress.DB.DirectDatabaseQuery.NoCaching
// phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
// phpcs:disable PluginCheck.Security.DirectDB.UnescapedDBParameter

class TSMP_Audit {

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

	public static function log( $action, $object_type, $object_id, $details = array() ) {
		global $wpdb;
		$wpdb->insert(
			self::table(),
			array(
				'user_id'     => get_current_user_id(),
				'action'      => sanitize_text_field( $action ),
				'object_type' => sanitize_text_field( $object_type ),
				'object_id'   => absint( $object_id ),
				'details'     => wp_json_encode( $details ),
			)
		);
	}

	public static function recent( $limit = 200 ) {
		global $wpdb;
		$t = self::table();
		return $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$t} ORDER BY id DESC LIMIT %d", absint( $limit ) ) );
	}

	public static function on_save_grade( $assignment_id, $student_id, $vals, $prev ) {
		if ( ! $prev || (string) ( $prev->points_earned ?? '' ) !== (string) ( $vals['points_earned'] ?? '' ) ) {
			self::log(
				'update', 'grade', $assignment_id,
				array(
					'student_id' => $student_id,
					'old'        => $prev->points_earned ?? null,
					'new'        => $vals['points_earned'] ?? null,
				)
			);
		}
	}

	public static function render_admin() {
		$rows = self::recent( 500 );
		?>
		<h2><?php esc_html_e( 'Audit Log', 'tradeschool-manager' ); ?></h2>
		<table class="widefat striped">
			<thead><tr><th><?php esc_html_e( 'When', 'tradeschool-manager' ); ?></th><th><?php esc_html_e( 'User', 'tradeschool-manager' ); ?></th><th><?php esc_html_e( 'Action', 'tradeschool-manager' ); ?></th><th><?php esc_html_e( 'Object', 'tradeschool-manager' ); ?></th><th><?php esc_html_e( 'Details', 'tradeschool-manager' ); ?></th></tr></thead>
			<tbody>
				<?php foreach ( $rows as $r ) :
					$u = $r->user_id ? get_userdata( $r->user_id ) : null; ?>
					<tr>
						<td><?php echo esc_html( $r->created_at ); ?></td>
						<td><?php echo esc_html( $u ? $u->user_login : ' - ' ); ?></td>
						<td><?php echo esc_html( $r->action ); ?></td>
						<td><?php echo esc_html( $r->object_type . ' #' . $r->object_id ); ?></td>
						<td><code><?php echo esc_html( wp_strip_all_tags( (string) $r->details ) ); ?></code></td>
					</tr>
				<?php endforeach; ?>
				<?php if ( empty( $rows ) ) : ?>
					<tr><td colspan="5"><em><?php esc_html_e( 'No log entries yet.', 'tradeschool-manager' ); ?></em></td></tr>
				<?php endif; ?>
			</tbody>
		</table>
		<?php
	}
}
