<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Storage;

class Product extends Model
{
    use HasFactory;

    protected $fillable = [
        'category_id',
        'name',
        'slug',
        'sku',
        'product_type',
        'short_description',
        'description',
        'price',
        'original_price',
        'discount',
        'stock',
        'status',
        'is_new',
        'is_best_seller',
        'is_featured',
        'is_trending',
        'is_sold_out',
        'badge',
        'image',
        'hover_image',
        'additional_images',
        'specifications',
    ];

    protected $casts = [
        'price' => 'decimal:2',
        'original_price' => 'decimal:2',
        'discount' => 'integer',
        'stock' => 'integer',
        'is_new' => 'boolean',
        'is_best_seller' => 'boolean',
        'is_featured' => 'boolean',
        'is_trending' => 'boolean',
        'is_sold_out' => 'boolean',
        'additional_images' => 'array',
        'specifications' => 'array',
    ];

    protected $appends = ['discount_percentage', 'primary_image_url', 'hover_image_url', 'additional_image_urls'];

    /**
     * Format and normalize image path to absolute URL.
     */
    public static function formatImageUrl(?string $path): ?string
    {
        if (empty($path)) {
            return null;
        }

        // Clean browser fakepath prefix if any
        if (str_contains($path, 'fakepath')) {
            $path = basename(str_replace('\\', '/', $path));
        }

        // External URL
        if (str_starts_with($path, 'http://') || str_starts_with($path, 'https://')) {
            return $path;
        }

        // Remove leading slash for consistency
        $cleanPath = ltrim($path, '/');

        // Check if already starts with storage/
        if (str_starts_with($cleanPath, 'storage/')) {
            return url($cleanPath);
        }

        // Convert relative storage path (e.g. products/2026/08/img.jpg) to full URL
        return url(Storage::url($cleanPath));
    }

    /**
     * Calculate discount percentage dynamically if MRP > price.
     */
    public function getDiscountPercentageAttribute(): int
    {
        if ($this->original_price && $this->original_price > $this->price) {
            return (int) round((($this->original_price - $this->price) / $this->original_price) * 100);
        }
        return $this->discount ?? 0;
    }

    /**
     * Get Primary Image URL with fallback to image column or default luxury placeholder.
     */
    public function getPrimaryImageUrlAttribute(): string
    {
        if ($this->relationLoaded('images')) {
            $primaryRecord = $this->images->first(function ($img) {
                return $img->is_primary || $img->image_type === 'primary';
            });
            if ($primaryRecord && !empty($primaryRecord->image_path)) {
                return static::formatImageUrl($primaryRecord->image_path);
            }
        }

        if (!empty($this->image)) {
            return static::formatImageUrl($this->image);
        }

        return 'https://images.unsplash.com/photo-1599643478518-a784e5dc4c8f?auto=format&fit=crop&w=800&q=80';
    }

    /**
     * Get Hover Image URL with fallback to primary image.
     */
    public function getHoverImageUrlAttribute(): string
    {
        if ($this->relationLoaded('images')) {
            $hoverRecord = $this->images->first(function ($img) {
                return $img->image_type === 'hover';
            });
            if ($hoverRecord && !empty($hoverRecord->image_path)) {
                return static::formatImageUrl($hoverRecord->image_path);
            }
        }

        if (!empty($this->hover_image)) {
            return static::formatImageUrl($this->hover_image);
        }

        return $this->primary_image_url;
    }

    /**
     * Get array of all additional gallery image URLs.
     */
    public function getAdditionalImageUrlsAttribute(): array
    {
        $urls = [];

        // 1. From JSON column 'additional_images'
        if (is_array($this->additional_images)) {
            foreach ($this->additional_images as $path) {
                $formatted = static::formatImageUrl($path);
                if ($formatted && !in_array($formatted, $urls)) {
                    $urls[] = $formatted;
                }
            }
        }

        // 2. From product_images table relation
        if ($this->relationLoaded('images') && $this->images->count() > 0) {
            foreach ($this->images as $img) {
                if ($img->image_type === 'gallery' || (!$img->is_primary && $img->image_type !== 'primary' && $img->image_type !== 'hover')) {
                    $formatted = static::formatImageUrl($img->image_path);
                    if ($formatted && !in_array($formatted, $urls)) {
                        $urls[] = $formatted;
                    }
                }
            }
        }

        return $urls;
    }

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

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

    public function primaryImage()
    {
        return $this->hasOne(ProductImage::class)->where('is_primary', true);
    }

    public function hoverImage()
    {
        return $this->hasOne(ProductImage::class)->where('image_type', 'hover');
    }

    public function galleryImages()
    {
        return $this->hasMany(ProductImage::class)->where('image_type', 'gallery')->orderBy('sort_order', 'asc');
    }
}
