<?php

namespace App\Models;

use CodeIgniter\Model;

class OrganizationMembershipModel extends Model
{
    protected $table         = 'organization_memberships';
    protected $primaryKey    = 'id';
    protected $returnType    = 'array';
    protected $useTimestamps = true;
    protected $allowedFields = [
        'organization_id',
        'user_id',
        'role',
        'status',
        'invited_by_user_id',
        'joined_at',
    ];

    public function activeForUser(int $userId): array
    {
        return $this->select(
            'organization_memberships.*, organizations.name AS organization_name, organizations.slug AS organization_slug'
        )
            ->join('organizations', 'organizations.id = organization_memberships.organization_id')
            ->where('organization_memberships.user_id', $userId)
            ->where('organization_memberships.status', 'active')
            ->orderBy('organizations.name', 'ASC')
            ->findAll();
    }

    public function findActiveMembership(int $userId, int $organizationId): ?array
    {
        return $this->select(
            'organization_memberships.*, organizations.name AS organization_name, organizations.slug AS organization_slug'
        )
            ->join('organizations', 'organizations.id = organization_memberships.organization_id')
            ->where('organization_memberships.user_id', $userId)
            ->where('organization_memberships.organization_id', $organizationId)
            ->where('organization_memberships.status', 'active')
            ->first();
    }

    public function teamForOrganization(int $organizationId): array
    {
        return $this->select(
            'organization_memberships.*, users.name, users.email, users.last_login_at'
        )
            ->join('users', 'users.id = organization_memberships.user_id')
            ->where('organization_memberships.organization_id', $organizationId)
            ->orderBy('users.name', 'ASC')
            ->findAll();
    }
}
