<?php

namespace App\Imports;

use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use App\Models\Product;
use App\Models\PriceList;
use App\Models\DetailPriceListProduct;
use App\Models\DetailPriceListCustomer;
use App\Models\Supplier;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use Carbon\Carbon;

class PriceListDataImport implements ToCollection
{
    protected $idcompany;

    public function collection(Collection $rows)
    {
        DB::beginTransaction();
        try {
            // Extraer los datos generales
            $generalData = [
                'code' => $rows[1][2] ?? null, // CÓDIGO LISTA DE PRECIO
                'name' => $rows[2][2] ?? null, // NOMBRE
                'description' => $rows[3][2] ?? null, // DESCRIPCIÓN
                'validity_date' => $rows[4][2] ?? null, // VIGENCIA
            ];

            // Validar que los datos generales estén completos
            if (!$generalData['code'] || !$generalData['name']) {
                throw new \Exception('El código o el nombre de la lista de precios no están definidos.');
            }

            // Validar duplicados
            if (PriceList::where('code', $generalData['code'])->exists()) {
                throw new \Exception('El código ya está registrado.');
            }
            if (PriceList::where('name', $generalData['name'])->exists()) {
                throw new \Exception('El nombre ya está registrado.');
            }

            $currentDate = Carbon::now()->format('Y-m-d');
            $iduser = Auth::user()->id;

            $quantity_products = 0;

            foreach ($rows as $index => $row) {
                if ($index >= 8 && isset($row[3], $row[4]) && !empty($row[3])) {
                    $quantity_products++;
                }
            }

            // Crear la lista de precios
            $priceList = PriceList::create([
                'code' => $generalData['code'],
                'name' => $generalData['name'],
                'description' => $generalData['description'],
                'creation_date' => $currentDate,
                'quantity_products' => $quantity_products,
                'validity_date' => $generalData['validity_date'],
                'idcompany' => request('idcompany'),
                'discounttype' => 3,
                'type' => 5, 
                'created_by' => $iduser,
            ]);

            // Procesar clientes (columna "RUT CLIENTES")
            
            $dataToInsert = [];

            foreach ($rows as $index => $row) {
                if ($index >= 8 && isset($row[1]) && !empty($row[1])) { // A partir de la fila 9
                    $supplier = Supplier::where('rut', $row[1])->where('idcompany', request('idcompany'))->first();
                    if ($supplier) {
                        $dataToInsert[] = [
                            'idpricelist' => $priceList->id,
                            'idcustomer' => $supplier->id,
                            'idcompany' => request('idcompany'),
                        ];
                    }
                }
            }

            if (!empty($dataToInsert)) {
                DetailPriceListCustomer::insert($dataToInsert);
            }

            // Procesar productos (columnas CÓDIGO PRODUCTO, NOMBRE, PRECIO)
            $productDetails = [];
            foreach ($rows as $index => $row) {
                if ($index >= 8 && isset($row[3], $row[4]) && !empty($row[3])) {   
                    $product = Product::where('code_erp', (int)$row[3])->where('idcompany', request('idcompany'))->first();
                    if($product && $product->price != $row[4]) {
                        $productDetails[] = [
                            'idpricelist' => $priceList->id,
                            'idproduct' => $product->id,
                            'price' => $row[4],
                            'idcompany' => request('idcompany'),
                            'created_at' => now(),
                            'updated_at' => now(),
                        ];
                    }
                }
            }

            if (!empty($productDetails)) {
                DetailPriceListProduct::insert($productDetails);
            }

            DB::commit();
        } catch (\Throwable $e) {
            DB::rollBack();
            throw $e; 
        }
    }

}
