<?php
/**
 * Database interaction functions for the download logs.
 *
 * @package email-gated-downloads
 */

defined('ABSPATH') || exit;

/**
 * Get download logs with optional filtering and pagination.
 *
 * @param string $filter_file_log The file name to filter logs by.
 * @param int    $per_page_logs   The number of logs to retrieve per page.
 * @param int    $paged_logs      The current page number.
 * @return array The log results.
 */
function spdfed_get_logs(string $filter_file_log = '', int $per_page_logs = 20, int $paged_logs = 1): array {
    global $wpdb;
    $offset_logs = ($paged_logs - 1) * $per_page_logs;

    if (!empty($filter_file_log)) {
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.DirectQuery
        $results = $wpdb->get_results($wpdb->prepare(
            "SELECT submitter_name, email, file_name, downloaded_at FROM `{$wpdb->prefix}spdfed_logs` WHERE file_name = %s ORDER BY downloaded_at DESC LIMIT %d OFFSET %d",
            $filter_file_log,
            $per_page_logs,
            $offset_logs
        ));
    } else {
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.DirectQuery
        $results = $wpdb->get_results($wpdb->prepare(
            "SELECT submitter_name, email, file_name, downloaded_at FROM `{$wpdb->prefix}spdfed_logs` ORDER BY downloaded_at DESC LIMIT %d OFFSET %d",
            $per_page_logs,
            $offset_logs
        ));
    }

    return $results;
}

/**
 * Get the total count of download logs with optional filtering.
 *
 * @param string $filter_file_log The file name to filter logs by.
 * @return int The total number of rows.
 */
function spdfed_get_logs_count(string $filter_file_log = ''): int {
    global $wpdb;

    if (!empty($filter_file_log)) {
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.DirectQuery
        $count = (int) $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM `{$wpdb->prefix}spdfed_logs` WHERE file_name = %s", $filter_file_log));
    } else {
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.DirectQuery
        $count = (int) $wpdb->get_var("SELECT COUNT(*) FROM `{$wpdb->prefix}spdfed_logs`");
    }

    return $count;
}

/**
 * Get a list of distinct file names from the download logs.
 *
 * @return array An array of file names.
 */
function spdfed_get_distinct_log_files(): array {
    global $wpdb;

    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.DirectQuery
    $files = $wpdb->get_col("SELECT DISTINCT file_name FROM `{$wpdb->prefix}spdfed_logs` ORDER BY file_name ASC");

    return $files;
} 