<?php

namespace App\Models;

use App\Libs\Database\Eloquent\BaseModel;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\DB;

class MediaItem extends BaseModel
{
    const MEDIA_TYPE_IMAGE    = "image";
    const MEDIA_TYPE_VIDEO    = "video";
    const MEDIA_TYPE_DOCUMENT = "document";
    const MEDIA_TYPE_SVG      = "svg";

    protected $guarded = ['id'];

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

        // Global scope to filter private media items 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) {
                    $query->where('is_private', 0);

                    $query->orWhere(function ($privateQuery) use ($allowedCommitteeIds) {
                        $privateQuery->where('is_private', 1);

                        $privateQuery->where(function ($associationQuery) use ($allowedCommitteeIds) {
                            $associationQuery->whereNotExists(function ($subQuery) {
                                $subQuery->select(DB::raw(1))
                                    ->from('documents')
                                    ->whereColumn('documents.document_file_id', 'media_items.id')
                                    ->whereNotNull('documents.committee_id');
                            })
                            ->whereNotExists(function ($subQuery) {
                                $subQuery->select(DB::raw(1))
                                    ->from('documents')
                                    ->join('document_document_list', 'documents.id', '=', 'document_document_list.document_id')
                                    ->join('committee_document_list', 'document_document_list.document_list_id', '=', 'committee_document_list.document_list_id')
                                    ->whereColumn('documents.document_file_id', 'media_items.id');
                            })
                            ->whereNotExists(function ($subQuery) {
                                $subQuery->select(DB::raw(1))
                                    ->from('documents')
                                    ->join('document_document_list', 'documents.id', '=', 'document_document_list.document_id')
                                    ->join('document_list_work_group', 'document_document_list.document_list_id', '=', 'document_list_work_group.document_list_id')
                                    ->whereColumn('documents.document_file_id', 'media_items.id');
                            });

                            if (!empty($allowedCommitteeIds)) {
                                $associationQuery->orWhereExists(function ($subQuery) use ($allowedCommitteeIds) {
                                    $subQuery->select(DB::raw(1))
                                        ->from('documents')
                                        ->whereColumn('documents.document_file_id', 'media_items.id')
                                        ->whereIn('documents.committee_id', $allowedCommitteeIds);
                                });

                                $associationQuery->orWhereExists(function ($subQuery) use ($allowedCommitteeIds) {
                                    $subQuery->select(DB::raw(1))
                                        ->from('documents')
                                        ->join('document_document_list', 'documents.id', '=', 'document_document_list.document_id')
                                        ->join('committee_document_list', 'document_document_list.document_list_id', '=', 'committee_document_list.document_list_id')
                                        ->whereColumn('documents.document_file_id', 'media_items.id')
                                        ->whereIn('committee_document_list.committee_id', $allowedCommitteeIds);
                                });

                                $associationQuery->orWhereExists(function ($subQuery) use ($allowedCommitteeIds) {
                                    $subQuery->select(DB::raw(1))
                                        ->from('documents')
                                        ->join('document_document_list', 'documents.id', '=', 'document_document_list.document_id')
                                        ->join('document_list_work_group', 'document_document_list.document_list_id', '=', 'document_list_work_group.document_list_id')
                                        ->join('work_groups', 'document_list_work_group.work_group_id', '=', 'work_groups.id')
                                        ->whereColumn('documents.document_file_id', 'media_items.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 backendUser()
    {
        $this->belongsTo('BackendUser');
    }

    public function isImage()
    {
        return $this->media_type == self::MEDIA_TYPE_IMAGE;
    }

    public function isVideo()
    {
        return $this->media_type == self::MEDIA_TYPE_VIDEO;
    }

    public function isSvg()
    {
        return $this->media_type == self::MEDIA_TYPE_SVG;
    }
}
