<?php
namespace App\Traits;

use App\Models\Admin;

trait VisibleToAdmin
{
      /**
       * Scope a query to only include records visible to the given admin.
       */
      public function scopeVisibleToAdmin($query, Admin $admin)
      {
            if ($admin->isSuperAdmin()) {
                  return $query; // super admins see everything
            }

            // If the model defines a visibility field (like 'visibility_level')
            if (property_exists($this, 'visibilityField')) {
                  $field = $this->visibilityField;
                  return $query->where($field, '<=', $admin->adminLevel());
            }

            // If the model defines a custom relation for visibility, traverse it
            if (method_exists($this, 'adminVisibilityRelation')) {
                  return $query->whereHas($this->adminVisibilityRelation(), function ($q) use ($admin) {
                        $q->visibleToAdmin($admin);
                  });
            }

            // Default: deny access for normal admins
            return $query->whereRaw('1 = 0');
      }
}