<?php

namespace App\Models\Accounts\Income;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class InvoiceCustomers extends Model
{
    use HasFactory;
    protected $table = 'invoice_customers';

      /** 
     * Attributes that should be mass-assignable.
     *
     * @var array
     */

    //protected $appends = ['invoice_total'];

    protected $fillable = ['company_id', 'invoice_id', 'customer_id'];

    public function invoice()
    {
        return $this->belongsTo('App\Models\Accounts\Income\Invoice', 'invoice_id');
    }

    public function customer()
    {
        return $this->belongsTo('App\Models\Accounts\Income\Customer');
    }

    public function payments(){
        return $this->hasMany('App\Models\Accounts\Income\InvoicePayment', 'invoice_id', 'invoice_id');
    }

    public function invoices_total()
    {
        return $this->invoice()->select('id', 'amount');
    }    

    public function payments_total()
    {
        return $this->payments()->selectRaw('invoice_payments.invoice_id, sum(invoice_payments.amount) as paid_amount')->groupBy('invoice_payments.invoice_id');
    }
}
