<?php

namespace Ignite\Core\Entities;

use Illuminate\Database\Eloquent\Model;
use OwenIt\Auditing\Audit as AuditTrait;
use OwenIt\Auditing\Contracts\Audit as AuditContract;

class Audit extends Model implements AuditContract
{
    use AuditTrait;

    /**
     * {@inheritdoc}
     */
    protected $table = 'core_audit';

    /**
     * {@inheritdoc}
     */
    protected $guarded = [];

    /**
     * {@inheritdoc}
     */
    protected $casts = [
        'old_values' => 'json',
        'new_values' => 'json',
    ];

    /**
     * Get the readable name for the auditable class entity.
     *
     * @return string
     */
    public function getReadableEntityName()
    {
        return ucwords(snake_case(class_basename($this->auditable_type), ' '));
    }

    /**
     * Get the readable identifier for the audited record.
     *
     * @return string
     */
    public function getReadableIdentifier()
    {
        $join = ' ';
        $field = $this->auditable_type::getAuditFriendlyField();
        if (method_exists($this->auditable_type, 'getAuditFriendlyFieldJoinCharacter')) {
            $join = $this->auditable_type::getAuditFriendlyFieldJoinCharacter();
        }

        if (is_array($field)) {
            foreach ($field as $attribute) {
                $values[] = $this->getReadableValueByAttributeKey($attribute);
            }
            return implode($join, $values);
        }

        return $this->getReadableValueByAttributeKey($field);
    }

    /**
     * Get a value from the correct value array by attribute.
     *
     * @param  string $attribute
     * @return string
     */
    private function getReadableValueByAttributeKey($attribute)
    {
        if ($this->event === 'deleted') {
            return $this->old_values[$attribute] ?? $attribute;
        }

        return $this->new_values[$attribute] ?? $attribute;
    }
}
