<?php

namespace App\Models;

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

class MembershipCertificate extends Model
{
    protected $fillable = [
        'member_id',
        'certificate_number',
        'issue_date',
        'valid_till_date',
        'pdf_path',
        'is_current',
        'issued_by',
    ];

    protected $casts = [
        'issue_date' => 'date',
        'valid_till_date' => 'date',
        'is_current' => 'boolean',
    ];

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

    public function issuer(): BelongsTo
    {
        return $this->belongsTo(User::class, 'issued_by');
    }

    public function renewal(): HasOne
    {
        return $this->hasOne(MembershipRenewal::class, 'certificate_id');
    }

    /**
     * Scope to only current certificates.
     */
    public function scopeCurrent($query)
    {
        return $query->where('is_current', true);
    }

    /**
     * Generate a unique certificate number in format MEMCERT-{YEAR}-{8 random uppercase chars}.
     */
    public static function generateCertificateNumber(): string
    {
        do {
            $number = 'MEMCERT-' . now()->year . '-' . strtoupper(Str::random(8));
        } while (static::where('certificate_number', $number)->exists());

        return $number;
    }
}
