<?php

namespace App\Imports;

use App\Models\BusinessArea;
use App\Models\Category;
use App\Models\CoinType;
use App\Models\ProductClassification;
use App\Models\ProductsImport;
use App\Models\SpecificSubcategory;
use App\Models\Subcategory;
use App\Models\Supplier;
use App\Models\TypeProduct;
use App\Models\UnitMeasure;
use App\Models\Store;
use Carbon\Carbon;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Tymon\JWTAuth\Facades\JWTAuth;

class ProductsDataImportNotInventory implements ToCollection, WithHeadingRow
{
    public function collection(Collection $products)
    {
        $now = Carbon::now();
        $productSave = [];

        foreach ($products as $product) {
            $category = Category::firstOrNew(['name' => $product['categoria'], 'idcompany' => request('idcompany')]);
            $category->save();
            // $category = Category::where('name', $product['categoria'])->active()->first();
            $supplier = Supplier::where('rut', $product['proveedor'])->active()->first();
            $unitMeasure = UnitMeasure::where('name', $product['unidad_de_medida'])->active()->first();

            //validar si el codigo de producto existe
            $existingProductKey = null;
            foreach ($productSave as $key => $savedProduct) {
                if ($savedProduct['code'] == $product['codigo']) {
                    $existingProductKey = $key;
                    break;
                }
            }

            if (!isset($existingProductKey)) {
                $productSave[] = [
                    'code' => $product['codigo'],
                    'name' => $product['nombre'],
                    'description' => $product['descripcion'] ?? '',
                    'cost' => $product['costo'] ?? 0,
                    'price' => $product['precio'] ?? 0,
                    'idcategory' => isset($category) ? $category->id : null,
                    'idsupplier' => isset($supplier) ? $supplier->id : null,
                    'idunitmeasure' => isset($unitMeasure) ? $unitMeasure->id : 1,
                    'idcointype' => 1,
                    'idtype' => 2,
                    'idwarehouses' => null,
                    'idcompany' => request('idcompany'),
                    'created_by' => JWTAuth::user()->id,
                    'created_at' => $now,
                    'updated_at' => $now
                ];
            };
        }
        ProductsImport::insert($productSave);
    }
}
