<?php

namespace Modules\MedOrganization\Entities;

use Illuminate\Database\Eloquent\Model;

/**
 * Staff license / credential with verification workflow + expiry alerting
 * (spec §5 user_management license_tracking + credentialing).
 */
class OrgStaffLicense extends Model
{
    protected $table = 'org_staff_licenses';

    protected $guarded = ['id'];

    protected $casts = [
        'issue_date'  => 'date',
        'expiry_date' => 'date',
        'verified_at' => 'datetime',
    ];

    public const STATUSES = ['pending_verification', 'verified', 'rejected', 'expired'];

    /** Common license_type values offered in the UI (free-text stays allowed). */
    public const TYPES = ['medical_license', 'specialization_cert', 'ce_credit'];

    public function user()
    {
        return $this->belongsTo(\App\User::class, 'user_id');
    }

    public function verifier()
    {
        return $this->belongsTo(\App\User::class, 'verified_by');
    }

    public function scopeForBusiness($query, $businessId)
    {
        return $query->where('business_id', $businessId);
    }

    /** Licenses expiring within $days days (and not already expired/rejected). */
    public function scopeExpiringWithin($query, int $days)
    {
        return $query->whereNotNull('expiry_date')
            ->whereIn('status', ['pending_verification', 'verified'])
            ->whereDate('expiry_date', '>=', now()->toDateString())
            ->whereDate('expiry_date', '<=', now()->addDays($days)->toDateString());
    }

    /** Licenses whose expiry_date has passed but status not yet flipped. */
    public function scopePastExpiry($query)
    {
        return $query->whereNotNull('expiry_date')
            ->whereIn('status', ['pending_verification', 'verified'])
            ->whereDate('expiry_date', '<', now()->toDateString());
    }
}
