<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Invoices extends Model
{
    use SoftDeletes;

    protected $fillable = [
        'clinic_id',
        'branch_id',
        'patient_id',
        'visit_id',
        'treatment_plan_id',
        'invoice_number',
        'date',
        'subtotal',
        'discount',
        'tax_percent',
        'tax_amount',
        'total',
        'paid_amount',
        'status',
        'payment_due_date',
    ];

    protected $casts = [
        'date'             => 'date',
        'payment_due_date' => 'date',
        'subtotal'         => 'decimal:2',
        'discount'         => 'decimal:2',
        'tax_percent'      => 'decimal:2',
        'tax_amount'       => 'decimal:2',
        'total'            => 'decimal:2',
        'paid_amount'      => 'decimal:2',
    ];

    // علاقات
    public function clinic()
    {
        return $this->belongsTo(Clinic::class, 'clinic_id');
    }

    public function branch()
    {
        return $this->belongsTo(Branches::class, 'branch_id');
    }

    public function patient()
    {
        return $this->belongsTo(Patients::class, 'patient_id');
    }

    public function visit()
    {
        return $this->belongsTo(Visits::class, 'visit_id');
    }

    public function treatmentPlan()
    {
        return $this->belongsTo(TreatmentPlans::class, 'treatment_plan_id');
    }

    public function items()
    {
        return $this->hasMany(InvoiceItems::class, 'invoice_id');
    }

    public function payments()
    {
        return $this->hasMany(Payments::class, 'invoice_id');
    }





    public function refreshStatus(): void
    {
        if ($this->paid_amount <= 0) {
            $this->status = 'unpaid';
        } elseif ($this->paid_amount > 0 && $this->paid_amount < $this->total) {
            $this->status = 'partial';
        } elseif ($this->paid_amount >= $this->total) {
            $this->status = 'paid';
        }

        $this->save();
    }
}
