<?php

namespace App\Models;

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

class Meeting extends ContentTypeModel
{
    use LanguageSupportTrait;
    use SafeSyncTrait;

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

    protected $casts = [
        'start_date' => 'datetime',
        'end_date' => 'datetime',
    ];

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

        // Global scope to filter meetings 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 meetings not associated with any committee or workgroup (general meetings)
                    $query->where(function ($orphanQuery) {
                        $orphanQuery->whereNull('meetings.committee_id')
                            ->whereNull('meetings.work_group_id');
                    });

                    if (!empty($allowedCommitteeIds)) {
                        // Or meetings associated with allowed committees
                        $query->orWhereIn('meetings.committee_id', $allowedCommitteeIds);

                        // Or meetings associated with workgroups of allowed committees
                        $query->orWhereExists(function ($subQuery) use ($allowedCommitteeIds) {
                            $subQuery->select(DB::raw(1))
                                ->from('work_groups')
                                ->whereColumn('work_groups.id', 'meetings.work_group_id')
                                ->whereIn('work_groups.committee_id', $allowedCommitteeIds);
                        });
                    }
                });
            }
            // If no backend user is authenticated (e.g., frontend user or artisan commands), don't apply filter
        });
    }

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

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

    public function workGroup() {
        return $this->belongsTo(WorkGroup::class);
    }

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