<?php
/**
 * Repository responsible for persisting notification events.
 *
 * @package StockGuardianPro
 */

declare(strict_types=1);

namespace StockGuardianPro\LowStock\Services;

use DateTimeImmutable;
use DateTimeZone;
use StockGuardianPro\LowStock\Plugin;

\defined('ABSPATH') || exit;

final class EventRepository implements ServiceInterface
{
    private Plugin $plugin;

    public function __construct(Plugin $plugin)
    {
        $this->plugin = $plugin;
    }

    public function register(): void
    {
    }

    public function log_event(
        int $product_id,
        int $variation_id,
        string $product_name,
        int $stock,
        int $threshold,
        string $channel = 'email'
    ): void {
        global $wpdb;

        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
        $table = $wpdb->prefix . 'low_stock_events';
        $now = new DateTimeImmutable('now', new DateTimeZone(wp_timezone_string()));

        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
        $wpdb->insert(
            $table,
            [
                'product_id'   => $product_id,
                'variation_id' => $variation_id,
                'product_name' => $product_name,
                'stock'        => $stock,
                'threshold'    => $threshold,
                'channel'      => $channel,
                'notified_at'  => $now->format('Y-m-d H:i:s'),
            ],
            [
                '%d',
                '%d',
                '%s',
                '%d',
                '%d',
                '%s',
                '%s',
            ]
        );
    }

    public function count_recent(int $seconds = DAY_IN_SECONDS): int
    {
        global $wpdb;

        // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, PluginCheck.Security.DirectDB.UnescapedDBParameter
        $table = $wpdb->prefix . 'low_stock_events';
        $since = gmdate('Y-m-d H:i:s', time() - $seconds);

        $count = $wpdb->get_var(
            $wpdb->prepare(
                "SELECT COUNT(*) FROM {$table} WHERE notified_at >= %s",
                $since
            )
        );
        // phpcs:enable

        return (int) $count;
    }

    /**
     * @return array<int, array<string, mixed>>
     */
    public function latest_events(int $limit = 10): array
    {
        global $wpdb;

        // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, PluginCheck.Security.DirectDB.UnescapedDBParameter
        $table = $wpdb->prefix . 'low_stock_events';

        $results = $wpdb->get_results(
            $wpdb->prepare(
                "SELECT product_id, variation_id, product_name, stock, threshold, channel, notified_at
                 FROM {$table}
                 ORDER BY notified_at DESC
                 LIMIT %d",
                (int) $limit
            ),
            ARRAY_A
        );
        // phpcs:enable

        return $results ?? [];
    }

    public function truncate_all(): void
    {
        global $wpdb;

        // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, PluginCheck.Security.DirectDB.UnescapedDBParameter
        $table = $wpdb->prefix . 'low_stock_events';
        $wpdb->query("DELETE FROM {$table}");
        // phpcs:enable
    }
}

