<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use App\Services\CurrencyService;
use Spatie\Translatable\HasTranslations;

class Product extends Model
{
    use HasFactory, HasTranslations;

    protected $fillable = [
        'category_id',
        'vendor_id',
        'name',
        'slug',
        'description',
        'short_description',
        'price',
        'sale_price',
        'stock_quantity',
        'image',
        'is_active',
        'is_featured',
        'discount_type',
        'discount_value',
        'discount_start',
        'discount_end',
    ];

    protected $casts = [
        'price' => 'decimal:2',
        'sale_price' => 'decimal:2',
        'discount_value' => 'decimal:2',
        'discount_start' => 'datetime',
        'discount_end' => 'datetime',
        'is_active' => 'boolean',
    ];

    public $translatable = ['name', 'description', 'short_description'];

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

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

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

    public function tags()
    {
        return $this->belongsToMany(Tag::class);
    }

    public function getRouteKeyName()
    {
        return 'slug';
    }

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

    public function inStock()
    {
        return $this->stock_quantity > 0;
    }

    public function isOnSale()
    {
        return $this->sale_price !== null && $this->sale_price < $this->price;
    }

    public function getImageUrlAttribute()
    {
        return $this->image ? asset('storage/' . $this->image) : 'https://via.placeholder.com/400';
    }

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

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

    public function isDiscounted()
    {
        if (!$this->discount_type || !$this->discount_value) return false;
        $now = now();
        if ($this->discount_start && $now->lt($this->discount_start)) return false;
        if ($this->discount_end && $now->gt($this->discount_end)) return false;
        return true;
    }

    public function getFinalPriceAttribute()
    {
        if ($this->isDiscounted()) {
            if ($this->discount_type === 'percent') {
                return round($this->price * (1 - $this->discount_value / 100), 2);
            } else {
                return max(0, $this->price - $this->discount_value);
            }
        }
        return $this->price;
    }

    // Currency conversion methods
    public function getCurrentPrice($currency = 'USD')
    {
        $basePrice = $this->getFinalPriceAttribute();
        return $this->convertCurrency($basePrice, 'USD', $currency);
    }

    public function getPriceInCurrency($currency = 'USD')
    {
        return $this->convertCurrency($this->price, 'USD', $currency);
    }

    public function getSalePriceInCurrency($currency = 'USD')
    {
        if (!$this->sale_price) return null;
        return $this->convertCurrency($this->sale_price, 'USD', $currency);
    }

    public function getFinalPriceInCurrency($currency = 'USD')
    {
        $finalPrice = $this->getFinalPriceAttribute();
        return $this->convertCurrency($finalPrice, 'USD', $currency);
    }

    private function convertCurrency($amount, $fromCurrency, $toCurrency)
    {
        $currencyService = app(CurrencyService::class);
        return $currencyService->convert($amount, $fromCurrency, $toCurrency);
    }

    public function getCurrencySymbol($currency = 'USD')
    {
        $currencyService = app(CurrencyService::class);
        return $currencyService->getSymbol($currency);
    }

    public function formatPrice($currency = 'USD')
    {
        $currencyService = app(CurrencyService::class);
        $price = $this->getCurrentPrice($currency);
        return $currencyService->formatPrice($price, $currency);
    }
}
