class-restai-analytics.php
1 <?php 2 /** 3 * Lightweight analytics card surfaced in the dashboard widget area. 4 * 5 * @package RESTai 6 */ 7 8 namespace RESTai; 9 10 if ( ! defined( 'ABSPATH' ) ) { 11 exit; 12 } 13 14 class Analytics { 15 16 /** @var Client */ 17 private $client; 18 19 public function __construct( Client $client ) { 20 $this->client = $client; 21 add_action( 'wp_dashboard_setup', array( $this, 'register_widget' ) ); 22 } 23 24 public function register_widget() { 25 if ( ! current_user_can( 'manage_options' ) ) { 26 return; 27 } 28 wp_add_dashboard_widget( 29 'restai_dashboard', 30 __( 'RESTai usage (last 30 days)', 'restai' ), 31 array( $this, 'render' ) 32 ); 33 } 34 35 public function render() { 36 if ( ! Plugin::is_connected() ) { 37 echo '<p>'; 38 printf( 39 /* translators: %s settings link */ 40 esc_html__( 'Not connected. Configure RESTai in %s.', 'restai' ), 41 '<a href="' . esc_url( admin_url( 'options-general.php?page=restai' ) ) . '">Settings → RESTai</a>' 42 ); 43 echo '</p>'; 44 return; 45 } 46 $tokens = $this->client->get( 'statistics/daily-tokens?days=30' ); 47 if ( is_wp_error( $tokens ) ) { 48 echo '<p>' . esc_html( $tokens->get_error_message() ) . '</p>'; 49 return; 50 } 51 $rows = isset( $tokens['tokens'] ) ? $tokens['tokens'] : array(); 52 $total_in = 0; 53 $total_out = 0; 54 $cost = 0.0; 55 foreach ( $rows as $r ) { 56 $total_in += isset( $r['input'] ) ? (int) $r['input'] : 0; 57 $total_out += isset( $r['output'] ) ? (int) $r['output'] : 0; 58 $cost += isset( $r['cost'] ) ? (float) $r['cost'] : 0.0; 59 } 60 echo '<ul>'; 61 echo '<li><strong>' . esc_html__( 'Input tokens:', 'restai' ) . '</strong> ' . esc_html( number_format_i18n( $total_in ) ) . '</li>'; 62 echo '<li><strong>' . esc_html__( 'Output tokens:', 'restai' ) . '</strong> ' . esc_html( number_format_i18n( $total_out ) ) . '</li>'; 63 echo '<li><strong>' . esc_html__( 'Cost:', 'restai' ) . '</strong> ' . esc_html( number_format_i18n( $cost, 3 ) ) . '</li>'; 64 echo '</ul>'; 65 echo '<p><a href="' . esc_url( admin_url( 'admin.php?page=restai-analytics' ) ) . '">' . esc_html__( 'Full analytics →', 'restai' ) . '</a></p>'; 66 } 67 }