<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Str;

class Member extends Model
{
    protected $fillable = [
        'member_code',
        'first_name',
        'middle_name',
        'last_name',
        'gender',
        'date_of_birth',
        'phone',
        'email',
        'address',
        'jumuiya_id',
        'member_position_id',
        'is_baptized',
        'is_confirmed',
        'is_allowed_sacrament',
        'qr_token',
        'status',
        'date_registered',
        'notes',
    ];

    protected $casts = [
        'date_of_birth' => 'date',
        'date_registered' => 'date',
        'is_baptized' => 'boolean',
        'is_confirmed' => 'boolean',
        'is_allowed_sacrament' => 'boolean',
    ];

    protected static function booted(): void
    {
        static::creating(function (Member $member) {
            $member->member_code ??= 'ACM-'.str_pad((string) ((int) (static::max('id') ?? 0) + 1), 5, '0', STR_PAD_LEFT);
            $member->qr_token ??= 'CHURCH-MEMBER-'.Str::upper(Str::random(24));
            $member->date_registered ??= now()->toDateString();
        });
    }

    public function jumuiya(): BelongsTo
    {
        return $this->belongsTo(Jumuiya::class);
    }

    public function position(): BelongsTo
    {
        return $this->belongsTo(MemberPosition::class, 'member_position_id');
    }

    public function attendanceRecords(): HasMany
    {
        return $this->hasMany(AttendanceRecord::class);
    }

    public function sacramentRecords(): HasMany
    {
        return $this->hasMany(SacramentRecord::class);
    }

    public function getFullNameAttribute(): string
    {
        return trim(collect([$this->first_name, $this->middle_name, $this->last_name])->filter()->join(' '));
    }
}
