<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class OrderLog extends Model
{
    protected $fillable = [
        'order_id', 
        'user_id', 
        'action', 
        'old_data', 
        'new_data'
    ];

    protected $casts = [
        'old_data' => 'array',
        'new_data' => 'array',
        'created_at' => 'datetime',
        'updated_at' => 'datetime'
    ];

    /**
     * Get the order that owns the log entry
     */
    public function order()
    {
        return $this->belongsTo(Order::class);
    }

    /**
     * Get the user who made the change
     */
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    /**
     * Get formatted action name
     */
    public function getActionLabelAttribute()
    {
        return ucfirst(str_replace('_', ' ', $this->action));
    }

    /**
     * Get a description of what changed
     */
    public function getChangeDescriptionAttribute()
    {
        if (!$this->old_data || !$this->new_data) {
            return 'Data modified';
        }

        $changes = [];
        foreach ($this->new_data as $key => $newValue) {
            $oldValue = $this->old_data[$key] ?? null;
            if ($oldValue != $newValue) {
                $changes[] = ucfirst(str_replace('_', ' ', $key));
            }
        }

        return count($changes) > 0 
            ? 'Changed: ' . implode(', ', $changes)
            : 'No changes detected';
    }
}