<?php

namespace App\Modules\FINANCE\Models;

use Illuminate\Database\Eloquent\Model;
use App\Modules\PLATFORM\Settings\Models\Company;
use App\Modules\PLATFORM\Settings\Models\Currency;

class Invoice extends Model
{
    protected $table = 'finance_invoices';

    protected $fillable = [
        'company_id',
        'document_type',
        'template_name',
        'converted_invoice_id',
        'client_id',
        'recurring_invoice_id',
        'invoice_number',
        'invoice_date',
        'due_date',
        'sub_total',
        'tax_total',
        'total_amount',
        'paid_amount',
        'balance_amount',
        'currency_id',
        'exchange_rate',
        'status',
        'public_hash',
        'notes',
        'po_number',
        'reference',
        'terms',
    ];

    protected $casts = [
        'invoice_date' => 'date',
        'due_date'     => 'date',
        'sub_total'    => 'decimal:2',
        'tax_total'    => 'decimal:2',
        'total_amount' => 'decimal:2',
        'paid_amount'  => 'decimal:2',
        'balance_amount' => 'decimal:2',
        'exchange_rate' => 'decimal:6',
    ];

    public function company()
    {
        return $this->belongsTo(Company::class);
    }

    public function client()
    {
        return $this->belongsTo(Client::class);
    }

    public function items()
    {
        return $this->hasMany(InvoiceItem::class);
    }

    public function payments()
    {
        return $this->hasMany(Payment::class);
    }

    public function currency()
    {
        return $this->belongsTo(Currency::class);
    }

    public function recurringInvoice()
    {
        return $this->belongsTo(RecurringInvoice::class, 'recurring_invoice_id');
    }

    public function reminders()
    {
        return $this->hasMany(InvoiceReminder::class);
    }

    public function convertedInvoice()
    {
        return $this->belongsTo(Invoice::class, 'converted_invoice_id');
    }

    public function quotes()
    {
        return $this->hasMany(Invoice::class, 'converted_invoice_id');
    }
}
