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

/**
 * Handles Usage Tracking and Logging
 */
class Podcastmaker_Usage_Tracker {

private $table_name;

public function __construct() {
global $wpdb;
$this->table_name = $wpdb->prefix . 'podcastmaker_usage_logs';
}

/**
 * Log usage event
 */
public function log_usage( $user_id, $action_type, $model_used, $char_count = 0, $duration = 0, $cost = 0.0 ) {
global $wpdb;

// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
$wpdb->insert(
$this->table_name,
array(
'user_id'        => $user_id,
'action_type'    => $action_type,
'model_used'     => $model_used,
'char_count'     => $char_count,
'duration'       => $duration,
'cost_estimated' => $cost,
'created_at'     => current_time( 'mysql' )
),
array( '%d', '%s', '%s', '%d', '%d', '%f', '%s' )
);
}

/**
 * Calculate Estimated Cost (Simple heuristic)
 */
public static function calculate_cost( $model, $char_count, $duration_seconds ) {
$cost = 0.0;

if ( strpos( $model, 'pro' ) !== false && strpos( $model, 'tts' ) === false ) {
$cost += ( $char_count / 1000000 ) * 3.50;
} elseif ( strpos( $model, 'flash' ) !== false && strpos( $model, 'tts' ) === false ) {
$cost += ( $char_count / 1000000 ) * 0.10;
}

if ( strpos( $model, 'tts' ) !== false ) {
$cost += ( $char_count / 1000000 ) * 16.00;
}

return round( $cost, 6 );
}

/**
 * Get logs for a specific user
 */
public function get_user_logs( $user_id, $limit = 50 ) {
global $wpdb;

$user_id = absint( $user_id );
$limit   = absint( $limit );
if ( $limit < 1 ) {
$limit = 1;
}

$table = $this->table_name;

// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
$sql = "SELECT * FROM {$table} WHERE user_id = %d ORDER BY created_at DESC LIMIT %d";

// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared
$results = $wpdb->get_results( $wpdb->prepare( $sql, $user_id, $limit ) );

return $results;
}

/**
 * Get global logs (Admin view)
 *
 * @param bool $mask_users If true, replace user display names with 'some_user'
 */
public function get_global_logs( $limit = 100, $mask_users = true ) {
global $wpdb;

$limit = absint( $limit );
if ( $limit < 1 ) {
$limit = 1;
}

$table = $this->table_name;

// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
$sql = "SELECT * FROM {$table} ORDER BY created_at DESC LIMIT %d";

// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared
$results = $wpdb->get_results( $wpdb->prepare( $sql, $limit ) );

if ( $results ) {
foreach ( $results as $row ) {
if ( $mask_users ) {
$row->user_display_name = 'some_user';
continue;
}
$user_info              = get_userdata( $row->user_id );
$row->user_display_name = $user_info ? $user_info->display_name : 'Unknown';
}
}

return $results;
}

/**
 * Get Aggregated Stats
 */
public function get_stats( $user_id = null, $period = 'total' ) {
global $wpdb;

$month_start = gmdate( 'Y-m-01 00:00:00' );
$table       = $this->table_name;

if ( $period === 'month' && $user_id ) {

// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
$sql  = "SELECT SUM(cost_estimated) AS total_cost, SUM(char_count) AS total_chars, SUM(duration) AS total_duration FROM {$table} WHERE user_id = %d AND created_at >= %s";
$args = array( absint( $user_id ), $month_start );

} elseif ( $period === 'month' ) {

// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
$sql  = "SELECT SUM(cost_estimated) AS total_cost, SUM(char_count) AS total_chars, SUM(duration) AS total_duration FROM {$table} WHERE created_at >= %s";
$args = array( $month_start );

} elseif ( $user_id ) {

// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
$sql  = "SELECT SUM(cost_estimated) AS total_cost, SUM(char_count) AS total_chars, SUM(duration) AS total_duration FROM {$table} WHERE user_id = %d";
$args = array( absint( $user_id ) );

} else {

// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
$sql  = "SELECT SUM(cost_estimated) AS total_cost, SUM(char_count) AS total_chars, SUM(duration) AS total_duration FROM {$table} WHERE 1 = %d";
$args = array( 1 );
}

// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
$prepared = $wpdb->prepare( $sql, ...$args );

// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared
$row = $wpdb->get_row( $prepared );

return array(
'cost'     => ( $row && isset( $row->total_cost ) && $row->total_cost ) ? (float) $row->total_cost : 0,
'chars'    => ( $row && isset( $row->total_chars ) && $row->total_chars ) ? (int) $row->total_chars : 0,
'duration' => ( $row && isset( $row->total_duration ) && $row->total_duration ) ? (int) $row->total_duration : 0,
);
}
}