<?php

namespace App\Models;

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

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

  protected $fillable = [
    'code',
    'name',
    'address',
    'status',
  ];

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

  public function userCompanies()
  {
    return $this->hasMany(UserCompany::class, 'company_id');
  }
  public function departments()
  {
    return $this->hasMany(Department::class, 'company_id');
  }

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

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

  public function payments()
  {
    return $this->hasMany(Payment::class, 'company_id');
  }

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

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

    return $query;
  }
}
