<?php

namespace App\Models;

use App\Enums\UserType;
use App\Enums\OriginStatusType;
use App\Models\Traits\Filterable;
use App\Models\Traits\SelectOptions;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class Department extends Model
{
  use HasFactory, SoftDeletes, Filterable, SelectOptions;

  protected $fillable = [
    'user_id',
    'company_id',
    'name',
    'code',
    'status',
    'is_finance',
  ];

  protected $casts = [
    'status' => OriginStatusType::class,
    'is_finance' => 'boolean',
  ];

  public function user()
  {
    return $this->belongsTo(User::class, 'user_id');
  }
  public function company()
  {
    return $this->belongsTo(Company::class, 'company_id');
  }

  public function userDepartments()
  {
    return $this->hasMany(UserDepartment::class, 'department_id');
  }

  public function directors()
  {
    return $this->userDepartments()->where('type', UserType::Director);
  }

  public function managers()
  {
    return $this->userDepartments()->where('type', UserType::Manager);
  }
  public function members()
  {
    return $this->userDepartments()->where('type', UserType::User);
  }

  public function users()
  {
    return $this->belongsToMany(User::class, 'user_departments', 'department_id', 'user_id');
  }

  public function balances()
  {
    return $this->hasMany(Balance::class, 'department_id');
  }

  public function budgets()
  {
    return $this->hasMany(Budget::class, 'department_id');
  }

  public function approvalLogs()
  {
    return $this->hasMany(ApprovalLog::class, 'department_id');
  }

  public function approvalDepartmentLogs()
  {
    return $this->hasMany(ApprovalLog::class, 'approval_department_id');
  }

  public function scopeActive($query, $request)
  {
    if ($request->hasCookie('department_id')) {
      $query->where('id', $request->cookie('department_id'));
    } else {
      $query->whereNull('id');
    }

    $query->where('status', OriginStatusType::Active);

    return $query;
  }
}
