<?php

namespace App\Models\Invoicing;

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

use App\Enums\Invoicing\QuantityApplicationType;

class TaxInvoiceItem extends Model
{
  //* Associated Table & Primary Key
    protected $table = 'tax_invoice_items';
    protected $primaryKey = 'id';

  //* Fillable Fields
    protected $fillable = [
      // Relations
        'prod_serv_id',
        'invoice_id',
        'line_number',

      // Local Data
        'name',
        'description',

      // Fiscal Data
        'prod_serv_key',
        'sat_description',
        'unit_key',
        'unit_price',
        'quantity',
        'object_tax',
        'unit_price_includes_tax',

        'discount_type',
        'discount_value',
        'discount_total',

        'tax_profile',
        'local_tax_profile',
        'subtotal',
        'tax_charges_summary',
        'total',
        'third_party_account',
        'property_tax_account',
    ];

  //* Cast Columns
    protected $casts = [
        'tax_profile'               => 'array',      // Example of structure/cases on resources\markdown\modules\invoices\tax_profile_structure.md
        'local_tax_profile'         => 'array',      // Example of structure/cases on resources\json\modules\invoices\local_tax_profile_structure.json
        'tax_charges_summary'       => 'array',      // Example of structure/cases on resources\json\modules\invoices\tax_charges_summary_structure.json
        'third_party_account'       => 'array',      // Example of structure/cases on resources\json\modules\invoices\third_party_account_structure.json

        'discount_type' => QuantityApplicationType::class,
        'unit_price_includes_tax'   => 'boolean',
    ];

  //* Relationships
    public function taxInvoice() {
        return $this->belongsTo(TaxInvoice::class, 'invoice_id');
    }

    public function taxProdServ() {
        return $this->belongsTo(TaxProdServ::class, 'prod_serv_id');
    }

  //* External Relationships
    public function prodServ()
    {
        return $this->belongsTo(\App\Models\Static\SAT\CatalogProdServ::class, 'prod_serv_key', 'prod_serv_key');
    }

    public function unit()
    {
        return $this->belongsTo(\App\Models\Static\SAT\CatalogUnit::class, 'unit_key', 'unit_key');
    }

    public function objectTax()
    {
        return $this->belongsTo(\App\Models\Static\SAT\CatalogItem::class, 'object_tax', 'item_key')
            ->where('catalog_code', 'c_ObjetoImp');
    }
}
