<?php

namespace FiloBlu\Flow\Model\Channel\In;

/**
 * Class Ite
 * Load received ite file into db
 *
 * @package FiloBlu\Flow\Model\Channel\In
 */
class Ite extends AbstractModel
{
    /**
     * Insert row read from source (Usually a CSV file) into db table.
     * The $data will be an associaive array like
     * @verbatim
     * [
     * 'codice_articolo'               => "ZA36PEL5128383A8 "
     * 'codice_articolo_del_fornitore' => "1234567890"
     * 'nome_articolo'                 => "ZANELLACCIO - SORGENTE "
     * 'codice_configurabile'          => ""
     * 'configurable_attributes'       => "size"
     * 'configurable_values'           => "UNICA"
     * 'fascia_iva_articoli'           => "STD"
     * 'visibility'                    => "4"
     * ]
     *
     * @param $data
     * @return bool
     */
    public function insertData($data)
    {
        $flow = $this->getFile()->getData('flow');
        $model = $this->objectManager->create("FiloBlu\Flow\Model\\{$flow}");

        if (!$model) {
            return false;
        }

        $model->setData('meta_file', $this->getFile()->getId());
        $model->setData('meta_processed', 0);
        $model->setData('meta_insert_time', date('Y-m-d H:i:s'));

        $usesMap = isset($this->map) && $this->getChannelConfig()->usesMap();

        foreach ($data as $field => $value) {

            if (!$usesMap) {
                $model->setData($field, $value);
                continue;
            }

            // Get the mapping
            $fieldMap = $this->map->get($field);
            // I need to skip this?
            if (isset($fieldMap['skip']) && $fieldMap['skip']) {
                continue;
            }

            $toField = $field;

            // Have a destination field? Set that as a 'to field'
            if (isset($fieldMap['to']) && $fieldMap['to']) {
                $toField = $fieldMap['to'];
            }

            $model->setData($toField, $value);
        }

        if (empty(trim($model->getCodiceArticolo() ?? ''))) {
            return false;
        }

        // If Product is only simple I need to reset configurable_attributes and configurable_values.
        // This prevents the creation of wrong configurable product of simple
        if (empty($model->getCodiceConfigurabile()) || trim($model->getCodiceConfigurabile()) === trim($model->getCodiceArticolo())) {
            $model->setData('configurable_attributes', null);
            $model->setData('configurable_values', null);
        }

        return $model->save();
    }
}
