<?php

namespace App\Models;

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

class PriceAdjustmentLog extends Model
{
    protected $fillable = [
        'user_id',
        'adjustment_type',
        'operation',
        'price_type',
        'adjustment_value',
        'products_updated',
        'notes',
    ];

    protected $casts = [
        'adjustment_value' => 'decimal:2',
        'products_updated' => 'integer',
    ];

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

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

    public function getFormattedTypeAttribute(): string
    {
        return $this->adjustment_type === 'percentage' ? 'Percentage (%)' : 'Fixed Amount (Kes)';
    }

    public function getFormattedOperationAttribute(): string
    {
        return ucfirst($this->operation);
    }

    public function getFormattedPriceTypeAttribute(): string
    {
        $types = [
            'cost' => 'Cost Price',
            'selling' => 'Selling Price',
            'both' => 'Both Prices',
        ];

        return $types[$this->price_type] ?? $this->price_type;
    }

    public function getFormattedValueAttribute(): string
    {
        if ($this->adjustment_type === 'percentage') {
            return $this->adjustment_value.'%';
        }

        return 'Kes '.number_format($this->adjustment_value, 2);
    }

    public function getTotalCostChangeAttribute(): float
    {
        return $this->details->sum(function ($d) {
            return $d->new_cost_price - $d->old_cost_price;
        });
    }

    public function getTotalSellingChangeAttribute(): float
    {
        return $this->details->sum(function ($d) {
            return $d->new_selling_price - $d->old_selling_price;
        });
    }
}
