<?php

namespace App\Models;

use Illuminate\Support\Facades\Auth;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Order extends Model{
    use SoftDeletes;

    protected $table='order';
    protected $guarded=[];

    public static function order_no($type)
    {
        if($type=='th'){
            $prefix = 'TH';
        }else{
            $prefix = 'DD';
        }
        $timestamp=date('ymdHis') . substr(microtime(), 2, 6);
        $rand=mt_rand(10000, 99999);
        $order_no=$prefix . $timestamp . $rand;
        if(self::where('order_no',$order_no)->first()){
            self::order_no();
        }else{
            return $order_no;
        }
    }
    public function orderDetail()
    {
        return $this->hasMany(OrderDetail::class,'order_no','order_no');
    }
    public function address()
    {
        return $this->hasOne(Address::class,'id','address_id')->withTrashed();
    }
    public function store(){
        return $this->hasOne(Store::class,'id','store_id')->withTrashed();
    }
    public function user(){
        return $this->hasOne(User::class,'id','user_id')->withTrashed();
    }
    public function cancel()
    {
        return $this->hasOne(OrderCancel::class,'order_id','id');
    }
    public function refund()
    {
        return $this->hasMany(OrderRefund::class,'order_no','order_no');
    }
    public function getAccountAttribute($value){
        return round($value);
    }

}
