<?php
declare(strict_types=1);

namespace App\Models;

final class CustomerUser extends BaseModel
{
    protected static string $table = 'customer_users';

    public static function allForTenant(): array
    {
        return static::db()->fetchAll(
            "SELECT c.*, a.name AS account_name
             FROM customer_users c
             INNER JOIN accounts a ON a.id = c.account_id
             WHERE c.tenant_id = :tid
             ORDER BY a.name, c.last_name",
            ['tid' => static::tenantId()]
        );
    }

    public static function forAccount(int $accountId): array
    {
        return static::db()->fetchAll(
            'SELECT * FROM customer_users WHERE tenant_id = :tid AND account_id = :aid ORDER BY last_name',
            ['tid' => static::tenantId(), 'aid' => $accountId]
        );
    }

    public static function findByEmail(string $email): ?array
    {
        return static::db()->fetch(
            'SELECT * FROM customer_users WHERE email = :e LIMIT 1',
            ['e' => $email]
        );
    }

    public static function emailTaken(string $email, ?int $exceptId = null): bool
    {
        $sql = 'SELECT id FROM customer_users WHERE email = :e';
        $params = ['e' => $email];
        if ($exceptId) {
            $sql .= ' AND id <> :id';
            $params['id'] = $exceptId;
        }
        return static::db()->fetch($sql, $params) !== null;
    }
}
