<?php

namespace apexl\Io\modules\product\callbacks;

use apexl\Io\modules\product\entities\productEntity;

class entityStoreCallback {

    public static function insert($data, $table, $extraStore, $extends)
    {
        if (isset($extends->foreignKey) && isset($extraStore['product_name']) && $extends->entity == 'apexl\Io\modules\product\entities\productEntity') {
            $product = new productEntity();
            foreach (['product_name','is_default','parent_id','type','description','code','price','invoice_nominal_code','has_subscription','frontend_id'] as $field) {
                if (isset($extraStore[$field])) $product->$field = $extraStore[$field];
            }
            $product->store();
            $data[$extends->foreignKey] = $product->id;
        }

        return $data;
    }

    public static function update($data, $table, $extraStore, $extends)
    {

        if (isset($extends->foreignKey) && isset($extraStore['price']) && $extends->entity == 'apexl\Io\modules\product\entities\productEntity' && isset($data[$extends->foreignKey])) {

            $product = new productEntity();
            $product->load($data[$extends->foreignKey]);
            foreach (['product_name','is_default','parent_id','type','description','code','price','invoice_nominal_code','has_subscription','frontend_id'] as $field) {
                if (isset($extraStore[$field])) $product->$field = $extraStore[$field];
            }
            foreach (['weight_kg','sku'] as $field) {
                if (isset($extraStore[$field]) && trim($extraStore[$field]) != "") $product->$field = $extraStore[$field];
            }

            $product->store();
            $data[$extends->foreignKey] = $product->id;
        }

        return $data;
    }
}