HEX
Server: Apache/2.4.41 (Ubuntu)
System: Linux ip-172-31-42-149 5.15.0-1084-aws #91~20.04.1-Ubuntu SMP Fri May 2 07:00:04 UTC 2025 aarch64
User: ubuntu (1000)
PHP: 7.4.33
Disabled: pcntl_alarm,pcntl_fork,pcntl_waitpid,pcntl_wait,pcntl_wifexited,pcntl_wifstopped,pcntl_wifsignaled,pcntl_wifcontinued,pcntl_wexitstatus,pcntl_wtermsig,pcntl_wstopsig,pcntl_signal,pcntl_signal_get_handler,pcntl_signal_dispatch,pcntl_get_last_error,pcntl_strerror,pcntl_sigprocmask,pcntl_sigwaitinfo,pcntl_sigtimedwait,pcntl_exec,pcntl_getpriority,pcntl_setpriority,pcntl_async_signals,pcntl_unshare,
Upload Files
File: /var/www/vhost/disk-apps/qas.sports-crowd.com/app/Http/Controllers/Imports/CategoriesImport.php
<?php

namespace App\Http\Controllers\Imports;

use DB;
use App\Product;
use App\Category;
use App\Parameter;
use App\Subcategories;
use App\SubcategoryProduct;
use Illuminate\Support\Collection;
use App\Http\Controllers\ShopifyController;
use Maatwebsite\Excel\Concerns\ToCollection;
use App\Http\Controllers\WoocommerceController;

class CategoriesImport implements ToCollection
{
    public $edit = [
        'creados' => 0,
    ];
    public $historyProduct = [];
    public $historySubCategory = [];
    public $historyRowProductCategory = [];
    public $historyRowProductSubcategory = [];
    public $request;
    public $current_product;

    public function collection(Collection $rows)
    {
        // Si el excel cargo correctamente eliminar todas los registros de subcategory_products si no esta activo productos por sucursal
        if (!isset($this->request->sucursal_id)) {
            SubcategoryProduct::truncate();
            DB::rollBack();
        }

        DB::beginTransaction();
        $cnt = 0;
        foreach ($rows as $row) {
            if ($cnt > 0) {
                $row[0] = strval($row[0]);
                $row[1] = strval($row[1]);
                $row[2] = strval($row[2]);
                ////////////////////////////////////////
                //////////////PRODUCTO///////////////
                ////////////////////////////////////////

                //verificar si el producto existe, validando logica de sucursal_productos
                if ($row[0] && isset($this->request->sucursal_id)) {
                    //valida en el array si ya se consulto ese producto en la bd y se guarda con el index del plu mas el id de la sucursal ya que pueden haber productos con el mismo plu pero diferente sucursal
                    if (array_key_exists($row[0] . '_' . $this->request->sucursal_id, $this->historyProduct)) {
                        $idProduct = trim($this->historyProduct[$row[0] . '_' . $this->request->sucursal_id]);
                    } else {
                        $idProduct = $this->getProductId($row[0], $this->request->sucursal_id);
                        if ($idProduct) {
                            $this->historyProduct[$row[0] . '_' . $this->request->sucursal_id] = $idProduct;
                        } else {
                            DB::rollback();
                            throw new \Exception(trans('messages.screen_products_tag49') . $row[0]);
                            break;
                        }
                    }
                } else if ($row[0]) {
                    //valida en el array si ya se consulto ese producto en la bd
                    if (array_key_exists($row[0], $this->historyProduct)) {
                        $idProduct = trim($this->historyProduct[$row[0]]);
                    } else {
                        $idProduct = $this->getProductId($row[0]);
                        if ($idProduct) {
                            $this->historyProduct[$row[0]] = $idProduct;
                        } else {
                            DB::rollback();
                            throw new \Exception(trans('messages.screen_products_tag49') . $row[0]);
                            break;
                        }
                    }
                } else {
                    DB::rollback();
                    throw new \Exception(trans('messages.screen_products_tag50') . $row[1]);
                    break;
                }

                // integraciones

                $parameters = Parameter::select('sync_shopify', 'sucursal_products')->find(1);
                if ($parameters && $parameters->sync_shopify) {
                    $sho = new ShopifyController();
                    $data_sho = [
                        "product_type" => trim(ucfirst($row[1])),
                    ];
                    $sho->updateProduct($this->current_product->reference_shopify_id, $data_sho, 'COP');
                }

                ////////////////////////////////////////
                //////////////CATEGORIAS///////////////
                ////////////////////////////////////////

                //verificar si la categoria existe y retorna el id de la subcategoria correspondiente, validando logica de sucursal_productos
                if ($row[1] != '' && isset($this->request->sucursal_id)) {
                    //valida en el array si ya se consulto la categoria en la bd y se guarda con el index: categoria mas el id de la sucursal ya que pueden haber categorias con el mismo nombre pero diferente sucursal
                    if (array_key_exists($row[1] . '_' . $this->request->sucursal_id, $this->historySubCategory)) {
                        $idSubCategory_rowCategory = trim($this->historySubCategory[$row[1] . '_' . $this->request->sucursal_id]);
                    } else {
                        $idSubCategory_rowCategory = $this->getSubCategoryId_rowCategory($row[1], $this->request->sucursal_id);
                        $this->historySubCategory[$row[1] . '_' . $this->request->sucursal_id] = $idSubCategory_rowCategory;
                    }
                } else if ($row[1] != '') {
                    //valida en el array si ya se consulto la categoria en la bd
                    if (array_key_exists($row[1], $this->historySubCategory)) {
                        $idSubCategory_rowCategory = trim($this->historySubCategory[$row[1]]);
                    } else {
                        $idSubCategory_rowCategory = $this->getSubCategoryId_rowCategory($row[1]);
                        $this->historySubCategory[$row[1]] = $idSubCategory_rowCategory;
                    }
                } else {
                    DB::rollback();
                    throw new \Exception(trans('messages.screen_products_tag51') . $row[0]);
                    break;
                }


                ////////////////////////////////////////
                //////////////SUBCATEGORIAS///////////////
                ////////////////////////////////////////

                //verificar si la subCategoria existe y retorna el id, validando logica sucursasl productos
                if ($row[2] != '' && isset($this->request->sucursal_id)) {
                    //valida en el array si ya se consultó la subcategoria en la bd y se guarda con el index: categoria + subcategoria + id de la sucursal ya que pueden haber subcategorias con el mismo nombre pero diferente categoria y sucursal
                    if (array_key_exists($row[1] . $row[2] . '_' . $this->request->sucursal_id, $this->historySubCategory)) {
                        $idSubCategory_rowSubcategory = trim($this->historySubCategory[$row[1] . $row[2] . '_' . $this->request->sucursal_id]);
                    } else {
                        $idSubCategory_rowSubcategory = $this->getSubCategoryId_rowSubcategory($row[1], $row[2], $this->request->sucursal_id);
                        $this->historySubCategory[$row[1] . $row[2] . '_' . $this->request->sucursal_id] = $idSubCategory_rowSubcategory;
                    }
                } else if ($row[2] != '') {
                    //valida en el array si ya se consultó la subcategoria en la bd
                    if (array_key_exists($row[1] . $row[2], $this->historySubCategory)) {
                        $idSubCategory_rowSubcategory = trim($this->historySubCategory[$row[1] . $row[2]]);
                    } else {
                        $idSubCategory_rowSubcategory = $this->getSubCategoryId_rowSubcategory($row[1], $row[2]);
                        $this->historySubCategory[$row[1] . $row[2]] = $idSubCategory_rowSubcategory;
                    }
                }

                // antes de crear la relacion se valida si previamente fue consultado el id de la subcategoria
                //y se valida que la relacion producto con subcategoria ya se haya registrado.
                if (isset($idSubCategory_rowCategory) && !array_key_exists($idSubCategory_rowCategory . $idProduct, $this->historyRowProductCategory)) {
                    if ($this->request->sucursal_id) {
                        $existsSubcategoryProduct = SubcategoryProduct::where([['subcategory_id', $idSubCategory_rowCategory], ['product_id', $idProduct]])->first();
                        if (isset($existsSubcategoryProduct->id)) {
                            $SubcategoryProduct = SubcategoryProduct::find($existsSubcategoryProduct->id);
                            $SubcategoryProduct->subcategory_id = $idSubCategory_rowCategory;
                            $SubcategoryProduct->product_id = $idProduct;
                            $SubcategoryProduct->update();
                            $this->historyRowProductCategory[$idSubCategory_rowCategory . $idProduct] = true;
                        } else {
                            SubcategoryProduct::create([
                                'subcategory_id' => $idSubCategory_rowCategory,
                                'product_id' => $idProduct,
                            ]);
                            $this->historyRowProductCategory[$idSubCategory_rowCategory . $idProduct] = true;
                        }
                    } else {
                        SubcategoryProduct::create([
                            'subcategory_id' => $idSubCategory_rowCategory,
                            'product_id' => $idProduct,
                        ]);
                        $this->historyRowProductCategory[$idSubCategory_rowCategory . $idProduct] = true;
                    }

                    $this->updateSubcategoryToProductInWoocommerce($idSubCategory_rowCategory, $idProduct);
                }

                // antes de crear la relacion se valida si previamente fue consultado el id de la subcategoria
                //y se valida que la relacion producto con subcategoria ya se haya registrado.
                if (isset($idSubCategory_rowSubcategory) && !array_key_exists($idSubCategory_rowSubcategory . $idProduct, $this->historyRowProductSubcategory)) {
                    if ($this->request->sucursal_id) {
                        $existsSubcategoryProduct = SubcategoryProduct::where([['subcategory_id', $idSubCategory_rowSubcategory], ['product_id', $idProduct]])->first();
                        if (isset($existsSubcategoryProduct->id)) {
                            $SubcategoryProduct = SubcategoryProduct::find($existsSubcategoryProduct->id);
                            $SubcategoryProduct->subcategory_id = $idSubCategory_rowSubcategory;
                            $SubcategoryProduct->product_id = $idProduct;
                            $SubcategoryProduct->update();
                            $this->historyRowProductSubcategory[$idSubCategory_rowSubcategory . $idProduct] = true;
                        } else {
                            SubcategoryProduct::create([
                                'subcategory_id' => $idSubCategory_rowSubcategory,
                                'product_id' => $idProduct,
                            ]);
                            $this->historyRowProductSubcategory[$idSubCategory_rowSubcategory . $idProduct] = true;
                        }
                    } else {
                        SubcategoryProduct::create([
                            'subcategory_id' => $idSubCategory_rowSubcategory,
                            'product_id' => $idProduct,
                        ]);
                        $this->historyRowProductSubcategory[$idSubCategory_rowSubcategory . $idProduct] = true;
                    }

                    $this->updateSubcategoryToProductInWoocommerce($idSubCategory_rowCategory, $idProduct);

                    // $this->updateSubcategoryToProductInWoocommerce($idSubCategory_rowCategory, $idProduct);
                }
            }
            $cnt++;
            $this->edit['creados'] = $cnt;
        }
        DB::commit();
    }

    public function getProductId($plu, $sucursal_id = false)
    {
        if ($sucursal_id) {
            $this->current_product = Product::select('id', 'reference_shopify_id')->where([['plu', '=', trim($plu)], ['sucursal_id', $sucursal_id]])->first();
        } else {
            $this->current_product = Product::select('id', 'reference_shopify_id')->where('plu', '=', trim($plu))->first();
        }
        if ($this->current_product) {
            return $this->current_product->id;
        } else {
            return false;
        }
    }

    public function getSubCategoryId_rowCategory($name, $sucursal_id = false)
    {
        if ($sucursal_id) {
            $category = Category::select('id')->where([['name', '=', trim(ucfirst($name))], ['sucursal_id', $sucursal_id]])->first();
        } else {
            $category = Category::select('id')->where('name', '=', trim(ucfirst($name)))->first();
            $sucursal_id = null;
        }


        // valida si existe la categoria si no la crea
        if (isset($category->id)) {
            $subCategory = Subcategories::select('id')->where('category_id', '=', $category->id)->first();
            return $subCategory->id;
        } elseif ($name != '') {
            $woo = new WoocommerceController();
            $data = [
                'name' => trim(ucfirst($name)),
            ];
            $reference_category_id = $woo->createCategory($data);

            $category = Category::create([
                'name' => trim(ucfirst($name)),
                'active' => 1,
                'order' => 100,
                'reference_woocommerce_category_id' => $reference_category_id,
                'sucursal_id' => $sucursal_id,
            ]);
            if ($category) {
                $subCategory = Subcategories::create([
                    'name' => trim(ucfirst($name)),
                    'active' => 1,
                    'order' => 1,
                    'reference_woocommerce_category_id' => $reference_category_id,
                    'category_id' => $category->id,
                ]);
            }

            //Asigna el ID de la categoria que viene en woocommerce y la actualiza en el panel web
            if ($category) {
                $categoryWoo = $woo->listAllCategory($reference_category_id);
                if ($categoryWoo) {
                    $categoryUpdate = Category::find($category->id);
                    $categoryUpdate->reference_woocommerce_category_id = $categoryWoo->id;
                    $categoryUpdate->update(); //Actualiza categoria

                    $SubcategoriesUpdate = Subcategories::find($subCategory->id);
                    $SubcategoriesUpdate->reference_woocommerce_category_id = $categoryWoo->id;
                    $SubcategoriesUpdate->update(); //Actualiza subcategoria
                }
            }

            return $subCategory->id;
        }
    }

    public function getSubCategoryId_rowSubcategory($cat, $subCat, $sucursal_id = false)
    {
        if ($sucursal_id) {
            $category = Category::select('id', 'reference_woocommerce_category_id')->where([['name', '=', trim(ucfirst($cat))], ['sucursal_id', $sucursal_id]])->first();
        } else {
            $category = Category::select('id', 'reference_woocommerce_category_id')->where('name', '=', trim(ucfirst($cat)))->first();
            $sucursal_id = null;
        }
        if ($subCategory = Subcategories::select('id')
            ->where([['name', '=', trim(ucfirst($subCat))], ['category_id', '=', $category->id]])
            ->first()
        ) {
            return $subCategory->id;
        } elseif ($cat != '' && $subCat != '') {
            if ($category) {
                $subCategory = Subcategories::create([
                    'name' => trim(ucfirst($subCat)),
                    'active' => 1,
                    'order' => 2,
                    'category_id' => $category->id,
                ]);
            } else {
                $woo = new WoocommerceController();
                $data = [
                    'name' => trim(ucfirst($cat)),
                ];
                $reference_category_id = $woo->createCategory($data);

                $category = Category::create([
                    'name' => trim(ucfirst($cat)),
                    'active' => 1,
                    'order' => 100,
                    'reference_woocommerce_category_id' => $reference_category_id,
                    'sucursal_id' => $sucursal_id,
                ]);
                if ($category) {
                    $subCategory = Subcategories::create([
                        'name' => trim(ucfirst($subCat)),
                        'active' => 1,
                        'order' => 2,
                        'category_id' => $category->id,
                    ]);
                }
            }
            return $subCategory->id;
        }
    }

    public function updateSubcategoryToProductInWoocommerce($category_id, $product_id)
    {

        $categoryWoo = Category::select('id', 'reference_woocommerce_category_id')->where([['id', '=', $category_id]])->first();
        $productWoo = Product::select('id', 'reference_woocommerce_product_id')->where([['id', '=', $product_id]])->first();

        if ($categoryWoo && $productWoo) {
            $categoryWooId = intval($categoryWoo->reference_woocommerce_category_id);
            $productWooId = intval($productWoo->reference_woocommerce_product_id);

            $woo = new WoocommerceController();
            $data = [
                'categories' => [
                    [
                        'id' => $categoryWooId
                    ]
                ],
            ];

            $woo->updateProduct($productWooId, $data);
        }
    }
}