<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Order extends Model
{
    use SoftDeletes;

    protected $fillable = ['user_id', 'status', 'pay_way', 'coupon_id', 'order_total', 'net_total', 'order_discount'];

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

    public function productOrder()
    {
        return $this->hasMany(ProductOrder::class);
    }

    public static function getUserOrder($userId, $status = null)
    {
        $language_id = currentLanguage()->id;
        $orders = self::where('orders.user_id', $userId)
            ->join('product_orders as po', 'po.order_id', 'orders.id')
            ->join('products', 'po.product_id', 'products.id')
            ->join('product_descriptions as pd', 'pd.product_id', 'products.id')
            ->where('pd.language_id', $language_id);

        if ($status){
            $orders->where('orders.status', $status);
        }

        $orders->select([
            'orders.*',
            'pd.name',
            'po.id as product_id',
            'po.amount',
            'po.color',
            'po.price as product_price',
            'products.price',
            'products.id as main_prod_id',
            'products.discount',
            'pd.description',
            'products.images',
            'products.colors',
        ])
            ->selectSub("SELECT code FROM coupons WHERE coupons.id = orders.coupon_id", 'code')
            ->selectSub("SELECT discount FROM coupons WHERE coupons.id = orders.coupon_id", 'coupon_discount');

        return $orders->get() ?? [];
    }

    public function coupon()
    {
        return $this->belongsTo(Coupon::class);
    }
}
