<?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 DocumentList extends ContentTypeModel
{
    use LanguageSupportTrait;
    use SafeSyncTrait;

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

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

        // Global scope to filter document lists 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 document lists not associated with any committee or workgroup
                    $query->where(function ($orphanQuery) {
                        $orphanQuery->whereNotExists(function ($subQuery) {
                            $subQuery->select(DB::raw(1))
                                ->from('committee_document_list')
                                ->whereColumn('committee_document_list.document_list_id', 'document_lists.id');
                        })
                        ->whereNotExists(function ($subQuery) {
                            $subQuery->select(DB::raw(1))
                                ->from('document_list_work_group')
                                ->whereColumn('document_list_work_group.document_list_id', 'document_lists.id');
                        });
                    });

                    if (!empty($allowedCommitteeIds)) {
                        // Or document lists associated with allowed committees
                        $query->orWhereExists(function ($subQuery) use ($allowedCommitteeIds) {
                            $subQuery->select(DB::raw(1))
                                ->from('committee_document_list')
                                ->whereColumn('committee_document_list.document_list_id', 'document_lists.id')
                                ->whereIn('committee_document_list.committee_id', $allowedCommitteeIds);
                        });

                        // Or document lists associated with workgroups of allowed committees
                        $query->orWhereExists(function ($subQuery) use ($allowedCommitteeIds) {
                            $subQuery->select(DB::raw(1))
                                ->from('document_list_work_group')
                                ->join('work_groups', 'document_list_work_group.work_group_id', '=', 'work_groups.id')
                                ->whereColumn('document_list_work_group.document_list_id', 'document_lists.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 documents()
    {
        return $this->belongsToMany(Document::class)->withPivot('position');
    }

    public function block()
    {
        return $this->belongsToMany(Block::class);
    }

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

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

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