<?php

namespace App\Models;

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

class Committee extends ContentTypeModel
{
    use LanguageSupportTrait;
    use SafeSyncTrait;

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

    protected $attributes = [
        'type' => ['legalCommittee', 'legalOpinions', 'standard'],
    ];

    protected $fillable = [
        'title',
        'description',
        'status',
        'type',
        'ms_id',
        'archive_active',
    ];

    public function users()
    {
        return $this->belongsToMany(User::class)->withPivot('type');
    }

    public function workGroups() {
        return $this->hasMany(WorkGroup::class);
    }

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

    public function documentListsArchive() {
        return $this->belongsToMany(DocumentList::class, 'committee_document_list_archive')->withPivot('position');
    }

    public function documents() {
        return $this->hasMany(Document::class);
    }

    /**
     * Relationship polymorphic with ContactFolder
     */
    public function contactFolders()
    {
        return $this->morphMany(ContactFolder::class, 'folderable');
    }

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

        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();

                if (!empty($allowedCommitteeIds)) {
                    $builder->whereIn('committees.id', $allowedCommitteeIds);
                } else {
                    $builder->whereRaw('1 = 0');
                }
            }
            // If no backend user is authenticated (e.g., frontend user or artisan commands), don't apply filter
        });

        static::created(function ($committee) {
            $trackingService = app(ModelChangeTrackingService::class);
            $trackingService->trackCommitteeCreated($committee);
        });

        static::deleting(function ($committee) {
            $trackingService = app(ModelChangeTrackingService::class);
            $trackingService->trackCommitteeDeleted($committee);
        });

        static::updating(function ($committee) {
            // Track status changes
            if ($committee->isDirty('status')) {
                $oldStatus = $committee->getOriginal('status');
                $newStatus = $committee->status;

                $trackingService = app(ModelChangeTrackingService::class);
                $trackingService->trackCommitteeStatusChanged($committee, $oldStatus, $newStatus);
            }
        });
    }
}
