<?php

namespace App\Models;

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

class ActivityLog extends Model
{
    use HasFactory;

    public $timestamps = false;

    protected $fillable = [
        'user_id',
        'finance_user_id',
        'user_type',
        'action',
        'module',
        'description',
        'ip_address',
        'user_agent',
        'old_data',
        'new_data',
    ];

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

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

    /**
     * Get the finance user
     */
    public function financeUser()
    {
        return $this->belongsTo(FinanceUser::class);
    }

    /**
     * Log an activity
     */
    public static function log($action, $module, $description, $oldData = null, $newData = null)
    {
        $user = auth()->user();
        $userType = 'backoffice';
        $userId = $user ? $user->id : null;
        $financeUserId = null;

        if (auth()->guard('finance')->check()) {
            $user = auth()->guard('finance')->user();
            $userType = 'finance';
            $userId = null;
            $financeUserId = $user ? $user->id : null;
        }

        return static::create([
            'user_id' => $userId,
            'finance_user_id' => $financeUserId,
            'user_type' => $userType,
            'action' => $action,
            'module' => $module,
            'description' => $description,
            'ip_address' => request()->ip(),
            'user_agent' => request()->userAgent(),
            'old_data' => $oldData,
            'new_data' => $newData,
        ]);
    }
}
