<?php

namespace App\Models;

// use Illuminate\Contracts\Auth\MustVerifyEmail;
use App\Models\Traits\Filterable;
use Laravel\Sanctum\HasApiTokens;
use App\Models\Traits\SelectOptions;
use App\Models\Traits\FilterDepartment;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
  use HasApiTokens, HasFactory, Notifiable, SoftDeletes, Filterable, SelectOptions, FilterDepartment;

  /**
   * The attributes that are mass assignable.
   *
   * @var array<int, string>
   */
  protected $fillable = [
    'name',
    'username',
    'email',
    'phone',
    'password',
    'role',
    'picture',
    'status'
  ];

  /**
   * The attributes that should be hidden for serialization.
   *
   * @var array<int, string>
   */
  protected $hidden = [
    'password',
    'remember_token',
  ];

  /**
   * The attributes that should be cast.
   *
   * @var array<string, string>
   */
  protected $casts = [
    'email_verified_at' => 'datetime',
  ];

  public function userDepartments()
  {
    return $this->belongsToMany(Department::class, 'user_departments', 'user_id', 'department_id')
      ->withPivot(['id', 'type'])
      ->withTimestamps();
  }

  public function banks()
  {
    return $this->belongsToMany(Bank::class, 'user_banks', 'user_id', 'bank_id')
      ->withPivot(['id', 'account_number', 'account_name', 'status'])
      ->withTimestamps();
  }

  public function companies()
  {
    return $this->belongsToMany(Company::class, 'user_companies', 'user_id', 'company_id')
      ->withPivot(['id'])
      ->withTimestamps();
  }

  public function categories()
  {
    return $this->belongsToMany(Category::class, 'user_categories', 'user_id', 'category_id')
      ->withPivot(['id', 'department_id'])
      ->withTimestamps();
  }

  public function owners()
  {
    return $this->belongsToMany(User::class, 'user_owners', 'user_id', 'owner_id')
      ->withPivot(['id'])
      ->withTimestamps();
  }
  public function owner()
  {
    return $this->hasOneThrough(
      User::class,
      UserOwner::class,
      'user_id',
      'id',
      'id',
      'owner_id'
    );
  }

  public function ownedUsers()
  {
    return $this->belongsToMany(User::class, 'user_owners', 'owner_id', 'user_id')
      ->withPivot(['id'])
      ->withTimestamps();
  }

  public function notifications()
  {
    return $this->hasMany(Notification::class, 'user_id');
  }

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

  public function budgetDetails()
  {
    return $this->hasMany(BudgetDetail::class, 'user_id');
  }

  public function transactions()
  {
    return $this->hasMany(Transaction::class, 'user_id');
  }

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