<?php

namespace Modules\MedBilling\Entities;

use Illuminate\Database\Eloquent\Model;

/**
 * A captured charge (SIFA P4-T1). The staging area between a clinical event and
 * the ERP invoice. billable() is true only when the row resolves to a real ERP
 * product (product_id + variation_id) — product-less service charges are shown
 * but cannot be pushed to the ERP sell (flagged in the UI).
 */
class MedbillChargeItem extends Model
{
    protected $table = 'medbill_charge_items';

    protected $guarded = ['id'];

    protected $casts = [
        'qty'        => 'decimal:4',
        'unit_price' => 'decimal:4',
    ];

    public const SOURCE_TYPES = ['clc_appointment', 'clc_order_item', 'clc_prescription_item', 'manual'];
    public const STATUSES     = ['draft', 'billed', 'voided'];

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

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

    /** Line total for this charge (qty × unit_price). */
    public function lineTotal(): float
    {
        return round((float) $this->qty * (float) $this->unit_price, 4);
    }

    /** True when this charge can become an ERP sell line (has a resolved product). */
    public function isBillable(): bool
    {
        return ! empty($this->product_id) && ! empty($this->variation_id);
    }
}
