<?php

namespace App\Models\Marketplace;

use App\Models\Post;
use App\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Storage;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class Product extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id',
        'store_id',
        'name',
        'description',
        'category_id',
        'price',
        'currency',
        'location',
        'type',
        'units',
        'status',
        'stock_quantity',
        'sku',
        'delivery_options',
        'is_featured',
        'views',
        'shipping_cost',
        'tax_rate',
        'discount_percentage',
        'specifications',
        'warranty_info'
    ];

    protected $casts = [
        'price' => 'float',
        'is_featured' => 'boolean',
        'delivery_options' => 'json',
        'views' => 'integer',
        'stock_quantity' => 'integer',
        'shipping_cost' => 'float',
        'tax_rate' => 'float',
        'discount_percentage' => 'float',
        'specifications' => 'json'
    ];

    public function category()
    {
        return $this->belongsTo(ProductCategory::class, 'category_id');
    }

    public function media()
    {
        return $this->hasMany(ProductMedia::class)->orderBy('sort_order');
    }

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

    public function store()
    {
        return $this->belongsTo(Store::class);
    }

    public function savedByUsers()
    {
        return $this->hasMany(SavedProduct::class);
    }

    public function conversations()
    {
        //return $this->hasMany(Conversation::class);
    }

    public function similarProducts()
    {
        return $this->hasMany(Product::class, 'category_id', 'category_id')
            ->where('id', '!=', $this->id)
            ->where('status', 'active')
            ->limit(3);
    }

    public function sellerProducts()
    {
        return $this->hasMany(Product::class, 'user_id', 'user_id')
            ->where('id', '!=', $this->id)
            ->where('status', 'active')
            ->limit(3);
    }

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

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

    // Scope to get products in stock
    public function scopeInStock($query)
    {
        return $query->where(function ($q) {
            $q->where('stock_quantity', '>', 0)
                ->orWhereNull('stock_quantity');
        });
    }

    // Scope to get products on sale
    public function scopeOnSale($query)
    {
        return $query->where('discount_percentage', '>', 0);
    }

    // Define the relationship with orders
    public function orders()
    {
        return $this->belongsToMany(Order::class, 'order_products')
            ->withPivot('quantity', 'price', 'store_id');
    }

    // Define the relationship with reviews
    public function reviews()
    {
        return $this->hasMany(ProductReview::class);
    }

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

    // Get total sales count
    public function getTotalSalesAttribute()
    {
        return $this->orders()->sum('order_products.quantity');
    }

    // Get sale price with discount applied
    public function getSalePriceAttribute()
    {
        if ($this->discount_percentage > 0) {
            return $this->price * (1 - ($this->discount_percentage / 100));
        }
        return $this->price;
    }

    // Check if the product is saved by a specific user
    public function isSavedBy($userId)
    {
        return $this->savedByUsers()->where('user_id', $userId)->exists();
    }
    public function deleteProduct($product)
    {
        foreach ($product->media as $media) {
            if (Storage::disk('public')->exists($media->file_path)) {
                Storage::disk('public')->delete($media->file_path);
            }
            $media->delete();
        }
        $postModel = new Post();
        $groupPosts = $postModel->where('product_id', $product->id)->pluck('id')->toArray();
        $postModel->deletePosts($groupPosts);
        $this->delete();
    }
}
