<?php
/***********************************************************************************
 * The contents of this file are subject to the Extension License Agreement
 * ("Agreement") which can be viewed at
 * https://www.espocrm.com/extension-license-agreement/.
 * By copying, installing downloading, or using this file, You have unconditionally
 * agreed to the terms and conditions of the Agreement, and You may not use this
 * file except in compliance with the Agreement. Under the terms of the Agreement,
 * You shall not license, sublicense, sell, resell, rent, lease, lend, distribute,
 * redistribute, market, publish, commercialize, or otherwise transfer rights or
 * usage to the software or any modified version or derivative work of the software
 * created by or for you.
 *
 * Copyright (C) 2015-2025 Letrium Ltd.
 *
 * License ID: a67be8f75bc1974a987315ddc1024a78
 ************************************************************************************/

namespace Espo\Modules\Sales\Classes\Record\Hooks\Quote;

use Espo\Core\Record\Hook\SaveHook;
use Espo\Core\Utils\FieldUtil;
use Espo\Core\Utils\Metadata;
use Espo\Modules\Crm\Entities\Opportunity;
use Espo\Modules\Sales\Entities\Product;
use Espo\Modules\Sales\Tools\Sales\OrderEntity;
use Espo\ORM\Entity;
use Espo\ORM\EntityManager;
use stdClass;

/**
 * Prepares product attributes in items.
 *
 * @implements SaveHook<OrderEntity|Opportunity>
 */
class EarlyBeforeSavePrepare implements SaveHook
{
    private const ATTR_ITEM_LIST = 'itemList';

    public function __construct(
        private EntityManager $entityManager,
        private Metadata $metadata,
        private FieldUtil $fieldUtil,
    ) {}

    public function process(Entity $entity): void
    {
        if (!$entity->has(self::ATTR_ITEM_LIST)) {
            return;
        }

        $items = $entity->get(self::ATTR_ITEM_LIST);

        if (!is_array($items)) {
            return;
        }

        $itemEntityType = $entity->getEntityType() . 'Item';

        $copyFieldList = $this->getCopyFieldList($itemEntityType);

        if ($copyFieldList === []) {
            return;
        }

        foreach ($items as $item) {
            if (!$item instanceof stdClass) {
                continue;
            }

            $this->prepareItem($item, $copyFieldList);
        }

        $entity->set(self::ATTR_ITEM_LIST, $items);
    }

    /**
     * @param stdClass $item
     * @param string[] $copyFieldList
     */
    private function prepareItem(stdClass $item, array $copyFieldList): void
    {
        $productId = $item->productId ?? null;

        if (!is_string($productId)) {
            return;
        }

        $attributeList = [];

        foreach ($copyFieldList as $field) {
            $itemAttributeList = $this->fieldUtil->getActualAttributeList(Product::ENTITY_TYPE, $field);

            $has = false;

            foreach ($itemAttributeList as $attribute) {
                if (property_exists($item, $attribute)) {
                    $has = true;

                    break;
                }
            }

            if ($has) {
                continue;
            }

            $attributeList = array_merge($attributeList, $itemAttributeList);
        }

        if ($attributeList === []) {
            return;
        }

        $product = $this->entityManager->getRDBRepositoryByClass(Product::class)->getById($productId);

        if (!$product) {
            return;
        }

        foreach ($attributeList as $attribute) {
            $item->$attribute = $product->get($attribute);
        }
    }

    /**
     * @return string[]
     */
    private function getCopyFieldList(string $itemEntityType): array
    {
        return $this->metadata->get("entityDefs.$itemEntityType.fields.product.copyFieldList") ?? [];
    }
}
