<?php
/**
 * Tenant Aggregated Stats Endpoint (Super Admin Only)
 */

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

$decoded = AuthMiddleware::check();

if ($decoded['role'] !== 'super_admin') {
    json_error('Unauthorized', 403);
}

$tenantId = $_GET['tenant_id'] ?? null;
if (!$tenantId) {
    json_error('Missing tenant_id', 400);
}

$db = Database::getInstance();

try {
    // 1. Overall Stats
    $stmt = $db->prepare("
        SELECT 
            COUNT(DISTINCT c.id) as total_companies,
            COUNT(i.id) as total_invoices,
            SUM(i.grand_total) as total_amount,
            SUM(i.tax_amount) as total_tax
        FROM companies c
        LEFT JOIN invoices i ON c.id = i.company_id AND i.deleted_at IS NULL
        WHERE c.tenant_id = ? AND c.deleted_at IS NULL
    ");
    $stmt->execute([$tenantId]);
    $summary = $stmt->fetch();

    // 2. Monthly breakdown
    $stmt = $db->prepare("
        SELECT 
            DATE_FORMAT(i.invoice_date, '%Y-%m') as month,
            COUNT(*) as total_invoices,
            SUM(i.tax_amount) as total_tax,
            SUM(i.grand_total) as total_amount
        FROM invoices i
        WHERE i.tenant_id = ? AND i.deleted_at IS NULL
        GROUP BY month
        ORDER BY month DESC
        LIMIT 12
    ");
    $stmt->execute([$tenantId]);
    $monthly = $stmt->fetchAll();

    json_success([
        'summary' => $summary,
        'monthly' => $monthly
    ]);

} catch (\Exception $e) {
    json_error('Stats Error: ' . $e->getMessage(), 500);
}
