<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Spatie\Activitylog\Traits\LogsActivity;
use Spatie\Activitylog\LogOptions;

class ItemVariation extends Model
{
	use LogsActivity;

	protected $table = 'item_variations';

	protected $fillable = [
		'item_id',
		'name',
		'sku_suffix',
		'size',
		'color',
		'unit',
		'length',
		'width',
		'height',
		'weight',
		'weight_unit',
		'cost_price',
		'selling_price',
		'is_active',
		'description',
	];

	protected $casts = [
		'length' => 'decimal:2',
		'width' => 'decimal:2',
		'height' => 'decimal:2',
		'weight' => 'decimal:2',
		'cost_price' => 'decimal:4',
		'selling_price' => 'decimal:4',
		'is_active' => 'boolean',
	];

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

	// New relationships
	public function itemSuppliers(): HasMany
	{
		return $this->hasMany(ItemSupplier::class);
	}

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

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

	public function scopeForItem($query, $itemId)
	{
		return $query->where('item_id', $itemId);
	}

	// Helper methods
	public function getFullSkuAttribute()
	{
		$sku = $this->item->sku;
		if ($this->sku_suffix) {
			$sku .= '-' . $this->sku_suffix;
		}
		return $sku;
	}

	public function getDimensionsAttribute()
	{
		$dimensions = [];
		if ($this->length) $dimensions[] = $this->length . 'L';
		if ($this->width) $dimensions[] = $this->width . 'W';
		if ($this->height) $dimensions[] = $this->height . 'H';

		return implode(' x ', $dimensions);
	}

	public function getFormattedCostPriceAttribute()
	{
		return $this->cost_price ? format_currency($this->cost_price) : '-';
	}

	public function getFormattedSellingPriceAttribute()
	{
		return $this->selling_price ? format_currency($this->selling_price) : '-';
	}

	public function getFormattedWeightAttribute()
	{
		return $this->weight ? $this->weight . ' ' . $this->weight_unit : '-';
	}

	public function getTotalStockAttribute()
	{
		return $this->inventories()->sum('quantity');
	}

	public function getAvailableStockAttribute()
	{
		return $this->inventories()->sum(\DB::raw('quantity - reserved_quantity'));
	}

	public function getActivitylogOptions(): LogOptions
	{
		return LogOptions::defaults()
			->useLogName('item_variation')
			->logFillable()
			->logOnlyDirty()
			->dontSubmitEmptyLogs();
	}
}
