<?php

namespace App;

use App\Repositories\InvoiceRepository;
use Illuminate\Database\Eloquent\Model;

class Invoice extends Model {
    protected $fillable = ["company_id", "box_order_id", "type", "from_fiscal_name", "from_nif_cif",
        "from_fiscal_address", "to_fiscal_name", "to_nif_cif", "to_fiscal_address", "emitted_date",
        "due_date", "concept", "subtotal", "tax_prcnt", "tax_amount", "total", "invoice_prefix",
        "invoice_serie", "invoice_number"];

    protected $appends = ["official_number"];

    /**
     * EVENTS
     */
    public static function boot() {
        parent::boot();

        static::creating(function(Invoice $i) {
            if(empty($i->invoice_prefix)) $i->invoice_prefix = null; //forcem que si ens passen "", sigui null

            $number = InvoiceRepository::getInvoiceNextNumber($i->type, $i->invoice_serie, $i->invoice_prefix, $i->company_id);
            $i->invoice_number = $number;
        });
    }

    /**
     * ATRIBUTS FICTICIS
     */
    public function getOfficialNumberAttribute() {
        return $this->invoice_prefix . $this->invoice_serie . "-" . $this->invoice_number;
    }

    /**
     * RELATIONSHIPS
     */
    public function box_order() {
        return $this->hasOne("App\BoxOrder");
    }

    public function company_order() {
        return $this->hasOne("App\CompanyOrder");
    }

    public function payment() {
        return $this->box_order ?
            $this->hasOneThrough("App\Payment", "App\BoxOrder") :
            $this->hasOneThrough("App\Payment", "App\CompanyOrder");
    }

    public function user() {
        return $this->box_order ? $this->hasOneThrough("App\User", "App\BoxOrder") : null;
    }

    public function box() {
        return $this->box_order ? $this->hasOneThrough("App\Box", "App\BoxOrder") : null;
    }

}
