<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Facades\Storage;

class Product extends Model
{
    protected $fillable = [
        'category_id',
        'name',
        'description',
        'price',
        'stock',
        'image',
        'images',
        'is_active',
        'is_custom',
        'points_earned',
    ];

    protected $casts = [
        'price' => 'decimal:2',
        'stock' => 'integer',
        'is_active' => 'boolean',
        'is_custom' => 'boolean',
        'points_earned' => 'integer',
        'images' => 'array',
    ];

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

    public function carts(): HasMany
    {
        return $this->hasMany(Cart::class);
    }

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

    public function sizes(): BelongsToMany
    {
        return $this->belongsToMany(Size::class)
            ->withPivot('stock', 'price')
            ->withTimestamps();
    }

    /**
     * حساب المخزون الفعلي (من القياسات إذا كان موجوداً، وإلا من المخزون الأساسي)
     */
    public function getActualStockAttribute(): int
    {
        if ($this->sizes()->count() > 0) {
            return $this->sizes()->sum('product_size.stock');
        }
        return $this->stock;
    }

    /**
     * تحديث المخزون الأساسي من مجموع القياسات
     */
    public function updateStockFromSizes(): void
    {
        if ($this->sizes()->count() > 0) {
            $totalStock = $this->sizes()->sum('product_size.stock');
            $this->stock = $totalStock;
            $this->save();
        }
    }

    /**
     * Get the normalized image URL
     * Handles both full URLs and relative paths
     */
    public function getImageUrlAttribute(): ?string
    {
        if (!$this->image) {
            return null;
        }

        // If it's already a full URL, extract the path
        if (str_starts_with($this->image, 'http')) {
            // Extract the path from the URL
            $parsedUrl = parse_url($this->image);
            if (isset($parsedUrl['path'])) {
                // Remove leading slash and storage/ prefix if present
                $path = ltrim($parsedUrl['path'], '/');
                if (str_starts_with($path, 'storage/')) {
                    $path = substr($path, 8); // Remove 'storage/' prefix
                }
                // Use Storage::url() which handles the URL generation correctly
                return Storage::disk('public')->url($path);
            }
            // If we can't parse it, return as is (might be external URL)
            return $this->image;
        }

        // It's a relative path, use Storage::url() which handles it correctly
        $path = ltrim($this->image, '/');
        if (str_starts_with($path, 'storage/')) {
            $path = substr($path, 8); // Remove 'storage/' prefix
        }
        
        return Storage::disk('public')->url($path);
    }
}

