<?php

namespace App\Models;

use App\Libs\Database\Eloquent\ContentTypeModel;
use App\Models\GenericBackoffice\Traits\LanguageSupportTrait;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\DB;

class Document extends ContentTypeModel
{
    use LanguageSupportTrait;

    protected $hidden = ['languages', "websites"];
    protected $with = ['languages', "websites"];

    /**
     * The "booting" method of the model.
     */
    protected static function boot()
    {
        parent::boot();

        // Global scope to filter documents by backend user committee permissions
        static::addGlobalScope('visibleByBackendUser', function (Builder $builder) {
            $backendUser = auth()->guard('admin')->user();

            if ($backendUser && $backendUser->userType->id != 1) {
                $allowedCommitteeIds = DB::table('backend_user_committee')
                    ->where('backend_user_id', $backendUser->id)
                    ->pluck('committee_id')
                    ->toArray();

                $builder->where(function ($query) use ($allowedCommitteeIds) {
                    // Show documents without committee (not associated)
                    $query->whereNull('documents.committee_id');

                    // Or documents associated with allowed committees
                    if (!empty($allowedCommitteeIds)) {
                        $query->orWhereIn('documents.committee_id', $allowedCommitteeIds);
                    }
                });
            }
            // If no backend user is authenticated (e.g., frontend user or artisan commands), don't apply filter
        });
    }

    public function documentFile() {
        return $this->belongsTo(MediaItem::class);
    }

    public function committee() {
        return $this->belongsTo(Committee::class);
    }

    public function tags() {
        return $this->belongsToMany(Tag::class)->withPivot('position');
    }

    public function country() {
        return $this->belongsTo(Country::class);
    }
}
