<?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 = [
        'vendor_id', 'category_id', 'brand_id', 'name', 'slug', 'sku',
        'short_description', 'description', 'price', 'sale_price',
        'stock_quantity', 'condition', 'part_number', 'oem_number',
        'thumbnail', 'is_active', 'is_featured', 
        'approval_status', 'rejection_reason', 'approved_at', 'approved_by',
        'views', 'weight', 'dimensions',
    ];

    protected $casts = [
        'price' => 'decimal:2',
        'sale_price' => 'decimal:2',
        'is_active' => 'boolean',
        'is_featured' => 'boolean',
        'approved_at' => 'datetime',
    ];

    protected static function boot()
    {
        parent::boot();
        static::creating(function ($product) {
            if (empty($product->slug)) {
                $product->slug = Str::slug($product->name) . '-' . Str::random(6);
            }
            if (empty($product->sku)) {
                $product->sku = strtoupper(Str::random(10));
            }
        });
    }

    public function vendor()
    {
        return $this->belongsTo(Vendor::class);
    }

    public function category()
    {
        return $this->belongsTo(Category::class);
    }

    public function brand()
    {
        return $this->belongsTo(Brand::class);
    }

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

    public function primaryImage()
    {
        // Check if is_primary column exists to avoid errors on older installations
        if (!\Schema::hasColumn('product_images', 'is_primary')) {
            return $this->hasOne(ProductImage::class)->orderBy('sort_order');
        }
        return $this->hasOne(ProductImage::class)->where('is_primary', true);
    }

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

    public function carYears()
    {
        return $this->belongsToMany(CarYear::class, 'product_car_year');
    }

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

    public function wishlists()
    {
        return $this->hasMany(Wishlist::class);
    }

    public function getCurrentPriceAttribute(): float
    {
        return $this->sale_price && $this->sale_price < $this->price
            ? (float) $this->sale_price
            : (float) $this->price;
    }

    public function getAverageRatingAttribute(): float
    {
        return round($this->reviews()->where('is_approved', true)->avg('rating') ?? 0, 1);
    }

    public function getThumbnailUrlAttribute(): string
    {
        try {
            // First check for primary image
            $primary = $this->primaryImage;
            if ($primary) {
                return $primary->url;
            }
        } catch (\Exception $e) {
            // Column might not exist yet, fall through to next method
        }
        
        try {
            // Then check for any image
            $firstImage = $this->images->first();
            if ($firstImage) {
                return $firstImage->url;
            }
        } catch (\Exception $e) {
            // Ignore errors
        }
        
        // Finally check thumbnail field
        if ($this->thumbnail) {
            return asset('storage/' . $this->thumbnail);
        }
        
        return asset('images/no-image.png');
    }

    public function isInStock(): bool
    {
        return $this->stock_quantity > 0;
    }

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

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

    public function scopePendingApproval($query)
    {
        return $query->where('approval_status', 'pending');
    }

    public function isApproved(): bool
    {
        return $this->approval_status === 'approved';
    }

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