<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class VendorProduct extends Model
{
    private const DEFAULT_IMAGE_PATH = 'images/default-banner.jpg';

    protected $fillable = [
        'vendor_profile_id',
        'user_id',
        'pd_category_id',
        'title',
        'description',
        'admin_price',
        'seller_price',
        'size',
        'sizes',
        'main_image',
        'status',
        'admin_note',
    ];

    protected $casts = [
        'admin_price' => 'decimal:2',
        'seller_price' => 'decimal:2',
        'sizes' => 'array',
    ];

    public function vendorProfile()
    {
        return $this->belongsTo(VendorProfile::class);
    }

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

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

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

    public function getMainImageUrlAttribute(): ?string
    {
        if (!$this->main_image) {
            return asset(self::DEFAULT_IMAGE_PATH);
        }

        $path = trim((string) $this->main_image);
        if (preg_match('/^https?:\/\//i', $path)) {
            return $path;
        }

        return $this->resolveMediaUrl($path, asset(self::DEFAULT_IMAGE_PATH));
    }

    public function getSizesListAttribute(): array
    {
        if (is_array($this->sizes) && count($this->sizes)) {
            return array_values(array_unique(array_filter($this->sizes)));
        }

        if (!empty($this->size)) {
            $parts = array_map('trim', explode(',', (string) $this->size));
            return array_values(array_unique(array_filter($parts)));
        }

        return [];
    }

    public function getSizesTextAttribute(): string
    {
        $list = $this->sizes_list;
        if (count($list)) {
            return implode(', ', $list);
        }

        return (string) ($this->size ?? '');
    }

    private function normalizeLegacyMediaPath(string $path): string
    {
        $clean = str_replace('\\', '/', trim($path));
        $clean = preg_replace('#/+#', '/', $clean);

        if (preg_match('#(?:^|/)(images/.*)$#i', $clean, $m)) {
            return ltrim($m[1], '/');
        }

        if (preg_match('#(?:^|/)(storage/.*)$#i', $clean, $m)) {
            return ltrim($m[1], '/');
        }

        return ltrim($clean, '/');
    }

    private function resolveMediaUrl(string $path, string $fallback): string
    {
        $relative = $this->normalizeLegacyMediaPath($path);
        if ($relative === '') {
            return $fallback;
        }

        return $this->assetWithVersion($relative);
    }

    private function assetWithVersion(string $relative): string
    {
        $url = asset($relative);
        $mtime = $this->updated_at?->getTimestamp();
        if (!$mtime) {
            return $url;
        }
        return $url . '?v=' . $mtime;
    }
}
