<?php
/**
 * سودانا AI Engine — GET /api/engine/usage.php
 * Returns usage stats for current user
 */
require_once __DIR__ . '/../../config.php';
require_once __DIR__ . '/../../engine/Kernel.php';
require_once __DIR__ . '/../engine/Logger.php'; // COVERAGE
require_once '../../engine/AIEngine.php';

$ctx = Kernel::handle(['auth' => true]);
$u   = $ctx['user'];
$userId = (int)$u['id'];

$today = db()->prepare("SELECT COUNT(*) FROM ai_usage WHERE user_id=? AND DATE(created_at)=CURDATE()");
$today->execute([$userId]);

$week = db()->prepare("SELECT COUNT(*) FROM ai_usage WHERE user_id=? AND created_at > DATE_SUB(NOW(), INTERVAL 7 DAY)");
$week->execute([$userId]);

$byType = db()->prepare(
    "SELECT event_type, COUNT(*) as cnt FROM ai_usage WHERE user_id=? AND created_at > DATE_SUB(NOW(), INTERVAL 30 DAY) GROUP BY event_type"
);
$byType->execute([$userId]);

$plan   = $u['plan_key'] ?? 'free';
$limit  = match($plan) { 'pro'=>5000, 'plus'=>500, default=>50 };

json_response([
    'success' => true,
    'plan'    => $plan,
    'limit_day' => $limit,
    'used_today' => (int)$today->fetchColumn(),
    'used_week'  => (int)$week->fetchColumn(),
    'by_type'    => $byType->fetchAll(),
]);
