<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Token/cost bookkeeping in the plugin's own usage table.
 *
 * phpcs:disable WordPress.DB.DirectDatabaseQuery -- the class manages the
 * plugin's custom table, which core APIs and object caching do not cover.
 */
class Arcai_Usage {

	public static function log( $event_type, $tokens_in, $tokens_out, $cost ) {
		global $wpdb;
		$wpdb->insert(
			$wpdb->prefix . 'arcai_usage',
			array(
				'created_at' => current_time( 'mysql' ),
				'event_type' => $event_type,
				'tokens_in'  => (int) $tokens_in,
				'tokens_out' => (int) $tokens_out,
				'cost'       => (float) $cost,
			),
			array( '%s', '%s', '%d', '%d', '%f' )
		);
	}

	public static function cost_today() {
		global $wpdb;
		$midnight = gmdate( 'Y-m-d 00:00:00', current_time( 'timestamp' ) );
		return (float) $wpdb->get_var(
			$wpdb->prepare(
				"SELECT COALESCE(SUM(cost), 0) FROM {$wpdb->prefix}arcai_usage WHERE created_at >= %s",
				$midnight
			)
		);
	}

	public static function summary( $days = 30 ) {
		global $wpdb;
		$since = gmdate( 'Y-m-d 00:00:00', current_time( 'timestamp' ) - $days * DAY_IN_SECONDS );
		return $wpdb->get_results(
			$wpdb->prepare(
				"SELECT event_type, COUNT(*) AS events, SUM(tokens_in) AS tokens_in, SUM(tokens_out) AS tokens_out, SUM(cost) AS cost
				 FROM {$wpdb->prefix}arcai_usage WHERE created_at >= %s GROUP BY event_type",
				$since
			)
		);
	}

	public static function over_daily_cap() {
		$cap = (float) Arcai_Settings::get( 'daily_cap' );
		if ( $cap <= 0 ) {
			return false;
		}
		return self::cost_today() >= $cap;
	}
}
