<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Spatie\MediaLibrary\HasMedia;
use Spatie\MediaLibrary\InteractsWithMedia;
use Illuminate\Database\Eloquent\SoftDeletes;

class Product extends Model implements HasMedia
{
    use HasFactory;
    use InteractsWithMedia;
    use SoftDeletes;
    protected $fillable =['title','price','storeowner_id','category_id','subcategory_id','storetype_id','status','description','store_detail_id'];

    protected $casts = [

        'category_id'       => 'integer',
        'subcategory_id'    => 'integer',
        'price'             => 'double',
        'status'            => 'integer',
        'storeowner_id'     => 'integer',
    ];

    public function storetype()
    {
        return $this->belongsTo(StoreType::class, 'storetype_id', 'id');
    }
    public function category()
    {
        return $this->belongsTo(Category::class, 'category_id', 'id');
    }
    public function subcategory()
    {
        return $this->belongsTo(SubCategory::class, 'subcategory_id', 'id');
    }
    public function storeowner(){
        return $this->belongsTo(User::class, 'storeowner_id', 'id');
    }
    public function orders()
    {
        return $this->belongsToMany(Order::class);
    }

    public function store(){
        return $this->belongsTo(Store::class, 'store_detail_id','id');
    }
    public function scopeProduct($query)
    {
        $user = auth()->user();
        if($user->user_type == 'client') {
            $query->whereStatus(1);
        }
        if($user->user_type == 'storeowner')
        {
            $query->where('storeowner_id', $user->id);
        }

        return $query;
    }

    public function getProductIdAttribute($value)
    {
        $val = isset($value) ? json_decode($value) : null;
        return $val;
    }

}
