<?php

namespace App\Models;

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

class Record extends Model
{
    use HasFactory;

    protected $fillable = [
        'member_id',
        'supplier_id',
        // 'causal_id',
        'payment_method_id',
        'destination_id',
        'origin_id',
        'date',
        'receipt_date',
        'year',
        'data_pagamento',
        //'month',
        //'year',
        'type',
        //'amount',
        //'note',
        'commercial',
        'corrispettivo_fiscale',
        'deleted',
        'financial_movement',
        'amount',
        'numero_fattura',
        //'attachment'
        'is_paid',
        'prediscount_amount',
    ];

    public function member()
    {
        return $this->belongsTo(Member::class);
    }

    public function supplier()
    {
        return $this->belongsTo(Supplier::class);
    }

    public function payment_method()
    {
        return $this->belongsTo(PaymentMethod::class);
    }

    public function origin()
    {
        return $this->belongsTo(\App\Models\Bank::class, 'origin_id');
    }

    public function destination()
    {
        return $this->belongsTo(\App\Models\Bank::class, 'destination_id');
    }

    public function rows()
    {
        return $this->hasMany(RecordRow::class);
    }

    public function getTotal()
    {
        $vat = 0;
        foreach($this->rows as $r)
        {
            if ($r->vat_id > 0)
            {
                $v = \App\Models\Vat::where('id', $r->vat_id)->first();
                if ($v && $v->value > 0)
                    $vat += $r->amount / 100 * $v->value;
            }
        }
        return $this->rows->sum('amount') + $vat;
    }

}

