<?php

namespace Modules\Billing\Models;

use Illuminate\Database\Eloquent\Model;
use Modules\Accounts\Models\Traits\HasFiscalYear;
use Modules\Accounts\Models\Traits\HasSourceVatTransactions;
use Modules\Billing\Enums\BillStatusEnum;
use Modules\Billing\Models\Traits\HasBillingItems;
use Modules\Billing\Models\Traits\HasBillingPayments;
use Modules\Core\Traits\AuditableTrait;

class Billing extends Model
{
    use AuditableTrait,
        HasFiscalYear,
        HasBillingPayments,
        HasBillingItems,
        HasSourceVatTransactions;

    /**
     * The attributes that are mass assignable.
     */
    protected $fillable = [
        'fiscal_year_id',
        'accounting_period_id',
        'billing_no',
        'patient_id',
        'billing_date',
        'subtotal',
        'total_discount',
        'total_subsidy',
        'taxable_amount',
        'total_vat',
        'rounding_adjustment',
        'grand_total',
        'paid_amount',
        'due_amount',
        'payment_status',
        'status',
        'created_by',
    ];

    protected $casts = [
        'billing_date' => 'date',
        'subtotal' => 'decimal:2',
        'total_discount' => 'decimal:2',
        'total_subsidy' => 'decimal:2',
        'taxable_amount' => 'decimal:2',
        'total_vat' => 'decimal:2',
        'rounding_adjustment' => 'decimal:2',
        'grand_total' => 'decimal:2',
        'paid_amount' => 'decimal:2',
        'due_amount' => 'decimal:2',
    ];

    public function isDraft(): bool
    {
        return $this->status === BillStatusEnum::DRAFT->value;
    }

    public function isConfirmed(): bool
    {
        return $this->status === BillStatusEnum::CONFIRMED->value;
    }

    public function isCancelled(): bool
    {
        return $this->status === BillStatusEnum::CANCELLED->value;
    }

    public function getSalePriceAttribute()
    {
        return $this->base_fee;
    }

    public function getCalculatedPaidAmountAttribute()
    {
        return $this->billingPayments()->sum('amount');
    }

    public function getCalculatedDueAmountAttribute()
    {
        return $this->net_total - $this->calculated_paid_amount;
    }
}
