<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class ClientInvoice extends Model
{
    protected $table = 'client_invoices';

    protected $fillable = [
        'client_id',
        'invoice_number',
        'invoice_date',
        'due_date',
        'matter_id',
        'case_id',
        'case_reference',
        'description',
        'responsible_lawyer',
        'quotation_id',
        'arrangement_id',
        'billing_period_from',
        'billing_period_to',
        'narration',
        'gl_account',
        'currency_id',
        'subtotal',
        'tax_total',
        'disbursement_total',
        'discount_total',
        'total',
        'amount_paid',
        'status',
        'sent_at',
        'paid_at',
        'created_by',
        'updated_by',
    ];

    protected $casts = [
        'invoice_date' => 'date',
        'due_date' => 'date',
        'billing_period_from' => 'date',
        'billing_period_to' => 'date',
        'subtotal' => 'decimal:2',
        'tax_total' => 'decimal:2',
        'disbursement_total' => 'decimal:2',
        'discount_total' => 'decimal:2',
        'total' => 'decimal:2',
        'amount_paid' => 'decimal:2',
        'sent_at' => 'datetime',
        'paid_at' => 'datetime',
    ];

    public function customer()
    {
        return $this->belongsTo(Client::class, 'client_id');
    }

    public function client()
    {
        return $this->customer();
    }

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

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

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

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

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

    /**
     * Calculate total disbursements from the new table
     */
    public function getTotalDisbursementsAttribute()
    {
        if ($this->relationLoaded('disbursementsList')) {
            return $this->disbursementsList->sum('amount');
        }

        return (float) ($this->disbursement_total ?? 0);
    }

    /**
     * Calculate total tax amount from multiple taxes
     */
    public function getTotalTaxAmountAttribute()
    {
        if ($this->relationLoaded('taxesList')) {
            return $this->taxesList->sum('tax_amount');
        }

        return (float) ($this->tax_total ?? 0);
    }

    /**
     * Calculate combined tax rate as a single percentage
     * This is calculated based on the net before tax
     */
    public function getCombinedTaxRateAttribute()
    {
        $netBeforeTax = $this->net_before_tax;
        if ($netBeforeTax <= 0) {
            return 0;
        }
        $totalTax = $this->total_tax_amount;
        return ($totalTax / $netBeforeTax) * 100;
    }

    /**
     * Get gross total (tariff subtotal before taxes/discounts/disbursements)
     */
    public function getGrossTotalAttribute()
    {
        $subtotal = (float) ($this->subtotal ?? 0);
        if ($subtotal > 0) {
            return $subtotal;
        }

        if ($this->relationLoaded('lines')) {
            return (float) $this->lines->sum('line_total');
        }

        return $subtotal;
    }

    /**
     * Get discount amount
     */
    public function getDiscountAmountAttribute()
    {
        return (float) ($this->discount_total ?? 0);
    }

    /**
     * Get net total before tax
     */
    public function getNetBeforeTaxAttribute()
    {
        return $this->gross_total - $this->total_disbursements - $this->discount_amount;
    }

    /**
     * Get net total after tax
     */
    public function getNetAfterTaxAttribute()
    {
        return $this->net_before_tax + $this->total_tax_amount;
    }

    public function getDocumentDateAttribute()
    {
        return $this->invoice_date;
    }

    public function getDocumentNumberAttribute()
    {
        return $this->invoice_number;
    }
}
