<?php

/**
 * LolaCore — Hub Action Log Reader
 *
 * @package LolaCore
 * @license GPL-2.0-or-later
 */

declare(strict_types=1);

namespace LolaCore\Hub;

// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared -- Custom LolaCore table queries with validated inputs.

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Reads wp_lolacore_log entries whose provenance is a LolaHub master (source LIKE hub:%).
 */
final class HubActionLogReader
{
    /**
     * @return array{entries: array<int, array<string, mixed>>, total: int}
     */
    public function getEntries(int $page = 1, int $perPage = 20, string $search = ''): array
    {
        global $wpdb;

        $page    = max(1, $page);
        $perPage = max(1, min(100, $perPage));
        $offset  = ($page - 1) * $perPage;
        $table   = $wpdb->prefix . 'lolacore_log';

        $where  = "source LIKE 'hub:%'";
        $params = [];

        $search = trim($search);
        if ($search !== '') {
            $like     = '%' . $wpdb->esc_like($search) . '%';
            $where   .= ' AND (description LIKE %s OR action_type LIKE %s OR source LIKE %s)';
            $params[] = $like;
            $params[] = $like;
            $params[] = $like;
        }

        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
        $countSql = "SELECT COUNT(*) FROM {$table} WHERE {$where}";
        if ($params !== []) {
            // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
            $total = (int) $wpdb->get_var($wpdb->prepare($countSql, ...$params));
        } else {
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
            $total = (int) $wpdb->get_var($countSql);
        }

        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
        $query = "SELECT id, action_type, description, status, source, executed_at
                  FROM {$table}
                  WHERE {$where}
                  ORDER BY executed_at DESC
                  LIMIT %d OFFSET %d";

        $listParams   = $params;
        $listParams[] = $perPage;
        $listParams[] = $offset;

        // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
        $entries = $wpdb->get_results($wpdb->prepare($query, ...$listParams), ARRAY_A);

        return [
            'entries' => is_array($entries) ? $entries : [],
            'total'   => $total,
        ];
    }
}
