<?php

namespace App\Models;

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

class User extends Authenticatable
{
    use HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name',
        'email',
        'password',
        'role',
        'society_id',
        'user_code',
        'house_number',
        'wing',
        'member_type',
        'employee_id_code',
        'designation',
        'joining_date',
        'vendor_id_code',
        'vendor_type',
        'service_description',
        'phone',
        'photo',
    ];

    protected static function boot()
    {
        parent::boot();
        static::creating(function ($user) {
            $latest = self::orderBy('id', 'desc')->whereNotNull('user_code')->first();
            $number = $latest ? (int) substr($latest->user_code, 3) + 1 : 1;
            do {
                $code = 'SMU' . str_pad($number, 7, '0', STR_PAD_LEFT);
                $exists = self::where('user_code', $code)->exists();
                if ($exists)
                    $number++;
            } while ($exists);
            $user->user_code = $code;
        });
    }

    public function society()
    {
        return $this->belongsTo(Society::class);
    }

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

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