<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use App\Traits\HasAuditLog;
use App\Scopes\ProductOwnerScope;

class Product extends Model
{
    use HasAuditLog, SoftDeletes;

    protected static function booted()
    {
        static::addGlobalScope(new ProductOwnerScope);
    }

    protected static function boot()
    {
        parent::boot();

        static::updating(function ($product) {
            if ($product->isDirty(['purchase_price', 'sale_price'])) {
                \App\Models\PriceHistory::create([
                    'product_id' => $product->id,
                    'user_id' => auth()->id() ?? 1,
                    'old_purchase_price' => $product->getOriginal('purchase_price'),
                    'new_purchase_price' => $product->purchase_price,
                    'old_sale_price' => $product->getOriginal('sale_price'),
                    'new_sale_price' => $product->sale_price,
                ]);
            }
        });
    }
    protected $fillable = [
        'supplier_id',
        'category_id',
        'sku',
        'name',
        'description',
        'image',
        'min_stock',
        'stock',
        'purchase_price',
        'sale_price'
    ];

    /**
     * Get the supplier that owns the product.
     */
    public function supplier(): BelongsTo
    {
        return $this->belongsTo(Supplier::class);
    }

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

    /**
     * Get the sale items for the product.
     */
    public function saleItems(): HasMany
    {
        return $this->hasMany(SaleItem::class);
    }

    /**
     * Get the stock movements for the product.
     */
    public function stockMovements(): HasMany
    {
        return $this->hasMany(StockMovement::class);
    }

    /**
     * Get the price history for the product.
     */
    public function priceHistories(): HasMany
    {
        return $this->hasMany(PriceHistory::class);
    }

    /**
     * Register a stock movement.
     */
    public function registerStockMovement(int $quantity, string $type, string $reason, $referenceId = null, $referenceType = null)
    {
        $previousStock = $this->stock;
        
        if ($type === 'in') {
            $this->increment('stock', $quantity);
        } else {
            $this->decrement('stock', $quantity);
        }

        $this->refresh();

        return $this->stockMovements()->create([
            'user_id' => auth()->id() ?? 1,
            'type' => $type,
            'quantity' => $quantity,
            'reason' => $reason,
            'reference_id' => $referenceId,
            'reference_type' => $referenceType,
            'previous_stock' => $previousStock,
            'current_stock' => $this->stock,
        ]);
    }
}
