<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class PriceHistory extends Model
{
    use HasFactory;

    protected $fillable = [
        'product_id', 'user_id',
        'price_type', 'old_price', 'new_price',
        'change_reason', 'notes', 'effective_from',
    ];

    protected $casts = [
        'old_price' => 'decimal:2',
        'new_price' => 'decimal:2',
        'effective_from' => 'date',
    ];

    protected $appends = [
        'price_change',
        'percentage_change',
        'price_type_label',
    ];

    /**
     * Relationships
     */
    public function product(): BelongsTo
    {
        return $this->belongsTo(Product::class);
    }

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

    /**
     * Accessors
     */
    public function getPriceChangeAttribute(): float
    {
        return $this->new_price - $this->old_price;
    }

    public function getPercentageChangeAttribute(): float
    {
        if ($this->old_price == 0) return 0;
        return (($this->new_price - $this->old_price) / $this->old_price) * 100;
    }

    public function getPriceTypeLabelAttribute(): string
    {
        return match($this->price_type) {
            'cost_price' => 'Cost Price',
            'sale_price' => 'Sale Price',
            'wholesale_price' => 'Wholesale Price',
            default => ucfirst(str_replace('_', ' ', $this->price_type)),
        };
    }

    /**
     * Scopes
     */
    public function scopeByProduct($query, $productId)
    {
        return $query->where('product_id', $productId);
    }

    public function scopeByPriceType($query, $priceType)
    {
        return $query->where('price_type', $priceType);
    }
}