<?php
/**
 * Tenants List Endpoint (Super Admin Only)
 */

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

$decoded = AuthMiddleware::check();

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

$db = Database::getInstance();

try {
    $stmt = $db->query("
        SELECT t.id, t.name, t.email, t.phone, t.status, t.created_at,
               (SELECT COUNT(*) FROM companies WHERE tenant_id = t.id) as companies_count,
               (SELECT COUNT(*) FROM invoices WHERE tenant_id = t.id) as invoices_count
        FROM tenants t 
        ORDER BY t.created_at DESC
    ");
    $tenants = $stmt->fetchAll();

    foreach ($tenants as &$t) {
        $decName = \App\Core\Encryption::decrypt($t['name']);
        $t['name'] = $decName !== false ? $decName : $t['name'];

        $decEmail = \App\Core\Encryption::decrypt($t['email']);
        $t['email'] = $decEmail !== false ? $decEmail : $t['email'];
    }

    json_success($tenants);

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