<?php

namespace App\Models;

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

class ConfigurationHistory extends Model
{
    protected $table = 'configuration_history';

    protected $fillable = ['key', 'old_value', 'new_value', 'changed_by', 'change_reason'];

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

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

    /**
     * Log a configuration change
     */
    public static function logChange($key, $oldValue, $newValue, $changedBy = null, $reason = null)
    {
        return static::create([
            'key' => $key,
            'old_value' => is_array($oldValue) ? json_encode($oldValue) : $oldValue,
            'new_value' => is_array($newValue) ? json_encode($newValue) : $newValue,
            'changed_by' => $changedBy,
            'change_reason' => $reason,
        ]);
    }

    /**
     * Get history for a specific configuration key
     */
    public static function getHistory($key, $limit = 50)
    {
        return static::where('key', $key)
            ->orderBy('created_at', 'desc')
            ->limit($limit)
            ->get();
    }

    /**
     * Get all changes made by a user
     */
    public static function getChangesByUser($userId, $limit = 100)
    {
        return static::where('changed_by', $userId)
            ->orderBy('created_at', 'desc')
            ->limit($limit)
            ->get();
    }

    /**
     * Get changes within a date range
     */
    public static function getChangesBetween($startDate, $endDate)
    {
        return static::whereBetween('created_at', [$startDate, $endDate])
            ->orderBy('created_at', 'desc')
            ->get();
    }
}

