<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Str;

class Product extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'name',
        'slug',
        'description',
        'short_description',
        'sku',
        'price',
        'price_dop',
        'compare_price',
        'compare_price_dop',
        'cost',
        'stock',
        'track_stock',
        'allow_backorder',
        'image',
        'gallery',
        'category_id',
        'weight',
        'dimensions',
        'sizes',
        'flavors',
        'nutrition_info',
        'tax_rate',
        'is_active',
        'is_featured',
        'sales_count',
        'view_count',
        'metadata',
    ];

    protected $casts = [
        'price' => 'decimal:2',
        'price_dop' => 'decimal:2',
        'compare_price' => 'decimal:2',
        'compare_price_dop' => 'decimal:2',
        'cost' => 'decimal:2',
        'tax_rate' => 'decimal:2',
        'weight' => 'decimal:2',
        'track_stock' => 'boolean',
        'allow_backorder' => 'boolean',
        'is_active' => 'boolean',
        'is_featured' => 'boolean',
        'gallery' => 'array',
        'sizes' => 'array',
        'flavors' => 'array',
        'nutrition_info' => 'array',
        'metadata' => 'array',
    ];

    protected $appends = ['image_url', 'gallery_urls', 'is_on_sale', 'discount_percentage', 'average_rating', 'reviews_count'];

    protected static function boot()
    {
        parent::boot();

        static::creating(function ($product) {
            if (empty($product->slug)) {
                $product->slug = Str::slug($product->name);
            }
            if (empty($product->sku)) {
                $product->sku = strtoupper(Str::random(8));
            }
        });
    }

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

    public function orderItems()
    {
        return $this->hasMany(OrderItem::class);
    }

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

    public function approvedReviews()
    {
        return $this->hasMany(ProductReview::class)->where('is_approved', true);
    }

    public function getAverageRatingAttribute()
    {
        return round($this->approvedReviews()->avg('rating') ?? 0, 1);
    }

    public function getReviewsCountAttribute()
    {
        return $this->approvedReviews()->count();
    }

    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    public function scopeFeatured($query)
    {
        return $query->where('is_featured', true);
    }

    public function scopeInStock($query)
    {
        return $query->where(function ($q) {
            $q->where('track_stock', false)
              ->orWhere('stock', '>', 0)
              ->orWhere('allow_backorder', true);
        });
    }

    public function scopeByCategory($query, $categoryId)
    {
        return $query->where('category_id', $categoryId);
    }

    public function getImageUrlAttribute()
    {
        if (!$this->image) {
            return null;
        }
        return str_starts_with($this->image, 'http') 
            ? $this->image 
            : asset('storage/' . $this->image);
    }

    public function getGalleryUrlsAttribute()
    {
        if (!$this->gallery) {
            return [];
        }
        return array_map(function ($img) {
            return str_starts_with($img, 'http') ? $img : asset('storage/' . $img);
        }, $this->gallery);
    }

    public function getIsOnSaleAttribute()
    {
        return $this->compare_price && $this->compare_price > $this->price;
    }

    public function getDiscountPercentageAttribute()
    {
        if (!$this->is_on_sale) {
            return 0;
        }
        return round((($this->compare_price - $this->price) / $this->compare_price) * 100);
    }

    public function isInStock()
    {
        if (!$this->track_stock) {
            return true;
        }
        return $this->stock > 0 || $this->allow_backorder;
    }

    public function decrementStock($quantity = 1)
    {
        if ($this->track_stock) {
            $this->decrement('stock', $quantity);
        }
    }

    public function incrementSalesCount($quantity = 1)
    {
        $this->increment('sales_count', $quantity);
    }
}
