<?php

namespace App\Models\Marketplace;

use App\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class Store extends Model
{
    use HasFactory;

    protected $fillable = [
        'name',
        'description',
        'user_id', // Assuming a store is associated with a user
        'location',
        'status', // e.g., active, inactive
        'logo',
        'banner',
        'contact_email',
        'contact_phone',
        'social_links',
        'shipping_policy',
        'return_policy',
        'commission_rate',
        'is_featured',
        'rating',
        'created_at',
        'updated_at'
    ];

    protected $casts = [
        'social_links' => 'json',
        'is_featured' => 'boolean',
        'rating' => 'float',
        'commission_rate' => 'float'
    ];

    public function owner()
    {
        return $this->belongsTo(User::class, 'user_id');
    }

    public function products()
    {
        return $this->hasMany(Product::class);
    }

    // Get the store's reviews through products
    public function reviews()
    {
        return $this->hasManyThrough(ProductReview::class, Product::class);
    }

    // Scope to get active stores
    public function scopeActive($query)
    {
        return $query->where('status', 'active');
    }

    // Scope to get featured stores
    public function scopeFeatured($query)
    {
        return $query->where('is_featured', true);
    }

    // Calculate store rating from product reviews
    public function getAverageRatingAttribute()
    {
        return $this->reviews()->avg('rating') ?? 0;
    }

    // Get total sales amount
    public function getTotalSalesAttribute()
    {
        return Order::whereHas('products', function($query) {
                $query->where('store_id', $this->id);
            })
            ->where('status', 'completed')
            ->sum('total_amount');
    }

    // Get total orders count
    public function getTotalOrdersAttribute()
    {
        return Order::whereHas('products', function($query) {
                $query->where('store_id', $this->id);
            })
            ->count();
    }
}
