<?php

namespace App\Models\Traits;

use App\Enums\UserType;
use App\Models\Department;
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Eloquent\Builder;

trait FilterDepartment
{
  public function scopeFilterDepartment(Builder $query): Builder
  {
    $tableName = $query->getModel()->getTable();
    $request = request();

    $departmentId = $request->cookie('department_id');
    $user = auth()->user();

    if ($user->role === UserType::PresidentDirector) {
      if ($departmentId) {
        $this->applyDepartmentFilter($query, $tableName, $departmentId);
      }
      return $query;
    }

    $allowedDepartments = Department::whereHas('userDepartments', function ($q) use ($user) {
      $q->where('user_id', $user->id);
    })->pluck('id')->toArray();

    if ($departmentId) {
      if (in_array($departmentId, $allowedDepartments)) {
        $this->applyDepartmentFilter($query, $tableName, $departmentId);
      } else {
        $query->whereRaw('1 = 0');
      }
    } else {
      $this->applyDepartmentFilter($query, $tableName, $allowedDepartments);
    }

    return $query;
  }

  private function applyDepartmentFilter(Builder $query, string $tableName, $departmentIds)
  {
    $isDepartmentId = Schema::hasColumn($tableName, 'department_id');

    if ($isDepartmentId) {
      if (is_array($departmentIds)) {
        $query->whereIn("$tableName.department_id", $departmentIds);
      } else {
        $query->where("$tableName.department_id", $departmentIds);
      }
    }

    if ($tableName === 'users') {
      $query->whereHas('userDepartments', function ($q) use ($departmentIds) {
        if (is_array($departmentIds)) {
          $q->whereIn('department_id', $departmentIds);
        } else {
          $q->where('department_id', $departmentIds);
        }

        if (auth()->user()->role == UserType::Manager) {
          $q->where('role', UserType::User);
        }
      });
    }
  }
}
