<?php

namespace App\Imports;

use App\Helpers\Helper;
use App\Models\Auth\User;
use App\Models\Catalogs\CfdiUse;
use App\Models\Catalogs\City;
use App\Models\Catalogs\Country;
use App\Models\Catalogs\PaymentMethod;
use App\Models\Catalogs\PaymentTerm;
use App\Models\Catalogs\PaymentWay;
use App\Models\Catalogs\Product;
use App\Models\Catalogs\SatProduct;
use App\Models\Catalogs\State;
use App\Models\Catalogs\Tax;
use App\Models\Catalogs\UnitMeasure;
use App\Models\Sales\Customer;
use App\Models\Sales\Salesperson;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Validator;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithHeadingRow;

class ProductTemplateImportImport implements ToCollection, WithHeadingRow
{

    /**
     * @param Collection $rows
     * @return mixed
     * @throws \Exception
     */
    public function collection(Collection $rows)
    {
        //Limpieza de datos
        $rows = Helper::clearArrayImport($rows);

        //Validacion
        foreach ($rows as $key => $row) {
            $num_row = $key + 2;

            Validator::make($row->toArray(), [
                'nombre' => 'required',
                'descripcion' => 'required',
            ], [
                'nombre.*' => __('catalogs/product.error_name') . sprintf(__('catalogs/product.error_row'), $num_row,$row['nombre']),
                'descripcion.*' => __('catalogs/product.error_description') . sprintf(__('catalogs/product.error_row'), $num_row,$row['descripcion']),
            ])->validate();
        }

        $company = Helper::firstCompany(); //Empresa
        if(!empty(setting('customers_per_taxid'))){
            $company = Helper::defaultCompany(); //Empresa
        }

        //Importar datos
        foreach ($rows as $key => $row) {
            $num_row = $key + 2;

            //Unidades de medida
            $unit_measure = null;
            if (!empty($row['unidad_de_medida'])) {
                $tpm = explode('-',$row['unidad_de_medida']);
                $unit_measure = UnitMeasure::where('code', '=', $tpm[0])->first();
                if (empty($unit_measure)) {
                    throw new \Exception(__('catalogs/product.error_unit_measure_id2') . sprintf(__('catalogs/product.error_row'), $num_row,$tpm[0]));
                }
            }else{
                throw new \Exception(__('catalogs/product.error_unit_measure_id') . sprintf(__('catalogs/product.error_row'), $num_row,$row['unidad_de_medida']));
            }
            //Catalogo sat
            $sat_product = null;
            if (!empty($row['productoservicio_sat'])) {
                $sat_product = SatProduct::where('code', '=', $row['productoservicio_sat'])->first();
                if (empty($sat_product)) {
                    throw new \Exception(__('catalogs/product.error_sat_product_id2') . sprintf(__('catalogs/product.error_row'), $num_row,$row['productoservicio_sat']));
                }
            }else{
                throw new \Exception(__('catalogs/product.error_sat_product_id') . sprintf(__('catalogs/product.error_row'), $num_row,$row['productoservicio_sat']));
            }
            //Valida impuestos
            $tax = null;
            $taxes = [];
            $taxesArr = [];
            if (!empty($row['impuestos'])) {
                $taxesArr = explode(', ', $row['impuestos']);
                for($i = 0; $i < count($taxesArr); $i++){
                    $tax = Tax::where('name', '=', $taxesArr[$i])->first();
                    if(!empty($tax)){
                        array_push($taxes, $tax->id);
                    }else{
                        throw new \Exception(__('sales/customer_invoice.error_line_taxes2') . sprintf(__('sales/customer_invoice.error_row'), $num_row,$row['impuestos']));
                    }
                }
            }

            //Guardar
            $product = Product::where('code',$row['codigo'])->where('company_id', $company->id)->first();
            if(!empty($product) && !empty($row['codigo'])){
                $product->updated_uid = \Auth::user()->id;
                $product->name = $row['nombre'];
                $product->description = $row['descripcion'];
                $product->model = $row['modelo'];
                $product->manufacturer = $row['marca'];
                $product->price = $row['precio'];
                $product->unit_measure_id = $unit_measure->id ?? null;
                $product->sat_product_id = $sat_product->id ?? null;
                $product->tax_object = empty($taxes) ? '01' : '02';
                $product->save();
            }else{
                $product = Product::create([
                    'created_uid' => \Auth::user()->id,
                    'updated_uid' => \Auth::user()->id,
                    'name' => $row['nombre'],
                    'code' => $row['codigo'],
                    'description' => $row['descripcion'],
                    'model' => $row['modelo'],
                    'manufacturer' => $row['marca'],
                    'price' => $row['precio'],
                    'unit_measure_id' => $unit_measure->id ?? null,
                    'sat_product_id' => $sat_product->id ?? null,
                    'status' => 1,
                    'company_id' => $company->id,
                    'tax_object' => empty($taxes) ? '01' : '02'
                ]);
            }
            //Impuestos
            if (!empty($taxes)) {
                $product->taxes()->sync($taxes);
            } else {
                $product->taxes()->sync([]);
            }
        }

        return true;
    }
}
