<?php

namespace App\Models;

use App\Traits\Multitenantable;
use DateTimeInterface;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class ProductVariant extends Model
{
    use SoftDeletes, Multitenantable;

    public $primaryKey = 'uuid';

    public $incrementing = false;

    public $keyType = 'string';

    public $imageFields = ['server_image_url'];

    protected $fillable = [
        'uuid',
        'tenant_id',
        'product_id',
        'name',
        'server_image_url',
        'is_visible_online',
        'total_rating',
        'average_rating',
        'total_sold',
        'is_product_variant'
    ];
    
     protected $casts = [
        'is_visible_online' => 'boolean',
        'is_product_variant' => 'boolean',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
    ];

    protected $dates = ['deleted_at'];

    protected function serializeDate(DateTimeInterface $date)
    {
        return $date->format('Y-m-d H:i:s');
    }

    public function product()
    {
        return $this->belongsTo(Product::class, 'product_id');
    }

    public function inventory()
    {
        return $this->morphOne(OutletInventory::class, 'item');
    }

    public function reviews()
    {
        return $this->hasMany(ProductReview::class, 'product_variant_id', 'uuid');
    }

    public function getServerImageUrlAttribute($value)
    {
        if (!$value) return null;
        
        return asset('storage/' . $value);
    }
}
