<?php

namespace App\Models;

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

class StockOpnameChangeLog extends Model
{
    use HasFactory;

    protected $table = 't_stock_opname_change_logs';
    
    // Disable Laravel's automatic timestamps since we use custom changed_at
    public $timestamps = false;

    protected $fillable = [
        'so_detail_id',
        'field_name',
        'old_value',
        'new_value',
        'changed_by',
        'changed_at',
        'ip_address',
        'user_agent',
        'created_at',
        'updated_at',
    ];

    protected $casts = [
        'changed_at' => 'datetime',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
        'old_value' => 'decimal:2',
        'new_value' => 'decimal:2',
    ];

    public function stockOpnameDetail()
    {
        return $this->belongsTo(StockOpnameDetail::class, 'so_detail_id');
    }

    public function changedBy()
    {
        return $this->belongsTo(User::class, 'changed_by');
    }

    // Create change log entry
    public static function logChange($soDetailId, $fieldName, $oldValue, $newValue)
    {
        $now = now();
        
        return static::create([
            'so_detail_id' => $soDetailId,
            'field_name' => $fieldName,
            'old_value' => $oldValue,
            'new_value' => $newValue,
            'changed_by' => auth()->id(),
            'changed_at' => $now,
            'ip_address' => request()->ip(),
            'user_agent' => request()->userAgent(),
            'created_at' => $now,
            'updated_at' => $now,
        ]);
    }

    // Get change history for a specific SO detail
    public static function getChangeHistory($soDetailId)
    {
        return static::where('so_detail_id', $soDetailId)
            ->with('changedBy')
            ->orderBy('changed_at', 'desc')
            ->get();
    }

    // Cleanup old logs (3 months)
    public static function cleanupOldLogs()
    {
        return static::where('changed_at', '<', now()->subMonths(3))->delete();
    }
}