<?php
declare(strict_types=1);

namespace App\Models;

final class Territory extends BaseModel
{
    protected static string $table = 'territories';
    protected static bool $softDelete = false;

    public static function allForTenant(): array
    {
        return static::db()->fetchAll(
            'SELECT * FROM territories WHERE tenant_id = :tid ORDER BY name',
            ['tid' => static::tenantId()]
        );
    }

    public static function usersIn(int $territoryId): array
    {
        return static::db()->fetchAll(
            'SELECT u.id, u.first_name, u.last_name
             FROM territory_users tu
             INNER JOIN users u ON u.id = tu.user_id
             WHERE tu.territory_id = :tid AND tu.tenant_id = :ten AND u.status = :st
             ORDER BY u.first_name',
            ['tid' => $territoryId, 'ten' => static::tenantId(), 'st' => 'active']
        );
    }
}
