<?php

namespace App;

use App\Repositories\PreferenceRepository;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;

class BoxOrder extends Model
{
    protected $table = 'box_orders';

    protected $primaryKey = 'id';

    protected $fillable = [
        'box_id', 'payment_id','user_id','subtotal','vat','discount_id','total'
    ];

    protected $with = ['discount','lines', "invoice", "payment"];

    protected $hidden = ['discount_id'];

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

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

            //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 box(){
        return $this->belongsTo("App\Box");
    }

    public function payment(){
        return $this->belongsTo("App\Payment","payment_id");
    }

    public function user(){
        return $this->belongsTo("App\User","user_id");
    }

    public function lines(){
        return $this->hasMany("App\BoxOrderLine","box_order_id","id");
    }

    public function discount(){
        return $this->hasOne("App\Discount","id","discount_id");
    }

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

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

    public function user_subscription() {
        foreach ($this->lines as $l) {
            if ( $l->user_subscription_id ) return $l->user_subscription_id; // Es suposa que nomes tindra una subscription per comanda
        }
        return null;
    }
}
