<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;

class Team extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'business_id',
        'name',
        'description',
        'status',
        'member_count',
    ];

    protected $casts = [
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
        'deleted_at' => 'datetime',
    ];

    // =============== Relationships ===============

    /**
     * Team belongs to a Business
     */
    public function business(): BelongsTo
    {
        return $this->belongsTo(Business::class);
    }

    /**
     * Team has many members through pivot table
     */
    public function members(): BelongsToMany
    {
        return $this->belongsToMany(User::class, 'team_user')
            ->withPivot('role_id', 'custom_permissions', 'status', 'invited_at', 'joined_at')
            ->withTimestamps();
    }

    /**
     * Team has many business staff
     */
    public function staff(): HasMany
    {
        return $this->hasMany(BusinessStaff::class);
    }

    /**
     * Team has many chats
     */
    public function chats(): HasMany
    {
        return $this->hasMany(Chat::class);
    }

    // =============== Scopes ===============

    /**
     * Scope to filter active teams only
     */
    public function scopeActive($query)
    {
        return $query->where('status', 'active');
    }

    /**
     * Scope to filter by business
     */
    public function scopeForBusiness($query, $businessId)
    {
        return $query->where('business_id', $businessId);
    }

    /**
     * Scope to include members
     */
    public function scopeWithMembers($query)
    {
        return $query->with('members');
    }

    // =============== Accessors & Mutators ===============

    /**
     * Get team URL for admin panel
     */
    public function getAdminUrl(): string
    {
        return route('admin.teams.edit', $this->id);
    }

    /**
     * Get team status badge color
     */
    public function getStatusColor(): string
    {
        return match($this->status) {
            'active' => 'success',
            'inactive' => 'secondary',
            'archived' => 'danger',
            default => 'info',
        };
    }

    // =============== Methods ===============

    /**
     * Add a member to the team
     */
    public function addMember(User $user, ?Role $role = null, array $permissions = [], $status = 'pending_invitation'): void
    {
        $this->members()->attach($user->id, [
            'role_id' => $role?->id,
            'custom_permissions' => json_encode($permissions),
            'status' => $status,
            'invited_at' => now(),
        ]);

        $this->updateMemberCount();
    }

    /**
     * Remove a member from the team
     */
    public function removeMember(User $user): void
    {
        $this->members()->detach($user->id);
        $this->updateMemberCount();
    }

    /**
     * Update member role
     */
    public function updateMemberRole(User $user, Role $role): void
    {
        $this->members()->updateExistingPivot($user->id, [
            'role_id' => $role->id,
        ]);
    }

    /**
     * Check if user is member of team
     */
    public function hasMember(User $user): bool
    {
        return $this->members()
            ->where('user_id', $user->id)
            ->where('status', 'active')
            ->exists();
    }

    /**
     * Check if user is team admin/manager
     */
    public function isAdmin(User $user): bool
    {
        $member = $this->members()->where('user_id', $user->id)->first();

        if (!$member) {
            return false;
        }

        $role = $member->pivot->role_id ? Role::find($member->pivot->role_id) : null;

        return $role && in_array($role->name, ['admin', 'manager', 'super_admin']);
    }

    /**
     * Get active members count
     */
    public function getActiveMembersCount(): int
    {
        return $this->members()
            ->where('status', 'active')
            ->count();
    }

    /**
     * Update member count
     */
    public function updateMemberCount(): void
    {
        $this->update([
            'member_count' => $this->getActiveMembersCount(),
        ]);
    }

    /**
     * Create a team chat
     */
    public function createChat(string $name, User $creator, array $participantIds = []): Chat
    {
        $chat = $this->chats()->create([
            'name' => $name,
            'type' => 'team',
            'created_by' => $creator->id,
        ]);

        // Add participants
        if (!empty($participantIds)) {
            $chat->addParticipants($participantIds);
        }

        return $chat;
    }
}

