<?php

namespace App\Models;

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

class Order extends Model
{
    use HasFactory;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    public $fillable = [
        'user_id',
        'order_status_id',
        'delivery_address_id',
        'payment_id',
        'tax',
        'subtotal',
        'final_amount',
        'delivery_fee',
        'promotional_disount',
        'is_coupon_applied',        
        'coupon_code',
        'payment_method',
        'timeslot_id'
    ];

    public static function getLists()
    {
        try {
            $query = new Self;
            if(isset($_GET['submit'])){
                if(isset($_GET['user_id']) && $_GET['user_id']!=''){
                    $query = $query->where('user_id',$_GET['user_id']);
                }
    
                if(isset($_GET['order_status_id']) && $_GET['order_status_id']!=''){
                    $query = $query->where('order_status_id',$_GET['order_status_id']);
                }
    
                return $query->with("user")->with("order_status")->with('payment')->orderBy("id","DESC")->paginate(config('constant.paginate.num_per_page'));
            }else{
                $data = $query->with('user')->with('order_status')->with('payment')->orderBy('id','DESC')->paginate(config('constant.paginate.num_per_page'));
                return $data;
            }
        }catch (\Exception $e) {
            return ['status' => false, 'message' => $e->getMessage() . ' '. $e->getLine() . ' '. $e->getFile()];
        }
    }

    public static function getLatest()
    {
        try {
            $query = new Self;
            return $query->with("user")->with("order_status")->with('payment')->orderBy("id","DESC")->take(10)->get();
        }catch (\Exception $e) {
            return ['status' => false, 'message' => $e->getMessage() . ' '. $e->getLine() . ' '. $e->getFile()];
        }
    }
    
    public function user()
    {
        return $this->hasOne('\App\Models\User','id','user_id')->with('userWallet');
    }

    public function order_status()
    {
        return $this->hasOne('\App\Models\OrderStatus','id','order_status_id');
    }

    public function product_orders()
    {
        return $this->hasMany('\App\Models\OrderProduct','order_id','id')->with('product')->with('product_deliverys');
    }

    public function payment()
    {
        return $this->hasOne('\App\Models\UserPayment','id','payment_id');
    }

    public function delivery_address()
    {
        return $this->hasOne('\App\Models\DeliveryAddresses','id','delivery_address_id');
    }

    public function time_slots()
    {
        return $this->hasOne('\App\Models\Timeslots','id','timeslot_id');
    }

    public function cancel_request()
    {
        return $this->hasOne('\App\Models\OrderCancelRequest','order_id','id');
    }
}
