<?php

namespace App\Models;

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

class Product extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id',
        'title',
        'description',
        'price',
        'category',
        'condition',
        'type',
        'images',
        'digital_file_url',
        'status',
        'quantity',
        'location',
        'shipping_fee',
        'meta_data'
    ];

    protected $casts = [
        'images' => 'array',
        'meta_data' => 'array',
        'price' => 'decimal:2',
        'shipping_fee' => 'decimal:2'
    ];

    const STATUS_ACTIVE = 'active';
    const STATUS_SOLD = 'sold';
    const STATUS_INACTIVE = 'inactive';
    const STATUS_SUSPENDED = 'suspended';

    const TYPE_PHYSICAL = 'physical';
    const TYPE_DIGITAL = 'digital';

    const CONDITION_NEW = 'new';
    const CONDITION_USED = 'used';
    const CONDITION_REFURBISHED = 'refurbished';

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

    public function orders()
    {
        return $this->hasMany(MarketplaceOrder::class);
    }

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

    public function scopeActive($query)
    {
        return $query->where('status', self::STATUS_ACTIVE);
    }

    public function scopePhysical($query)
    {
        return $query->where('type', self::TYPE_PHYSICAL);
    }

    public function scopeDigital($query)
    {
        return $query->where('type', self::TYPE_DIGITAL);
    }

    public function getMainImageAttribute()
    {
        return $this->images ? $this->images[0] : null;
    }

    public function getAverageRatingAttribute()
    {
        return $this->reviews()->avg('rating') ?? 0;
    }

    public function getTotalReviewsAttribute()
    {
        return $this->reviews()->count();
    }
}
