<?php

namespace WPSN\Modules\AIReadiness;

defined('ABSPATH') || exit;

/**
 * DB installer for aggregated Bot Blocker stats.
 */
final class BotBlockStatsInstaller
{
    private const DB_VERSION = 1;
    private const OPTION_NAME = 'wpsn_ai_botblock_stats_db_version';

    public static function maybeInstall(): void
    {
        $installed = (int) get_option(self::OPTION_NAME, 0);
        if ($installed >= self::DB_VERSION) {
            return;
        }

        self::install();
    }

    public static function install(): void
    {
        global $wpdb;

        require_once ABSPATH . 'wp-admin/includes/upgrade.php';

        $table = $wpdb->prefix . 'wpsn_ai_botblock_stats';
        $charset = $wpdb->get_charset_collate();

        // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
        $sql = "CREATE TABLE {$table} (
            id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
            day date NOT NULL,
            bot_key varchar(64) NOT NULL,
            bot_label varchar(190) NOT NULL,
            hits bigint(20) unsigned NOT NULL DEFAULT 0,
            last_seen datetime NULL,
            last_path text NULL,
            last_user_agent varchar(255) NULL,
            PRIMARY KEY  (id),
            UNIQUE KEY day_bot (day, bot_key),
            KEY bot_day (bot_key, day),
            KEY day (day),
            KEY last_seen (last_seen)
        ) {$charset};";

        dbDelta($sql);

        update_option(self::OPTION_NAME, self::DB_VERSION, false);
    }
}
