<?php

namespace Licenzo\Model;

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

use Licenzo\Casts\MoneyCast;
use Licenzo\Framework\Database\Model;

class InvoiceItem extends Model
{
    protected $table = 'licenzo_invoice_items';

    const LINE_SUBSCRIPTION = 'subscription';
    const LINE_RENEWAL = 'renewal';
    const LINE_PRORATION = 'proration';
    const LINE_TAX = 'tax';
    const LINE_DISCOUNT = 'discount';

    protected $fillable = [
        'invoice_id',
        'line_type',
        'reference_type',
        'reference_id',
        'description',
        'quantity',
        'unit_amount',
        'line_total',
        'currency',
        'meta'
    ];

    protected $casts = [
        'id' => 'int',
        'invoice_id' => 'int',
        'reference_id' => 'int',
        'quantity' => 'float',
        'unit_amount' => MoneyCast::class,
        'line_total' => MoneyCast::class,
        'meta' => 'array',
        'created_at' => 'datetime',
        'updated_at' => 'datetime'
    ];

    public function invoice()
    {
        return $this->belongsTo(Invoice::class);
    }

    public function scopeByInvoice($query, int $invoiceId)
    {
        return $query->where('invoice_id', $invoiceId);
    }

    public function scopeByReference($query, string $referenceType, int $referenceId)
    {
        return $query
            ->where('reference_type', $referenceType)
            ->where('reference_id', $referenceId);
    }

    public function calculateLineTotal(): float
    {
        return round((float) $this->quantity * (float) $this->unit_amount, 2);
    }
}
