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



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


class VersionHook
{
// An optional parameter, defines in which order hooks will be processed.
    // Lesser value means sooner.
    public static int $order = 5; 
	private $entityManager;

    public function __construct(EntityManager $entityManager) {
	
	$this->entityManager = $entityManager;
        // Define needed dependencies.
    } 
	

    public function beforeSave(Entity $entity, array $options): void 
    {
     
        if (!$entity->isNew()) {
          $beforeEntity = $this->entityManager->getEntity($entity->getEntityType(), $entity->id);
          $beforeValues = $beforeEntity->toArray();
          $currentValues = $entity->toArray();

          //unset($currentValues['id']);
          unset($beforeValues['id']);

          $attributeValue = $entity->get('attributeName');

          $newhire = $this->entityManager->getEntity($entity->getEntityType());
          //$newhire->set($currentValues);
          $newhire->set($beforeValues);

          $newhire->set("status", "Arhiva");
          $this->entityManager->saveEntity($newhire, ['silent' => true]);

          //$entity->set($beforeValues);
          $this->entityManager->getRepository('Document')->relate($newhire, 'documentParent', $entity->id);
          $teams = $entity->get('teams');
          if ($teams) {
            foreach ($teams as $team) {
              $teamId = $team->id; // This is the team ID
              $this->entityManager->getRepository('Document')->relate($newhire, 'teams', $teamId);
            }
          }
        }
    }
}
?>