<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use App\Notifications\SetPasswordNotification;
use App\Notifications\VerifyEmailCustom;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable implements MustVerifyEmail
{
  /** @use HasFactory<\Database\Factories\UserFactory> */
  use HasFactory, Notifiable;

  /**
   * The attributes that are mass assignable.
   *
   * @var list<string>
   */
  protected $fillable = [
    'name',
    'email',
    'password',
    'events_limit',
    'staff_limit',
    'role',
    'guest_limit',
    'user_invitation_limit',
    'phone_number',
  ];

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

  /**
   * Get the attributes that should be cast.
   *
   * @return array<string, string>
   */
  protected function casts(): array
  {
    return [
      'email_verified_at' => 'datetime',
      'password' => 'hashed',
    ];
  }

  protected static function booted()
  {
    static::deleting(function ($user) {

      // احذف الدعوات أولاً
      if (method_exists($user, 'invitations')) {
        $user->invitations()->each(fn($inv) => $inv->delete());
      }

      // ثم احذف المناسبات (سيحذف صورها + مجلد qr)
      if (method_exists($user, 'events')) {
        $user->events()->each(fn($event) => $event->delete());
      }

      // detach pivot (اختياري حسب نظامك)
      if (method_exists($user, 'assignedStaff')) $user->assignedStaff()->detach();
      if (method_exists($user, 'ownersImAssignedTo')) $user->ownersImAssignedTo()->detach();
    });
  }


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

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

  public function assignedStaff()
  {
    return $this->belongsToMany(User::class, 'staff_assignments', 'owner_id', 'staff_id')
      ->withTimestamps();
  }

  public function ownersImAssignedTo()
  {
    return $this->belongsToMany(User::class, 'staff_assignments', 'staff_id', 'owner_id')
      ->withTimestamps();
  }

  public function sendPasswordResetNotification($token): void
  {
    $this->notify(new SetPasswordNotification($token));
  }

  public function sendEmailVerificationNotification(): void
  {
    $this->notify(new VerifyEmailCustom);
  }
}
