<?php
/**
 * Users List Endpoint (Role-Based & Tenant-Aware)
 */

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

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

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

try {
    // 2. Build Query based on Role
    if ($role === 'super_admin') {
        // Super Admin sees ALL users from ALL tenants
        $stmt = $db->query("
            SELECT u.id, u.name, u.email, u.role, u.is_active, u.created_at, t.name as tenant_name
            FROM users u
            LEFT JOIN tenants t ON u.tenant_id = t.id
            ORDER BY u.created_at DESC
        ");
    } elseif ($role === 'admin') {
        // Admin sees only users in THEIR tenant (Accounting Office)
        $stmt = $db->prepare("
            SELECT u.id, u.name, u.email, u.role, u.is_active, u.created_at, t.name as tenant_name
            FROM users u
            LEFT JOIN tenants t ON u.tenant_id = t.id
            WHERE u.tenant_id = ?
            ORDER BY u.created_at DESC
        ");
        $stmt->execute([$tenantId]);
    } else {
        // Other roles shouldn't see user list
        json_error('Unauthorized', 403);
    }

    $users = $stmt->fetchAll();

    // 3. Decrypt data and format
    $dec = function($val) {
        if (empty($val)) return '';
        $result = \App\Core\Encryption::decrypt((string)$val);
        return ($result !== false && $result !== null) ? $result : (string)$val;
    };

    foreach ($users as &$user) {
        $user['name'] = $dec($user['name']);
        $user['email'] = $dec($user['email']);
        
        if (!empty($user['tenant_name'])) {
            $user['tenant_name'] = $dec($user['tenant_name']);
        }
    }

    if (empty($users)) {
        error_log("USERS LIST: No users found for role: $role, tenant_id: $tenantId");
    }

    json_success($users);

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