<?php

namespace Modules\MedWorkforce\Entities;

use Illuminate\Database\Eloquent\Model;

/**
 * A periodic compliance review item overlaying MedOrganization's license master
 * (SIFA P7-T1 compliance.mandatory_training / credentialing_status). This tracks
 * the obligations org_staff_licenses does NOT hold (training, competency, ad-hoc
 * reviews); it never duplicates licence numbers/expiry. See the
 * create_medwf_credential_reviews migration and ComplianceService.
 */
class CredentialReview extends Model
{
    protected $table = 'medwf_credential_reviews';

    protected $guarded = ['id'];

    protected $casts = [
        'due_date'       => 'date',
        'completed_date' => 'date',
    ];

    public const ITEM_TYPES = ['license', 'mandatory_training', 'competency', 'other'];
    public const STATUSES   = ['pending', 'completed', 'overdue', 'waived'];

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

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

    /**
     * Effective status: a still-pending item past its due date reads as overdue
     * even if the stored status has not been recomputed by a cron.
     */
    public function effectiveStatus(): string
    {
        if ($this->status === 'pending' && $this->due_date && $this->due_date->isPast()) {
            return 'overdue';
        }

        return $this->status;
    }
}
