<?php

namespace App\Imports;

use App\Model\product\CategoryModel;
use App\Model\product\ProductModel;
use App\Model\product\UnitModel;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithCalculatedFormulas;

class MaterialImport implements ToModel, WithHeadingRow, WithCalculatedFormulas
{
    public function model(array $row)
    {
        $product = ProductModel::where('barcode',$row['barcode'])->exists();
        if (@$row['barcode'] && !$product) {
            // need to use code -> must import or create first
            $where = ['product_name' => $row['material'], 'barcode' => $row['barcode'], 'type' => 'material'];
            $unit = ['unit' => $row['unit'], 'type' => 'material'];
            $sub_unit = ['unit' => $row['sub_unit'], 'type' => 'material'];
            $category = ['category_name' => $row['category'], 'type' => 'material'];
            $unit = UnitModel::updateOrCreate($unit, $unit);
            $sub_unit = UnitModel::updateOrCreate($sub_unit,$sub_unit);
            $category = CategoryModel::updateOrCreate($category,$category );

            ProductModel::updateOrCreate(
                $where,
                [
                    'type' => 'material',
                    'unit_id' => $unit->id,
                    'child_unit' => $sub_unit->id,
                    'category_id' => $category->id,
                    'product_name' => $row['material'],
                    'barcode' => $row['barcode'],
                    'status' => 1,
                    'cost_riel' => $row['cost_riel'],
                    'cost_usd' => $row['cost_usd'],
                ]
            );
        }
    }

//        public function onFailure(Failure ...$failures)
//        {
//            // TODO: Implement onFailure() method.
//        }
}
