<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class JointAccountMember extends Model
{
    use HasFactory;

    protected $fillable = [
        'joint_account_id',
        'user_id',
        'role',
        'status',
        'permissions',
        'joined_at',
        'invited_by'
    ];

    protected $casts = [
        'permissions' => 'array',
        'joined_at' => 'datetime',
    ];

    // Relationships
    public function jointAccount(): BelongsTo
    {
        return $this->belongsTo(JointAccount::class);
    }

    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    public function invitedBy(): BelongsTo
    {
        return $this->belongsTo(User::class, 'invited_by');
    }

    // Helper methods
    public function hasPermission(string $permission): bool
    {
        $permissions = $this->permissions ?? [];
        return in_array($permission, $permissions) || $this->role === 'owner';
    }

    public function canApproveTransactions(): bool
    {
        return in_array($this->role, ['owner', 'admin']) || $this->hasPermission('approve_transactions');
    }

    public function canInviteMembers(): bool
    {
        return in_array($this->role, ['owner', 'admin']) || $this->hasPermission('invite_members');
    }

    public function canViewTransactions(): bool
    {
        return $this->status === 'active';
    }

    public function activate(): void
    {
        $this->update([
            'status' => 'active',
            'joined_at' => now()
        ]);
    }
} 