<?php
/**
 * Client access helpers — included by every API that needs client filtering.
 * Safe to include multiple times (functions are defined once).
 */

if (!function_exists('is_admin')) {
    function is_admin(array $user): bool {
        return (int)$user['user_type_id'] === 1;
    }
}

if (!function_exists('allowed_clients')) {
    function allowed_clients(array $user): ?array {
        if (is_admin($user)) return null;
        $ids = array_values(array_filter(array_map('intval',
            explode(',', $user['clients_multi'] ?? '')
        )));
        return $ids ?: [-1];
    }
}

if (!function_exists('client_where')) {
    function client_where(array $user, string $col = 'clients_id'): array {
        $ids = allowed_clients($user);
        if ($ids === null) return ['1=1', []];
        if (empty($ids))   return ['1=0', []];
        $ph = implode(',', array_fill(0, count($ids), '?'));
        return ["$col IN ($ph)", $ids];
    }
}