<?php
/**
 * Detailed Usage Statistics (for Charts/Stats)
 * GET /api/v1/subscriptions/usage
 */

use App\Core\Database;
use App\Middleware\AuthMiddleware;

$decoded = AuthMiddleware::check();
$tenantId = $decoded['tenant_id'];

$db = Database::getInstance();

try {
    // 1. Monthly growth (Invoices over last 6 months)
    $stmt = $db->prepare("
        SELECT DATE_FORMAT(created_at, '%Y-%m') as month, COUNT(*) as count
        FROM invoices
        WHERE tenant_id = ? AND created_at >= DATE_SUB(NOW(), INTERVAL 6 MONTH)
        GROUP BY month
        ORDER BY month ASC
    ");
    $stmt->execute([$tenantId]);
    $monthlyInvoices = $stmt->fetchAll();

    // 2. Usage by company
    $stmt = $db->prepare("
        SELECT c.name, COUNT(i.id) as count
        FROM companies c
        LEFT JOIN invoices i ON i.company_id = c.id
        WHERE c.tenant_id = ? AND c.deleted_at IS NULL
        GROUP BY c.id
        ORDER BY count DESC
    ");
    $stmt->execute([$tenantId]);
    $usageByCompany = $stmt->fetchAll();

    // 3. Status distribution
    $stmt = $db->prepare("
        SELECT status, COUNT(*) as count
        FROM invoices
        WHERE tenant_id = ?
        GROUP BY status
    ");
    $stmt->execute([$tenantId]);
    $statusDistribution = $stmt->fetchAll();

    json_success([
        'monthly_growth'     => $monthlyInvoices,
        'usage_by_company'   => $usageByCompany,
        'status_distribution' => $statusDistribution
    ], 'إحصائيات الاستهلاك');

} catch (\Exception $e) {
    error_log("Usage Stats Error: " . $e->getMessage());
    json_error('حدث خطأ أثناء جلب إحصائيات الاستهلاك', 500);
}
