<?php

namespace App;

use App\Repositories\PreferenceRepository;
use Carbon\Carbon;
use Faker\Factory as Faker;
use Illuminate\Database\Eloquent\Model;

class CompanyOrder extends Model {
    protected $fillable = ["company_id", "subscription_id", "subtotal", "vat", "total"];

    protected $with = ["invoice", "payment"];


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

        static::created(function(CompanyOrder $order) { //Quan es crei una nova instancia de box, assigna els box settings auto
            //Crear factura <-- no es crea perque es crea quan es paga

            //Crear pagament
            $payment = Payment::create([
                "charged" => $order->total > 0 ? false : true,
                "amount" => $order->total
            ]);

            //Guardem
            $order->payment_id = $payment->id;
            $order->save();
        });
    }

    /**
     * RELATIONSHIPS
     */
    public function payment() {
        return $this->belongsTo("App\Payment");
    }

    public function invoice() {
        return $this->belongsTo("App\Invoice");
    }

    public function subscription() {
        return $this->belongsTo("App\Subscription");
    }

    public function company() {
        return $this->hasOneThrough("App\Company", "App\Subscription", "company_id", "id", "subscription_id");
    }
}
