<?php

namespace App\Traits;

use App\Services\AuditService;

trait Auditable
{
    protected static $auditingEnabled = true;

    public static function bootAuditable()
    {
        static::created(function ($model) {
            if (self::$auditingEnabled)
                self::logToAudit('CREATED', $model);
        });

        static::updated(function ($model) {
            if (self::$auditingEnabled)
                self::logToAudit('UPDATED', $model);
        });

        static::deleted(function ($model) {
            if (self::$auditingEnabled)
                self::logToAudit('DELETED', $model);
        });
    }

    public static function withoutAuditing(callable $callback)
    {
        $original = self::$auditingEnabled;
        self::$auditingEnabled = false;

        try {
            return $callback();
        } finally {
            self::$auditingEnabled = $original;
        }
    }

    protected static function logToAudit($action, $model)
    {
        $className = class_basename($model);
        // Split camel case to words: StockBatch -> Stock Batch
        $module = trim(preg_replace('/(?<!\ )[A-Z]/', ' $0', $className));

        $description = "$action $module";

        // Add specific details
        if ($model->batch_no) {
            $description .= " ($model->batch_no)";
        } elseif ($model->invoice_no) {
            $description .= " ($model->invoice_no)";
        } elseif ($model->name) {
            $description .= " ($model->name)";
        } else {
            $description .= " #{$model->id}";
        }

        $metadata = $model->getChanges(); // For updates

        AuditService::log($action, $module, $description, $model, $metadata);
    }
}
