<?php
namespace App\Models;
use App\Models\Concerns\BelongsToBusiness;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class CrmFile extends Model {
    use BelongsToBusiness, SoftDeletes;
    protected $guarded = ['id'];
    public function fileable() { return $this->morphTo(); }
    public function uploader() { return $this->belongsTo(User::class, 'uploaded_by'); }
    protected $casts = ['is_current'=>'boolean','scanned_at'=>'datetime'];
    public function parentVersion() { return $this->belongsTo(self::class, 'parent_file_id'); }
    public function rootVersion() { return $this->belongsTo(self::class, 'root_file_id'); }
    public function versions() { return $this->hasMany(self::class, 'root_file_id')->orderByDesc('version'); }
    public function permissions() { return $this->hasMany(CrmFilePermission::class); }
    public function accessLogs() { return $this->hasMany(CrmFileAccessLog::class); }

    public function scopeVisibleTo($query, User $user)
    {
        if ($user->hasRole('admin') || $user->can('manage_crm_files')) {
            return $query;
        }

        return $query->where(function ($query) use ($user) {
            $query->where('uploaded_by', $user->id)
                ->orWhere('access_level', 'business')
                ->orWhereHas('permissions', fn ($permission) => $permission
                    ->where('user_id', $user->id)->where('can_view', true))
                ->orWhere(function ($team) use ($user) {
                    $team->where('access_level', 'team')
                        ->whereHas('uploader', function ($uploader) use ($user) {
                            $uploader->where('id',$user->id);
                            if(filled($user->team_name))$uploader->orWhere(fn($member)=>$member->where('business_id',$user->business_id)->where('team_name',$user->team_name));
                        });
                });
        });
    }
}
