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/agile-selling-wpb/app/Http/Controllers/ProductController.php
<?php

namespace App\Http\Controllers;

use App\BoSalesTaxCode;
use App\Brand;
use App\Category;
use App\Product;
use App\SizingUnit;
use App\Subcategories;
use App\SubcategoryProduct;
use App\ServiceCity;
use App\Parameter;
use App\Sucursal;
use App\ProductImage;
use App\ProductAttribute;
use App\UserInformation;
use Datatables;
use DB;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use Intervention\Image\ImageManagerStatic as Image;
use Excel;
use File;
use Box\Spout\Reader\ReaderFactory;
use Box\Spout\Common\Type;
use App\Http\Controllers\ShopifyController;
use App\Http\Controllers\WoocommerceController;
use App\Http\Controllers\Exports\ReportProducts;
use App\Http\Controllers\Imports\ProductImports;
use App\Http\Controllers\Imports\CategoryImports;
use App\Http\Controllers\Exports\ReportCategories;

class ProductController extends Controller
{
    public function __construct(Request $request)
    {
        $this->middleware('auth');
        // $this->middleware(function ($request, $next) {
        //     $this->user = Auth::user();
        //     if (Auth::user()->rol->id == 1 || Auth::user()->rol->id == 6) {
        //         $this->changeDbDefault($request);
        //     }
        //     return $next($request);
        // });
    }

    public function index()
    {
        // $rol = Auth::user()->rol->id;
        // if ($rol == 1 ||  $rol == 6) {
            $db_name = Parameter::where('id', 1)->select('id', 'db_name', 'sucursal_products', 'external_template')->first();
            $services = new ServiceCity();
            $services->setConnection('main-db');
            $servicesN = $services->where('active', 1)->get();
            $parameter =  Parameter::find(1);

            if ($db_name->sucursal_products) {
                $sucursals = Sucursal::where('active', 1)->get();
            } else {
                $sucursals = null;
            }
            return view('products.products')
                ->with('services', $servicesN)
                ->with('db_name', $db_name->db_name)
                ->with('sucursal_products', $db_name->sucursal_products)
                ->with('external_template', $db_name->external_template)
                ->with('sucursals', $sucursals)
                ->with('parameter', $parameter);
        // } else {
        //     return redirect()->back();
        // }
    }

    public function indexAdd()
    {
        $brands = Brand::where('active', 1)->get();
        $sub_categories = Subcategories::where('active', 1)->get();
        $parameter = Parameter::where('id', 1)->select('sucursal_products','sync_shopify','sync_woocommerce', 'b1_activate')->first();

        if ($parameter->sucursal_products) {
            $sucursals = Sucursal::where('active', 1)->get();
        } else {
            $sucursals = null;
        }
        return view('products.addProduct')
            ->with('brands', $brands)
            ->with('sub_categories', $sub_categories)
            ->with('sucursals', $sucursals)
            ->with('parameter', $parameter);
    }

    public function create(Request $request, $sync = true)
    {
        $reference_id = null;
        $reference_shopify_id = null;
        if($sync){
            $woo = new WoocommerceController();
            $data = [
                'name'          => $request["name"],
                'price'         => $request["price"],
                'regular_price' => $request["price"],
            ];
            $reference_id = $woo->createProduct($data);

            $subcategory = "";
            if(isset($request["sub_categories"]) && count($request["sub_categories"])){
                $subcategory = Subcategories::where('id', $request["sub_categories"][0])->first();
                if($subcategory){
                    $subcategory = $subcategory->name;
                }
            }
            $sho = new ShopifyController();
            $brand = Brand::where('id', $request["brand_id"])->first();
            $data_sho = [
                "title" => $request["name"],
                "vendor" => $brand->name,
                "product_type" => $subcategory,
                "status"    => "active",
            ];
            $reference_shopify_id = $sho->createProduct($data_sho);
        }else{
            $reference_id = $request["reference_woocommerce_product_id"];
            $reference_shopify_id = $request["reference_shopify_id"];
        }

        $product = new Product();
        $product->active = 1;
        $product->name = $request["name"];
        $product->plu = $request["plu"];
        $product->bar_code = $request["bar_code"];
        $product->bin_location = $request["bin_location"];
        $product->price = $request["price"];
        $product->available_units = $request["available_units"];
        $product->max_units_per_order = $request["max_units_per_order"];
        $product->percentage_discount = $request["percentage_discount"];
        $product->start_discount = $request["start_discount"];
        $product->limit_discount = $request["limit_discount"];
        $product->limit_hour_discount = $request["limit_hour_discount"];
        $product->flash_price = $request["flash_price"];
        $product->start_flash_discount = $request["start_flash_discount"];
        $product->limit_flash_discount = $request["limit_flash_discount"];
        $product->limit_hour_flash_discount = $request["limit_hour_flash_discount"];
        $product->brand_id = $request["brand_id"];
        $product->order = $request["order"];
        $product->validate_age = $request["chkAgeProduct"];
        $product->sucursal_id = $request["sucursal_id"];
        $product->reference_woocommerce_product_id = $reference_id;
        $product->reference_shopify_id = $reference_shopify_id;
        $product->popup_active = $request["popup_active"];
        $product->popup_text = $request["popup_text"];
        $product->highlight = $request["highlight"];
        $product->save();

        if ($product) {
            ProductImage::create([
                "name" => $request["plu"] . ".jpg",
                "product_id" => $product->id,
            ]);

            foreach ($request["sub_categories"] as $id_subcategory) {
                if($id_subcategory){
                    $subcategoryProduct = new SubcategoryProduct();
                    $subcategoryProduct->subcategory_id = $id_subcategory;
                    $subcategoryProduct->product_id = $product->id;
                    $subcategoryProduct->save();
                }
            }
            return array('r' => true, 'd' => array('id' => $product->id, 'plu' => $request["plu"]), 'm' => trans('messages.screen_products_tag34'));
        } else {
            return array('r' => false, 'd' => null, 'm' => trans('messages.screen_products_tag35'));
        }
    }

    public function indexEdit($id)
    {

        $product = Product::with('productImages')->with('bo_sales_tax_code')->find($id);
        $brands = Brand::where('active', 1)->get();
        $sub_categories = Subcategories::where('active', 1)->get();
        $subcategoryProduct = SubcategoryProduct::select('subcategory_id')->where('product_id', $id)->get();
        $parameter = Parameter::where('id', 1)->select('sucursal_products', 'b1_activate')->first();
        $bo_sales_tax_codes = BoSalesTaxCode::where("active", true)->get();
        if ($parameter->sucursal_products) {
            $sucursals = Sucursal::where('active', 1)->get();
        } else {
            $sucursals = null;
        }

        // se crea array con solo el id de la subcategoria para poder
        // hacer in_array en el select del view y dejar selected las subcategorias del producto
        $arraySubcategorySelected = array();
        foreach ($subcategoryProduct as $subcatProduct) {
            $arraySubcategorySelected[] = $subcatProduct->subcategory_id;
        }

        return view('products.editProduct')
            ->with('product', $product)
            ->with('brands', $brands)
            ->with('sub_categories', $sub_categories)
            ->with('arraySubcategorySelected', $arraySubcategorySelected)
            ->with('sucursals', $sucursals)
            ->with('parameter', $parameter)
            ->with('bo_sales_tax_codes', $bo_sales_tax_codes);
    }

    public function update(Request $request)
    {
        $product = Product::find($request["id"]);

        $woo = new WoocommerceController();
        $data = [
            'name'          => $request["name"],
            'price'         => $request["price"],
            'regular_price' => $request["price"],
        ];
        $woo->updateProduct($product->reference_woocommerce_product_id,$data);

        $subcategory = "";
        if(isset($request["sub_categories"]) && count($request["sub_categories"])){
            $subcategory = Subcategories::where('id', $request["sub_categories"][0])->first();
            if($subcategory){
                $subcategory = $subcategory->name;
            }
        }
        $sho = new ShopifyController();
        $brand = Brand::where('id', $request["brand_id"])->first();
        $data_sho = [
            "title" => $request["name"],
            "vendor" => $brand->name,
            "product_type" => $subcategory,
            "status"    => "active",
        ];
        $sho->updateProduct($product->reference_shopify_id,$data_sho);

        $product->active = 1;
        $product->name = $request["name"];
        $product->plu = $request["plu"];
        $product->bar_code = $request["bar_code"];
        $product->bin_location = $request["bin_location"];
        $product->price = $request["price"];
        $product->available_units = $request["available_units"];
        $product->max_units_per_order = $request["max_units_per_order"];
        $product->percentage_discount = $request["percentage_discount"];
        $product->start_discount = $request["start_discount"];
        $product->limit_discount = $request["limit_discount"];
        $product->limit_hour_discount = $request["limit_hour_discount"];
        $product->flash_price = $request["flash_price"];
        $product->start_flash_discount = $request["start_flash_discount"];
        $product->limit_flash_discount = $request["limit_flash_discount"];
        $product->limit_hour_flash_discount = $request["limit_hour_flash_discount"];
        $product->brand_id = $request["brand_id"];
        $product->order = $request["order"];
        $product->validate_age = $request["chkAgeProduct"];
        $product->sucursal_id = $request["sucursal_id"];
        $product->popup_active = $request["popup_active"];
        $product->popup_text = $request["popup_text"];
        $product->highlight = $request["highlight"];
        $product->update();

        if ($product) {
            $subcategoryProductDelete = SubcategoryProduct::where('product_id', $request["id"])->delete();
            foreach ($request["sub_categories"] as $id_subcategory) {
                $subcategoryProduct = new SubcategoryProduct();
                $subcategoryProduct->subcategory_id = $id_subcategory;
                $subcategoryProduct->product_id = $product->id;
                $subcategoryProduct->save();
            }
            return array('r' => true, 'd' => array('id' => $product->id, 'plu' => $request["plu"]), 'm' => trans('messages.screen_products_tag39'));
        } else {
            return array('r' => false, 'd' => null, 'm' => trans('messages.screen_products_tag40'));
        }
    }

    public function saveImage(Request $request)
    {
        $id = $request->id;
        $plu = $request->plu;
        $extension = $request->file('image')->getClientOriginalExtension();
        // $imageresize = Image::make($request->file('image'))->fit(1300, 660);
        // $imageresize = Image::make($request->file('image'))->resize(1300, 660);
        $filenametostore = $plu . '.' . $extension;
        Storage::disk('s3')->put(env('S3_PRODUCTS_PATH') . $filenametostore, fopen($request->file('image'), 'r+'), 'public');

        $status = Product::where('id', $id)->update(['image' => $filenametostore]);
        if ($status) {
            return array('r' => true, 'd' => null, 'm' => trans('messages.screen_products_tag34'));
        } else {
            return array('r' => false, 'd' => null, 'm' => trans('messages.screen_products_tag35'));
        }
    }

    public function updateImage(Request $request)
    {
        $id = $request->id;
        $plu = $request->plu;
        $extension = $request->file('image')->getClientOriginalExtension();

        $filenametostore = $plu . '.' . $extension;
        Storage::disk('s3')->put(env('S3_PRODUCTS_PATH') . $filenametostore, fopen($request->file('image'), 'r+'), 'public');

        $status = Product::where('id', $id)->update(['image' => $filenametostore]);
        if ($status) {
            return array('r' => true, 'd' => null, 'm' => trans('messages.screen_products_tag39'));
        } else {
            return array('r' => false, 'd' => null, 'm' => trans('messages.screen_products_tag40'));
        }
    }

    public function activateProduct(Request $request)
    {
        $id = $request['id'];
        $state = $request['state'];

        $product = Product::find($id);
        $product->active = $state;
        $product->update();

        $woo = new WoocommerceController();
        $data = [
            'catalog_visibility'    => $state ? 'visible' : 'hidden',
        ];
        $woo->updateProduct($product->reference_woocommerce_product_id,$data);

        $sho = new ShopifyController();
        $data_sho = [
            "status"    => $state ? "active" : 'archived',
        ];
        $sho->updateProduct($product->reference_shopify_id,$data_sho);

        if ($product) {
            return array('r' => true, 'd' => null, 'm' => trans('messages.screen_products_tag27'));
        } else {
            return array('r' => false, 'd' => null, 'm' => trans('messages.screen_products_tag28'));
        }
    }

    public function deleteProduct(Request $request)
    {
        $product = Product::find($request['id']);
        $product->active = false;
        $product->delete();

        if ($product) {
            $woo = new WoocommerceController();
            $woo->deleteProduct($product->reference_woocommerce_product_id);

            $sho = new ShopifyController();
            $sho->deleteProduct($product->reference_shopify_id);
            return array('r' => true, 'd' => null, 'm' => trans('messages.screen_products_tag29'));
        } else {
            return array('r' => false, 'd' => null, 'm' => trans('messages.screen_products_tag30'));
        }
    }

    public function tableFilter($db_database, $sucursal_id = false)
    {
        $products = new Product();
        $products->setConnection($db_database);

        if ($sucursal_id) {
            $obj = $products->select('id', 'name', 'plu', 'bar_code', 'price', 'active')
            ->with('productImages')
            ->where('sucursal_id', $sucursal_id)->whereNull('deleted_at');
        } else {
            $obj = $products->select('id', 'name', 'plu', 'bar_code', 'price', 'active')
            ->with('productImages')
            ->whereNull('deleted_at');
        }

        //  $obj = DB::table('products')
        //         ->setConnection($db_database)
        //         ->select('products.id', 'products.image', 'products.name', 'products.plu', 'products.bar_code', 'products.price', 'products.active')->whereNull('products.deleted_at');

        return Datatables::of($obj)
            ->addColumn('image', function ($obj) {
                if (!count($obj->productImages)) {
                    return '<div class="media-left">
        <img src="' . env('AWS_URL') . '/public/no_image.png" class="media-object" alt="no_image">
        </div>';
                } else {
                    return '<div class="media-left">
        <img src="' . env('AWS_URL') . '/products/' . $obj->productImages[0]->name . '" class="media-object" alt="' . $obj->productImages[0]->name . '">
        </div>';
                }
            })
            ->addColumn('actions', function ($obj) {
                return '
      <i class="fa fa-tags iconMini " onClick="clickAttributes(' . $obj->id . ')" data-id="' . $obj->id . '" data-toggle="tooltip" data-placement="bottom" title="Atributos" style="cursor:pointer;"></i>
      <i class="fa fa-pencil iconMini " onClick="clickEditProduct(' . $obj->id . ')" data-id="' . $obj->id . '" data-toggle="tooltip" data-placement="bottom" title="Editar" style="cursor:pointer;"></i>
      <i class="fa fa-trash iconMini " onClick="clickDeleteProduct(' . $obj->id . ')" data-id="' . $obj->id . '" data-toggle="tooltip" data-placement="bottom"  style="cursor:pointer;" title="Eliminar"></i>
      <i class="fa fa-search iconMini " id="scraper' . $obj->id . '" data-text="' . $obj->name . '" onClick="clickScraper(' . $obj->id . ')" data-id="' . $obj->id . '" data-toggle="tooltip" data-placement="bottom"   title="Comparar"></i>

      ';
            })
            ->editColumn('active', function ($obj) {
                if ($obj->active == 0) {
                    return '<div class="switch"><label><div class="checkbox checbox-switch switch-success"> <label> No <input type="checkbox" onChange="chkProduct(' . $obj->id . ')" data-id="' . $obj->id . '" id="Checkactive' . $obj->id . '" name="Checkactivo" /> <span></span>Si </label></div> </label> </div>';
                } else {
                    return '<div class="switch"><label> <div class="checkbox checbox-switch switch-success"> <label>   No <input type="checkbox" onChange="chkProduct(' . $obj->id . ')" data-id="' . $obj->id . '" id="Checkactive' . $obj->id . '" name="Checkactivo" checked="" />
        <span></span> Si </label> </div>  </label> </div>';
                }
            })
            ->rawColumns(['active', 'actions', 'image'])
            ->make(true);
    }

    public function getBrandId($name)
    {
        if ($brand = Brand::select('id')->where('name', '=', trim(ucfirst($name)))->first()) {
            return $brand->id;
        } elseif ($name != '') {
            $brand = Brand::create([
                'name' => trim(ucfirst($name)),
                'active' => 1,
            ]);
            return $brand->id;
        }
    }

    public function getSucursalId($name)
    {
        if ($sucursal = Sucursal::select('id')->where('name', '=', trim($name))->first()) {
            return $sucursal->id;
        } elseif ($name != '') {
            $sucursal = Sucursal::create([
                'code' => trim($name),
                'name' => trim($name),
                'mail' => trim($name),
                'phone' => trim($name),
                'active' => 1,
                'address_id' => 1,
                'city_id' => 1,
                'coverage_id' => 1,
            ]);
            return $sucursal->id;
        }
    }

    public function getSizingUnitsId($name)
    {
        if ($sizing = SizingUnit::select('id')->where('name', '=', trim(ucfirst($name)))->first()) {
            return $sizing->id;
        } elseif ($name != '') {
            $sizing = SizingUnit::create([
                'name' => trim(ucfirst($name)),
            ]);
            return $sizing->id;
        }
    }

    public function getProductId($plu, $sucursal_id = false)
    {
        if ($sucursal_id) {
            $product = Product::select('id')->where([['plu', '=', trim($plu)], ['sucursal_id', $sucursal_id]])->first();
        } else {
            $product = Product::select('id')->where('plu', '=', trim($plu))->first();
        }
        if ($product) {
            return $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();
            if($subCategory){
                $subCategory->active = true;
                $subCategory->update();
            }else{
                $subCategory = Subcategories::create([
                    'name' => trim(ucfirst($name)),
                    'active' => 1,
                    'order' => 1,
                    'category_id' => $category->id,
                ]);
            }
            $category->active = true;
            $category->update();
            return $subCategory->id;
        } elseif ($name != '') {
            $category = Category::create([
                'name' => trim(ucfirst($name)),
                'active' => 1,
                'order' => 100,
                'sucursal_id' => $sucursal_id,
            ]);
            if ($category) {
                $subCategory = Subcategories::create([
                    'name' => trim(ucfirst($name)),
                    'active' => 1,
                    'order' => 1,
                    'category_id' => $category->id,
                ]);
            }
            return $subCategory->id;
        }
    }

    public function getSubCategoryId_rowSubcategory($cat, $subCat,$sucursal_id = false)
    {
        if ($sucursal_id) {
            $category = Category::select('id')->where([['name', '=', trim(ucfirst($cat))], ['sucursal_id', $sucursal_id]])->first();
        } else {
            $category = Category::select('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()
        ) {
            $category->active = true;
            $category->update();
            $subCategory->active = true;
            $subCategory->update();
            return $subCategory->id;
        } elseif ($cat != '' && $subCat != '') {
            if ($category) {
                $subCategory = Subcategories::create([
                    'name' => trim(ucfirst($subCat)),
                    'active' => 1,
                    'order' => 2,
                    'category_id' => $category->id,
                ]);
            } else {
                $category = Category::create([
                    'name' => trim(ucfirst($cat)),
                    'active' => 1,
                    'order' => 100,
                    '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 export()
    {
        return Excel::download(new ReportProducts, trans('messages.screen_products_tag1').'.xlsx');
    }

    public function exportCategories()
    {
        return Excel::download(new ReportCategories, trans('messages.screen_products_tag47').'.xlsx');
    }

    public function import(Request $request)
    {
        try {
            $file = new ProductImports;
            $file->request = $request;
            Excel::import($file,$request->importProducts);
            return array('r' => true, 'd' => null, 'm' => trans('messages.screen_products_tag45') . ' ' .$file->edit['creados'] . ' creados, ' . $file->edit['editados'] . ' editados, ' . $file->edit['inactivados'] . ' inactivados.');
        } catch (\Exception $e) {
            return array('r' => false, 'd' => null, 'm' => trans('messages.screen_products_tag46') . $e->getMessage());
        }
    }

    // public function import(Request $request)
    // {
    //     try {
    //         $this->edit = [
    //             'creados' => 0,
    //             'editados' => 0,
    //             'inactivados' => 0,
    //         ];
    //         $this->historyBrand = [];
    //         $this->historySizingUnits = [];

    //         DB::beginTransaction();
    //         if (!isset($request->sucursal_id)) {
    //             // Inactivar todos los productos, desactiva las fechas establecidas previamente para relampago y descuento, deja en 0 los descuentos de los productos.
    //             DB::table('products')
    //             ->update([
    //                 'active' => false,
    //                 'flash_price' => null,
    //                 'start_flash_discount' => null,
    //                 'limit_flash_discount' => null,
    //                 'limit_hour_flash_discount' => null,
    //                 'percentage_discount' => null,
    //                 'start_discount' => null,
    //                 'limit_discount' => null,
    //                 'limit_hour_discount' => null,
    //             ]);
    //         }
    //         $reader = ReaderFactory::create(Type::XLSX); // for XLSX files
    //         $reader->open($request->importProducts);
    //         $cnt = 0;

    //         foreach ($reader->getSheetIterator() as $sheet) {
    //             foreach ($sheet->getRowIterator() as $row) {
    //                 if ($cnt > 0 && $row[0] != '') {
    //                     //validaciones
    //                     if(!$row[3] || $row[3] == ''){
    //                         return array('r' => false, 'd' => null, 'm' => trans('messages.screen_products_tag58', ['plu' => $row[0]]));
    //                     }
    //                     // Verificar si existe el producto.
    //                     if (isset($request->sucursal_id)) {
    //                         $current_product = Product::where([['plu', $row[0]], ['sucursal_id', $request->sucursal_id]])->first();
    //                     } else {
    //                         $current_product = Product::where('plu', $row[0])->first();
    //                     }

    //                     if (isset($row[19]) && $row[19] == 'x' || isset($row[19]) && $row[19] == 'X') {
    //                         $this->edit['inactivados'] += 1;
    //                     }else if ($current_product) { // Existe, Actualizar
    //                         $current_product->active = 1;
    //                         $current_product->name = trim($row[2]);
    //                         $current_product->bar_code = trim($row[1]);
    //                         $current_product->sizing = trim($row[4]);
    //                         $current_product->available_units = intval($row[6]) == 0 || intval($row[6]) == '' ? null : intval($row[6]);
    //                         $current_product->max_units_per_order = intval($row[7]) == 0 || intval($row[7]) == '' ? null : intval($row[7]);
    //                         $current_product->price = intval($row[8]);

    //                         $current_product->flash_price = intval($row[9]);
    //                         $current_product->start_flash_discount = $row[10] == '0000-00-00' || $row[10] == '' ? null : trim($row[10]);
    //                         $current_product->limit_flash_discount = $row[11] == '0000-00-00' || $row[11] == '' ? null : trim($row[11]);
    //                         $current_product->limit_hour_flash_discount = $row[12] == '00:00:00' || $row[12] == '' ? null : trim($row[12]);

    //                         $current_product->percentage_discount = intval($row[13]);
    //                         $current_product->start_discount = $row[13] == '0000-00-00' || $row[13] == '' ? null : trim($row[13]);
    //                         $current_product->limit_discount = $row[15] == '0000-00-00' || $row[15] == '' ? null : trim($row[15]);
    //                         $current_product->limit_hour_discount = $row[16] == '00:00:00' || $row[16] == '' ? null : trim($row[16]);

    //                         // busca en el array si ya se consulto el id de la marca para no volver a consultar la bd
    //                         if (array_key_exists($row[3], $this->historyBrand)) {
    //                             $current_product->brand_id = trim($this->historyBrand[$row[3]]);
    //                         } else {
    //                             $id = $this->getBrandId($row[3]);
    //                             $this->historyBrand[$row[3]] = $id;
    //                             $current_product->brand_id = $id;
    //                         }

    //                         // busca en el array si ya se consulto el id de la unidad para no volver a consultar la bd
    //                         if (array_key_exists($row[5], $this->historySizingUnits)) {
    //                             $current_product->sizing_units_id = trim($this->historySizingUnits[$row[5]]);
    //                         } else {
    //                             $id = $this->getSizingUnitsId($row[5]);
    //                             $this->historySizingUnits[$row[5]] = $id;
    //                             $current_product->sizing_units_id = $id;
    //                         }

    //                         $current_product->order = intval($row[17]);
    //                         $current_product->validate_age = isset($row[18]) && $row[18] == "x" ? true : false;
    //                         if (isset($request->sucursal_id)) {
    //                             $current_product->sucursal_id = $request->sucursal_id;
    //                         } else {
    //                             $current_product->sucursal_id = null;
    //                         }

    //                         $current_product->update();
    //                         $this->edit['editados'] += 1;
    //                     } else { // Crear

    //                         // busca en el array si ya se consulto el id de la marca para no volver a consultar la bd
    //                         if (array_key_exists($row[3], $this->historyBrand)) {
    //                             $brand_id = trim($this->historyBrand[$row[3]]);
    //                         } else {
    //                             $id = $this->getBrandId($row[3]);
    //                             $this->historyBrand[$row[3]] = $id;
    //                             $brand_id = $id;
    //                         }

    //                         // busca en el array si ya se consulto el id de la unidad para no volver a consultar la bd
    //                         if (array_key_exists($row[5], $this->historySizingUnits)) {
    //                             $sizing_units_id = trim($this->historySizingUnits[$row[5]]);
    //                         } else {
    //                             $id = $this->getSizingUnitsId($row[5]);
    //                             $this->historySizingUnits[$row[5]] = $id;
    //                             $sizing_units_id = $id;
    //                         }

    //                         if (isset($request->sucursal_id)) {
    //                             $sucursal_id = $request->sucursal_id;
    //                         } else {
    //                             $sucursal_id = null;
    //                         }

    //                         if ($row[0] != null || $row[0] != "") {
    //                             $new_product = Product::create([
    //                                 'active' => 1,
    //                                 'name' => trim($row[2]),
    //                                 'plu' => trim($row[0]),
    //                                 'bar_code' => trim($row[1]),
    //                                 'sizing' => trim($row[4]),
    //                                 'available_units' => intval($row[6]) == 0 || intval($row[6]) == '' ? null : intval($row[6]),
    //                                 'max_units_per_order' => intval($row[7]) == 0 || intval($row[7]) == '' ? null : intval($row[7]),
    //                                 'price' => intval($row[8]),

    //                                 'flash_price' => intval($row[9]),
    //                                 'start_flash_discount' => $row[10] == '0000-00-00' || $row[10] == '' ? null : trim($row[10]),
    //                                 'limit_flash_discount' => $row[11] == '0000-00-00' || $row[11] == '' ? null : trim($row[11]),
    //                                 'limit_hour_flash_discount' => $row[12] == '00:00:00' || $row[12] == '' ? null : trim($row[12]),

    //                                 'percentage_discount' => intval($row[13]),
    //                                 'start_discount' => $row[13] == '0000-00-00' || $row[13] == '' ? null : trim($row[13]),
    //                                 'limit_discount' => $row[15] == '0000-00-00' || $row[15] == '' ? null : trim($row[15]),
    //                                 'limit_hour_discount' => $row[16] == '00:00:00' || $row[16] == '' ? null : trim($row[16]),

    //                                 'brand_id' => $brand_id,
    //                                 'sizing_units_id' => $sizing_units_id,

    //                                 'order' => intval($row[17]),
    //                                 'validate_age' => isset($row[18]) && $row[18] == "x" ? true : false,
    //                                 'image' => trim($row[0]) . ".jpg",
    //                                 'sucursal_id' => $sucursal_id,
    //                             ]);
    //                             $new_product->save();
    //                             $this->edit['creados'] += 1;
    //                         }
    //                     }
    //                 }
    //                 $cnt++;
    //             }
    //         }
    //         DB::commit();
    //         $reader->close();
    //         return array('r' => true, 'd' => null, 'm' => trans('messages.screen_products_tag45') . ' ' .$this->edit['creados'] . ' creados, ' . $this->edit['editados'] . ' editados, ' . $this->edit['inactivados'] . ' inactivados.');
    //     } catch (\Exception $e) {
    //         return array('r' => false, 'd' => null, 'm' => trans('messages.screen_products_tag46') . $e);
    //     }
    // }

    //  importa las categorias y subcategorias de los productos
    public function importCategoriesAndSubcategories(Request $request)
    {
        try {
            $file = new CategoryImports;
            $file->request = $request;
            Excel::import($file,$request->importCategories);
            return array('r' => true, 'd' => null, 'm' => trans('messages.screen_products_tag45') . ' ' .$file->edit['creados'] . ' creados ');
        } catch (\Exception $e) {
            return array('r' => false, 'd' => null, 'm' => trans('messages.screen_products_tag46') . $e->getMessage());
        }
    }

    // public function importCategoriesAndSubcategories(Request $request)
    // {
    //     try {
    //         $this->edit = [
    //             'creados' => 0,
    //         ];
    //         $this->historyProduct = [];
    //         $this->historySubCategory = [];
    //         $this->historyRowProductCategory = [];
    //         $this->historyRowProductSubcategory = [];

    //         // Si el excel cargo correctamente eliminar todas los registros de subcategory_products si no esta activo productos por sucursal
    //         if (!isset($request->sucursal_id)) {
    //             SubcategoryProduct::truncate();
    //             DB::rollBack();
    //         }
    //         DB::beginTransaction();
    //         DB::table('categories')->update(['active' => false]);
    //         DB::table('subcategories')->update(['active' => false]);
    //         $reader = ReaderFactory::create(Type::XLSX); // for XLSX files
    //         $reader->open($request->importCategories);
    //         $cnt = 0;
    //         foreach ($reader->getSheetIterator() as $sheet) {
    //             foreach ($sheet->getRowIterator() as $row) {
    //                 if ($cnt > 0) {
    //                     $row[0] = isset($row[0]) ? strval($row[0]) : null;
    //                     $row[1] = isset($row[1]) ? strval($row[1]) : null;
    //                     $row[2] = isset($row[2]) ? strval($row[2]) : null;
    //                     ////////////////////////////////////////
    //                     //////////////PRODUCTO///////////////
    //                     ////////////////////////////////////////

    //                     //verificar si el producto existe, validando logica de sucursal_productos
    //                     if ($row[0] && isset($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] . '_' . $request->sucursal_id, $this->historyProduct)) {
    //                             $idProduct = trim($this->historyProduct[$row[0] . '_' . $request->sucursal_id]);
    //                         } else {
    //                             $idProduct = $this->getProductId($row[0], $request->sucursal_id);
    //                             if ($idProduct) {
    //                                 $this->historyProduct[$row[0] . '_' . $request->sucursal_id] = $idProduct;
    //                             } else {
    //                                 return array('r' => false, 'd' => null, 'm' => trans('messages.screen_products_tag49') . $row[0]);
    //                             }
    //                         }
    //                     } 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 {
    //                                 return array('r' => false, 'd' => null, 'm' => trans('messages.screen_products_tag49') . $row[0] . $idProduct);
    //                             }
    //                         }
    //                     } else {
    //                         return array('r' => false, 'd' => null, 'm' => trans('messages.screen_products_tag50') . $row[1]);
    //                     }

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

    //                     //verificar si la categoria existe y retorna el id de la subcategoria correspondiente, validando logica de sucursal_productos
    //                     if ($row[1] != '' && isset($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] . '_' . $request->sucursal_id, $this->historySubCategory)) {
    //                             $idSubCategory_rowCategory = trim($this->historySubCategory[$row[1] . '_' . $request->sucursal_id]);
    //                         } else {
    //                             $idSubCategory_rowCategory = $this->getSubCategoryId_rowCategory($row[1], $request->sucursal_id);
    //                             $this->historySubCategory[$row[1] . '_' . $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 {
    //                         return array('r' => false, 'd' => null, 'm' => trans('messages.screen_products_tag51') . $row[0]);
    //                     }


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

    //                     //verificar si la subCategoria existe y retorna el id, validando logica sucursasl productos
    //                     if ($row[2] != '' && isset($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] . '_' . $request->sucursal_id, $this->historySubCategory)) {
    //                             $idSubCategory_rowSubcategory = trim($this->historySubCategory[$row[1] . $row[2] . '_' . $request->sucursal_id]);
    //                         } else {
    //                             $idSubCategory_rowSubcategory = $this->getSubCategoryId_rowSubcategory($row[1], $row[2], $request->sucursal_id);
    //                             $this->historySubCategory[$row[1] . $row[2] . '_' . $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 ($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 {
    //                                 $new_subcategory_products = SubcategoryProduct::create([
    //                                     'subcategory_id' => $idSubCategory_rowCategory,
    //                                     'product_id' => $idProduct,
    //                                 ]);
    //                                 $this->historyRowProductCategory[$idSubCategory_rowCategory . $idProduct] = true;
    //                             }
    //                         } else {
    //                             $new_subcategory_products = SubcategoryProduct::create([
    //                                 'subcategory_id' => $idSubCategory_rowCategory,
    //                                 'product_id' => $idProduct,
    //                             ]);
    //                             $this->historyRowProductCategory[$idSubCategory_rowCategory . $idProduct] = true;
    //                         }
    //                     }

    //                     // 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 ($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 {
    //                                 $new_subcategory_products = SubcategoryProduct::create([
    //                                     'subcategory_id' => $idSubCategory_rowSubcategory,
    //                                     'product_id' => $idProduct,
    //                                 ]);
    //                                 $this->historyRowProductSubcategory[$idSubCategory_rowSubcategory . $idProduct] = true;
    //                             }
    //                         } else {
    //                             $new_subcategory_products = SubcategoryProduct::create([
    //                                 'subcategory_id' => $idSubCategory_rowSubcategory,
    //                                 'product_id' => $idProduct,
    //                             ]);
    //                             $this->historyRowProductSubcategory[$idSubCategory_rowSubcategory . $idProduct] = true;
    //                         }
    //                     }
    //                     $idProduct = null;
    //                     $idSubCategory_rowCategory = null;
    //                     $idSubCategory_rowSubcategory = null;
    //                 }
    //             $cnt++;
    //             $this->edit['creados'] = $cnt;
    //             }
    //         }
    //         DB::commit();
    //         $reader->close();
    //         return array('r' => true, 'd' => null, 'm' => trans('messages.screen_products_tag45') . ' ' .$this->edit['creados'] . ' creados ');
    //     } catch (\Exception $e) {
    //         return array('r' => false, 'd' => null, 'm' => trans('messages.screen_products_tag46') . $e->getMessage());
    //     }
    // }

    public function importExternal(Request $request)
    {
        try {
            $this->edit = [
                'creados' => 0,
                'editados' => 0,
            ];

            $this->historySucursal = [];

            DB::table('subcategory_products')->truncate();
            DB::table('subcategory_products')->delete();

            $reader = ReaderFactory::create(Type::XLSX); // for XLSX files
            $reader->open($request->importProductsExternal);
            $cnt = 0;
            foreach ($reader->getSheetIterator() as $sheet) {
                foreach ($sheet->getRowIterator() as $row) {
                    if ($cnt > 6) {
                        // se valida si esta activa la logica sucursal por productos y se busca en el array si ya se consulto el id de la sucursal para no volver a consultar la bd
                        if ($row[2] != "" && $row[3] != "") {
                            if ($request->sucursal_id) {
                                if (array_key_exists($row[2], $this->historySucursal)) {
                                    $sucursal_id = trim($this->historySucursal[$row[2]]);
                                    $current_product = Product::where([['plu', $row[3]], ['sucursal_id', $sucursal_id]])->first();
                                } else {
                                    $id = $this->getSucursalId($row[2]);
                                    $this->historySucursal[$row[2]] = $id;
                                    $sucursal_id = $id;
                                    $current_product = Product::where([['plu', $row[3]], ['sucursal_id', $sucursal_id]])->first();
                                }
                            } else {
                                $sucursal_id = null;
                                $current_product = Product::where('plu', $row[3])->first();
                            }
                        } else {
                            $sucursal_id = null;
                            $current_product = null;
                        }

                        if ($current_product) { // Existe, Actualizar
                            $current_product->active = true;
                            $current_product->name = trim($row[4]);
                            $current_product->plu = trim($row[3]);
                            $current_product->price = intval($row[6]);
                            $current_product->sucursal_id = $sucursal_id;
                            $current_product->update();
                            $this->createRelationship($row[9], $current_product->id, $sucursal_id);
                            $this->edit['editados'] += 1;
                        } else {
                            if ($row[3] != null || $row[3] != "") {
                                $new_product = Product::create([
                                    'active' => 1,
                                    'name' => trim($row[4]),
                                    'plu' => trim($row[3]),
                                    'price' => intval($row[6]),
                                    'order' => 1,
                                    'image' => trim($row[3]) . ".jpg",
                                    'sucursal_id' => $sucursal_id,
                                ]);
                                $new_product->save();
                                $this->createRelationship($row[9], $new_product->id, $sucursal_id);
                                $this->edit['creados'] += 1;
                            }
                        }
                    }
                    $cnt++;
                }
            }

            $reader->close();
            return array('r' => true, 'd' => null, 'm' => trans('messages.screen_products_tag45') . $this->edit['creados'] . ' creados, ' . $this->edit['editados'] . ' editados. ');
        } catch (\Exception $e) {
            // dd($e->getTrace()[6]['args'][0]);
            return array('r' => false, 'd' => null, 'm' => trans('messages.screen_products_tag46') . $e->getMessage());
        }
    }

    // funcion para crear la categoria, subcategoria y la relacion con los productos cuando se importa con una plantilla externa
    public function createRelationship($category_name, $product_id, $sucursal_id)
    {
        $this->historySubCategory = [];
        $this->historySubCategoryProduct = [];

        //verificar si la categoria existe y retorna el id de la subcategoria correspondiente, validando logica de sucursal_productos
        if ($category_name != '' && $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($category_name . '_' . $sucursal_id, $this->historySubCategory)) {
                $subcategory_id = trim($this->historySubCategory[$category_name . '_' . $sucursal_id]);
            } else {
                $subcategory_id = $this->getSubCategoryId_rowCategory($category_name, $sucursal_id);
                $this->historySubCategory[$category_name . '_' . $sucursal_id] = $subcategory_id;
            }
        } else if ($category_name != '') {
            //valida en el array si ya se consulto la categoria en la bd
            if (array_key_exists($category_name, $this->historySubCategory)) {
                $subcategory_id = trim($this->historySubCategory[$category_name]);
            } else {
                $subcategory_id = $this->getSubCategoryId_rowCategory($category_name);
                $this->historySubCategory[$category_name] = $subcategory_id;
            }
        } else {
            return false;
        }

        if (isset($subcategory_id) && !array_key_exists($subcategory_id . $product_id, $this->historySubCategoryProduct)) {
            $new_subcategory_products = SubcategoryProduct::create([
                'subcategory_id' => $subcategory_id,
                'product_id' => $product_id,
            ]);
            $this->historySubCategoryProduct[$subcategory_id . $product_id] = true;
            return true;
        } else {
            return false;
        }
    }

    // metodo para filtrar el producto por el nombre o plu desde el pedido e-commerce
    public function autocomplete(Request $request)
    {
        $term = $request->input('term');
        $results = array();
        $parameters = Parameter::where('id', 1)->first();

        $user_sucursal_id = UserInformation::where('user_id',Auth::user()->id)->first();

        // realiza la busqueda en la bd
        // $queries = DB::table('products')
        //     ->where('name', 'LIKE', '%' . $term . '%')
        //     ->orWhere('plu', 'LIKE', '%' . $term . '%')
        //     ->take(5)->get();

        $queries = Product::with('subcategory_products','productImages')
                            ->where('active', 1)
                            ->where('name', 'like', '%' . $term . '%')
                            ->orWhere('plu', 'like', '%' . $term . '%')
                            ->has('subcategory_products')
                            ->take(5);

        if ($parameters->sucursal_products) {
            $queries = $queries->where('sucursal_id',$user_sucursal_id->sucursal_id)->get();
        } else {
            $queries = $queries->get();
        }

        // se recorre el array para obtener los datos necesarios y mandarlos al js
        foreach ($queries as $query) {
            $query->product_attributes = ProductAttribute::where('product_id', $query->id)->with('attribute')->get()->groupBy('attribute_id')->toArray();
            $results[] = [
                'id' => $query->id,
                'plu' => $query->plu,
                'value' => $value = $query->name . ' - ' . $query->plu . ' - $' . $query->price,
                'price' => $query->price,
                'max_units_per_order' => $query->max_units_per_order,
                'flash_price' => $query->flash_price,
                'percentage_discount' => $query->percentage_discount,
                'limit_discount' => $query->limit_discount,
                'limit_flash_discount' => $query->limit_flash_discount,
                'limit_hour_discount' => $query->limit_hour_discount,
                'start_discount' => $query->start_discount,
                'start_flash_discount' => $query->start_flash_discount,
                'limit_hour_flash_discount' => $query->limit_hour_flash_discount,
                'product_attributes' => $query->product_attributes,
                'data' => json_encode($query),
            ];
        }
        //dd($results);
        return json_encode($results);
    }

    function human_filesize($bytes, $decimals = 0) {
        $sz = 'BKMGTP';
        $factor = floor((strlen($bytes) - 1) / 3);
        return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor));
    }

    public function uploadMassivePhoto(Request $request)
    {
        if($this->human_filesize(filesize($request->file('file'))) < 2000){
            $filenametostore = $request->file('file')->getClientOriginalName();
            $extension = $request->file('file')->getClientOriginalExtension();
            $listName = explode(".", $filenametostore);
            $isMoreOne = explode("_", $listName[0]);
            $current_plu = "";
            if(count($isMoreOne) > 1){
                $product = Product::select('id','reference_woocommerce_product_id','reference_shopify_id')->where('plu', $isMoreOne[0])->first();
                $current_plu = $isMoreOne[0];
            }else{
                $product = Product::select('id','reference_woocommerce_product_id','reference_shopify_id')->where('plu', $listName[0])->first();
                $current_plu = $listName[0];
            }

            if($product){
                $indb = ProductImage::where('name', $filenametostore)->first();
                if(!$indb){
                    ProductImage::create([
                        "name" => $filenametostore,
                        "product_id" => $product->id,
                    ]);
                }

                if ($extension == "jpg" || $extension == "png" || $extension == "mp4" || $extension == "jpeg") {
                    Storage::disk('s3')->put(env('S3_PRODUCTS_PATH') . $filenametostore, fopen($request->file('file'), 'r+'), 'public');
                    $woo = new WoocommerceController();
                    $data = [
                        'image' => [
                            'src' => env('AWS_URL').'/products/'.$filenametostore
                        ]
                    ];
                    $woo->updateProduct($product->reference_woocommerce_product_id,$data);

                    $sho = new ShopifyController();
                    $data_sho = [
                        'src' => env('AWS_URL').'/products/'.$filenametostore
                    ];
                    $sho->addImageProduct($product->reference_shopify_id,$data_sho);
                    return array('r' => 200);
                }
            }else{
                return response('El plu: ' . $current_plu . ' no existe')->setStatusCode(500);
            }
        }else{
            return response('Tamaño del archivo superior a 2MB')->setStatusCode(500);
        }
        return response('Error')->setStatusCode(500);
    }

    function getGlobalInventoryFromPLU($plu){
        $services = new ServiceCity();
        $services->setConnection('main-db');

        $databases = $services->where('active',1)->get();
        $response = [];

        foreach ($databases as $db) {
            $productQty = Product::on($db->name_database)->select('id', 'plu', 'available_units', 'available_warehouse')->where('plu', $plu)->first();

            if(!$productQty){
                continue;
            }

            $response[] = array(
                'city' => $db-> name,
                'plu' => $plu,
                'qty_bin' => $productQty->available_units,
                'qty_warehouse' => $productQty->available_warehouse
            );
        }

        return $response;
    }
}