<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Order extends Model
{
                protected $guarded = [];

    public function items()
    {
        return $this->hasMany(OrderItem::class);
    }

    public function the_payment()
    {
        return $this->belongsTo('App\Models\Payment','order_id');
    }

    public function payments()
    {
        return $this->hasMany(Payment::class);
    }

    public function customer()
    {
        return $this->belongsTo(Customer::class);
    }

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


    public function getCustomerPaid()
    {
        if($this->customer) {
            return $this->customer->paid;
        }
        return '0';
    }


    public function getCustomerName()
    {
        if($this->customer) {
            return $this->customer->first_name . ' ' . $this->customer->last_name;
        }
        return 'Working Customer';
    }

    public function total()
    {
        return $this->items->map(function ($i){
            return ($i->price * $i->quantity);
        })->sum();
    }

    public function total_purchases()
    {
        return $this->items->map(function ($i){
            return ($i->buy_price * $i->quantity);
        })->sum();
    }
    public function formattedTotal()
    {
        return number_format($this->total(), 2);
    }


        public function discountAmount()
    {
        return $this->payments->map(function ($i){
            return $i->discount;
        })->sum();
    }

    public function receivedAmount()
    {
        return $this->payments->map(function ($i){
            return $i->amount;
        })->sum();
    }


    public function all_paid()
    {
        return $this->payments->map(function ($i){
            return $i->bankak + $i->cash + $i->shake;
        })->sum();
    }



    public function formattedReceivedAmount()
    {
        return number_format($this->receivedAmount(), 2);
    }
}
