<?php
/**
 * Activity log admin page. Displays every plugin log entry with pagination.
 *
 * @package SuiteMkt3k
 */

namespace SuiteMkt3k\Admin\Pages;

use SuiteMkt3k\Installer;
use SuiteMkt3k\Security\Capabilities;

defined( 'ABSPATH' ) || exit;

final class Activity_Page extends Base_Page {

	protected static string $slug = 'suitemkt3k-activity';
	protected static string $cap  = Capabilities::MANAGE;

	public const PER_PAGE_DEFAULT = 5;

	/** @var int[] */
	public const PER_PAGE_OPTIONS = array( 5, 10, 25, 100 );

	public static function render(): void {
		static::$page_title    = __( 'Activity log', 'suitemkt3k' );
		static::$page_subtitle = __( 'Every event captured by SuiteMkt3k', 'suitemkt3k' );
		parent::render();
	}

	protected static function content(): void {
		global $wpdb;
		$table = Installer::table( 'logs' );
		$per   = self::resolve_per_page();
		$total = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$table}" ); // phpcs:ignore
		$pages = (int) max( 1, (int) ceil( $total / $per ) );
		$paged = (int) filter_input( INPUT_GET, 'paged', FILTER_SANITIZE_NUMBER_INT );
		$paged = $paged > 0 ? $paged : 1;
		$paged = min( max( 1, $paged ), $pages );
		$offset = ( $paged - 1 ) * $per;

		$rows = $wpdb->get_results( $wpdb->prepare( "SELECT level, context, message, created_at FROM {$table} ORDER BY id DESC LIMIT %d OFFSET %d", $per, $offset ), ARRAY_A ); // phpcs:ignore
		$rows = is_array( $rows ) ? $rows : array();

		$per_page_options = self::PER_PAGE_OPTIONS;

		include SUITEMKT3K_PATH . 'includes/admin/views/activity-log.php';
	}

	private static function resolve_per_page(): int {
		$requested = (int) filter_input( INPUT_GET, 'per_page', FILTER_SANITIZE_NUMBER_INT );
		$requested = $requested > 0 ? $requested : self::PER_PAGE_DEFAULT;
		return in_array( $requested, self::PER_PAGE_OPTIONS, true ) ? $requested : self::PER_PAGE_DEFAULT;
	}
}
