<?php
namespace Espo\Custom\Hooks\Document;

use Espo\ORM\Entity;
use Espo\ORM\EntityManager;

class VersionHook
{
    public static int $order = 5;
    private $entityManager;

    public function __construct(EntityManager $entityManager) {
        $this->entityManager = $entityManager;
    } 

    public function beforeSave(Entity $entity, array $options): void {
        if (!$entity->isNew()) {
            // Fetch the original entity before updates
            $originalEntity = $this->entityManager->getEntity($entity->getEntityType(), $entity->id);
            $originalValues = $originalEntity->toArray();
            unset($originalValues['id']);

            // Update status of the original entity
            $this->updateStatus($originalEntity);

            // Create a new version based on the original entity's state before updates
            $newVersion = $this->entityManager->getEntity($entity->getEntityType());
            $newVersion->set($originalValues);
            $this->entityManager->saveEntity($newVersion);

            // Relate the new version to the original entity
            $this->entityManager->getRepository('Document')->relate($newVersion, 'documentParent', $entity->id);
        }
    }

    private function updateStatus(Entity $entity): void {
        // Update the status of the original entity as needed
        $entity->set('status', 'Arhivă'); // Replace 'YourNewStatus' with the appropriate status
        $this->entityManager->saveEntity($entity);
    }
}

?>