<?php

namespace App\Models;

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

class Invoice extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'invoice_number', 'company_id', 'bank_account_id', 'type', 'client_name', 'client_email',
        'client_address', 'client_tax_id', 'invoice_date', 'due_date',
        'subtotal', 'tax_amount', 'discount_amount', 'total_amount',
        'paid_amount', 'balance', 'status', 'notes', 'terms',
        'payment_method', 'cash_amount',
        'is_profit_allocation_payment', 'allocation_month', 'month_revenue', 'month_expenses', 'month_net_profit', 'sweep_percentage',
        'is_loan_request', 'is_loan_repayment', 'loan_id',
        'created_by'
    ];

    protected $casts = [
        'invoice_date'                  => 'date',
        'due_date'                      => 'date',
        'subtotal'                      => 'decimal:2',
        'tax_amount'                    => 'decimal:2',
        'discount_amount'               => 'decimal:2',
        'total_amount'                  => 'decimal:2',
        'paid_amount'                   => 'decimal:2',
        'balance'                       => 'decimal:2',
        'is_profit_allocation_payment'  => 'boolean',
        'month_revenue'                 => 'decimal:2',
        'month_expenses'                => 'decimal:2',
        'month_net_profit'              => 'decimal:2',
        'sweep_percentage'              => 'decimal:2',
        'is_loan_request'              => 'boolean',
        'is_loan_repayment'             => 'boolean',
    ];

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

    public function creator()
    {
        return $this->belongsTo(\App\Models\User::class, 'created_by');
    }

    public function bankAccount()
    {
        return $this->belongsTo(BankAccount::class);
    }

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

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

    public function loan()
    {
        return $this->belongsTo(\App\Models\IntercompanyLoan::class, 'loan_id');
    }
}
