<?php

namespace Modules\MedBilling\Entities;

use Illuminate\Database\Eloquent\Model;

/**
 * A patient's coverage under a payer (SIFA P4-T1). coverage_pct + copay_fixed
 * drive the patient_share / payer_share split computed at bill time. Optionally
 * links a Wave-A clc_patient_insurances card row.
 */
class MedbillPatientPolicy extends Model
{
    protected $table = 'medbill_patient_policies';

    protected $guarded = ['id'];

    protected $casts = [
        'coverage_pct'   => 'decimal:2',
        'copay_fixed'    => 'decimal:4',
        'annual_limit'   => 'decimal:4',
        'effective_from' => 'date',
        'expiry_date'    => 'date',
    ];

    public const STATUSES = ['active', 'expired', 'cancelled'];

    public function payer()
    {
        return $this->belongsTo(MedbillPayer::class, 'payer_id');
    }

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

    public function scopeActive($query)
    {
        return $query->where('status', 'active');
    }

    /**
     * Split a gross billable amount into [patient_share, payer_share] using this
     * policy's coverage_pct + copay_fixed. The copay is always the patient's; the
     * payer covers coverage_pct of the remainder, capped so neither side goes
     * negative.
     *
     * @return array{patient_share: float, payer_share: float}
     */
    public function splitAmount(float $gross): array
    {
        $copay = min((float) $this->copay_fixed, $gross);
        $coverable = max(0.0, $gross - $copay);
        $payerShare = round($coverable * ((float) $this->coverage_pct / 100), 4);
        $patientShare = round($gross - $payerShare, 4);

        return [
            'patient_share' => max(0.0, $patientShare),
            'payer_share'   => max(0.0, $payerShare),
        ];
    }
}
