<?php

declare(strict_types=1);

/**
 * @author Amasty Team
 * @copyright Copyright (c) Amasty (https://www.amasty.com)
 * @package Jet Theme Backend for Magento 2 (System)
 */

namespace Amasty\JetTheme\Model\FooterLink;

use Magento\Framework\Model\AbstractModel;

trait StoresTrait
{
    /**
     * @inheritdoc
     */
    protected function _getLoadSelect($field, $value, $object)
    {
        $select = parent::_getLoadSelect($field, $value, $object);

        $table = $this->getMainTable();
        $select->joinLeft(
            ['stores' => $this->getTable($this->storeConfig['storeTableName'])],
            $table . '.'
            . $this->storeConfig['entityId']
            . ' = stores.'
            . $this->storeConfig['entityIdField'],
            []
        );
        $this->dbHelper->addGroupConcatColumn(
            $select,
            'stores',
            'stores.store_id'
        );

        return $select;
    }

    /**
     * @param AbstractModel $object
     */
    protected function updateStores(AbstractModel $object): void
    {
        if (!$object->hasData($this->storeConfig['stores'])) {
            return;
        }

        $connection = $this->getConnection();
        $footerLinkId = $object->getId();

        $table = $this->getTable($this->storeConfig['storeTableName']);
        $select = $connection->select()
            ->from($table, $this->storeConfig['storeIdField'])
            ->where($this->storeConfig['entityIdField'] . ' = ?', $footerLinkId);
        $oldData = $connection->fetchCol($select);
        $newData = is_array($object->getStores()) ? $object->getStores() : explode(',', $object->getStores());

        if (is_array($newData)) {
            $toDelete = array_diff($oldData, $newData);
            $toInsert = array_diff($newData, $oldData);
            $toInsert = array_diff($toInsert, ['']);
        } else {
            $toDelete = $oldData;
            $toInsert = null;
        }

        if (!empty($toDelete)) {
            $deleteSelect = clone $select;
            $deleteSelect->where('store_id IN (?)', $toDelete);
            $query = $connection->deleteFromSelect($deleteSelect, $table);
            $connection->query($query);
        }

        if (!empty($toInsert)) {
            $insertArray = [];
            foreach ($toInsert as $value) {
                $insertArray[] = [
                    $this->storeConfig['entityIdField'] => $footerLinkId,
                    $this->storeConfig['storeIdField'] => $value
                ];
            }

            $connection->insertMultiple($table, $insertArray);
        }
    }

    /**
     * @return void
     */
    protected function joinStores(): void
    {
        $select = $this->getSelect();
        $select->joinLeft(
            ['stores' => $this->getTable($this->storeConfig['storeTableName'])],
            'main_table.'
            . $this->storeConfig['entityId']
            . ' = stores.'
            . $this->storeConfig['entityIdField'],
            []
        );

        $select->group('main_table.entity_id');
        $this->dbHelper->addGroupConcatColumn(
            $select,
            'stores',
            'stores.store_id'
        );
    }
}
