<?php
/**
 * Dashboard Stats Endpoint (Role-Based & Tenant-Aware)
 */

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

// 1. Auth Check
$decoded = AuthMiddleware::check();
$db = Database::getInstance();

$tenantId = $decoded['tenant_id'] ?? null;
$companyId = $decoded['company_id'] ?? null;
$role = $decoded['role'];

try {
    $stats = [
        'role' => $role,
        'invoices' => [
            'total' => 0,
            'pending' => 0,
            'approved' => 0
        ]
    ];

    // 2. Fetch Invoice Stats
    if ($role === 'super_admin') {
        $where = "WHERE 1=1";
        $params = [];
    } elseif ($role === 'accountant' || $role === 'viewer') {
        $where = "WHERE tenant_id = ? AND company_id = ?";
        $params = [$tenantId, $companyId];
    } else {
        // admin
        $where = "WHERE tenant_id = ?";
        $params = [$tenantId];
    }

    $stmt = $db->prepare("SELECT COUNT(*) FROM invoices $where");
    $stmt->execute($params);
    $stats['invoices']['total'] = (int)$stmt->fetchColumn();

    $stmt = $db->prepare("SELECT COUNT(*) FROM invoices $where AND status = 'extracted'");
    $stmt->execute($params);
    $stats['invoices']['pending'] = (int)$stmt->fetchColumn();

    $stmt = $db->prepare("SELECT COUNT(*) FROM invoices $where AND status = 'approved'");
    $stmt->execute($params);
    $stats['invoices']['approved'] = (int)$stmt->fetchColumn();

    // 3. Role-Specific Extra Stats
    if ($role === 'super_admin') {
        $stats['tenants'] = (int)$db->query("SELECT COUNT(*) FROM tenants")->fetchColumn();
        $stats['total_users'] = (int)$db->query("SELECT COUNT(*) FROM users")->fetchColumn();
    } elseif ($role === 'admin') {
        $stmt = $db->prepare("SELECT COUNT(*) FROM companies WHERE tenant_id = ?");
        $stmt->execute([$tenantId]);
        $stats['companies'] = (int)$stmt->fetchColumn();

        $stmt = $db->prepare("SELECT COUNT(*) FROM users WHERE tenant_id = ?");
        $stmt->execute([$tenantId]);
        $stats['users'] = (int)$stmt->fetchColumn();

        // Get Subscription Quota
        $stmt = $db->prepare("SELECT max_invoices_per_month, invoices_used_this_month FROM subscriptions WHERE tenant_id = ?");
        $stmt->execute([$tenantId]);
        $sub = $stmt->fetch();
        if ($sub) {
            $stats['subscription'] = [
                'limit' => (int)$sub['max_invoices_per_month'],
                'used'  => (int)$sub['invoices_used_this_month']
            ];
        }
    }

} catch (\Exception $e) {
    // Return default zeroed stats on error
}

json_success($stats);
