<?php

namespace App\Models;

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

class Purchase extends Model
{
    use HasFactory;
    protected $table = 'purchases';
    protected $guarded = ['id'];

    public function product_price_purchases()
    {
        return $this->hasMany(ProductPricePurchase::class, 'purchase_id', 'id');
    }

    public function status()
    {
        return $this->belongsTo(Status::class, 'status_id', 'id');
    }

    public function total()
    {
        $total = 0;
        foreach ($this->product_price_purchases as $item) {
            $total += ($item->product_price->price * $item->quantity);
        }
        return $total += $this->shipping;
    }

    public function mercado_pago()
    {
        return $this->belongsTo(MercadoPagoData::class, 'id', 'purchase_id');
    }
    
    public function address_purchase()
    {
        return $this->belongsTo(AddressPurchase::class, 'id', 'purchase_id');
    }

    public function user()
    {
        return $this->belongsTo(User::class, 'user_id', 'id');
    }

    public function data_invoice()
    {
        return $this->belongsTo(Invoice::class, 'id', 'purchase_id');
    }
}