<?php

namespace App\Imports;

use App\Model\product\BrandModel;
use App\Model\product\CategoryModel;
use App\Model\product\ColorModel;
use App\Model\product\ProductModel;
use App\Model\product\ProductUnitModel;
use App\Model\product\SizeModel;
use App\Model\product\UnitModel;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithCalculatedFormulas;
use phpDocumentor\Reflection\Type;

class FabricImport implements ToModel, WithHeadingRow, WithCalculatedFormulas
{
    public function model(array $row)
    {
        $product = ProductModel::where('barcode',$row['barcode'])->first();
        if (@$row['barcode']) {
            // need to use code -> must import or create first
            if($product){
                $where = ['id' => $product->id,'type' => 'fabric'];
                $data = [
                    'type' => 'fabric',
                    'unit_id' => $product->unit_id,
                    'child_unit' => $product->child_unit,
                    'category_id' => $product->category_id,
                    'product_name' => $row['fabric']??$product->product_name,
                    'barcode' => $product->barcode,
                    'status' => 1,
                    'cost_riel' => $row['cost_riel'],
                    'cost_usd' => $row['cost_usd'],
                ];
            }else{
                $unit = ['unit' => $row['unit'], 'type' => 'fabric'];
                $sub_unit = ['unit' => $row['sub_unit'], 'type' => 'fabric'];
                $category = ['category_name' => $row['category'], 'type' => 'fabric'];
                $unit = UnitModel::updateOrCreate($unit, $unit);
                $sub_unit = UnitModel::updateOrCreate($sub_unit,$sub_unit);
                $category = CategoryModel::updateOrCreate($category,$category );
                $where = ['product_name' => $row['fabric'], 'barcode' => $row['barcode'], 'type' => 'fabric'];
                $data = [
                    'type' => 'fabric',
                    'unit_id' => $unit->id,
                    'child_unit' => $sub_unit->id,
                    'category_id' => $category->id,
                    'product_name' => $row['fabric'],
                    'barcode' => $row['barcode'],
                    'status' => 1,
                    'cost_riel' => $row['cost_riel'],
                    'cost_usd' => $row['cost_usd'],
                ];
            }



            ProductModel::updateOrCreate(
                $where,$data
            );
        }
    }
}
