<?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 users WHERE tenant_id = t.id) as users_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();

    $dec = function($val) {
        if (empty($val)) return '';
        $result = \App\Core\Encryption::decrypt((string)$val);
        return ($result !== false && $result !== null) ? $result : (string)$val;
    };

    foreach ($tenants as &$t) {
        $t['name'] = $dec($t['name']);
        $t['email'] = $dec($t['email']);
        if (!empty($t['phone'])) {
            $t['phone'] = $dec($t['phone']);
        }
    }

    json_success($tenants);

} catch (\Exception $e) {
    safe_error($e, 'tenants/index');
}
