<?php

namespace App\Models;

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

class ProductPriceHistory extends Model
{
    protected $table = 'product_price_history';

    protected $fillable = [
        'product_id',
        'user_id',
        'price_adjustment_log_id',
        'old_cost_price',
        'new_cost_price',
        'old_selling_price',
        'new_selling_price',
        'reason',
    ];

    protected $casts = [
        'old_cost_price' => 'decimal:2',
        'new_cost_price' => 'decimal:2',
        'old_selling_price' => 'decimal:2',
        'new_selling_price' => 'decimal:2',
    ];

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

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

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

    public function getCostChangeAttribute(): float
    {
        return (float) $this->new_cost_price - (float) $this->old_cost_price;
    }

    public function getSellingChangeAttribute(): float
    {
        return (float) $this->new_selling_price - (float) $this->old_selling_price;
    }

    public function getCostChangePercentAttribute(): float
    {
        if ((float) $this->old_cost_price == 0) {
            return 0;
        }

        return ($this->cost_change / (float) $this->old_cost_price) * 100;
    }

    public function getSellingChangePercentAttribute(): float
    {
        if ((float) $this->old_selling_price == 0) {
            return 0;
        }

        return ($this->selling_change / (float) $this->old_selling_price) * 100;
    }

    public function getOldMarginAttribute(): float
    {
        if ((float) $this->old_cost_price == 0) {
            return 0;
        }

        return ((float) $this->old_selling_price - (float) $this->old_cost_price) / (float) $this->old_cost_price * 100;
    }

    public function getNewMarginAttribute(): float
    {
        if ((float) $this->new_cost_price == 0) {
            return 0;
        }

        return ((float) $this->new_selling_price - (float) $this->new_cost_price) / (float) $this->new_cost_price * 100;
    }
}
