<?php

namespace App\Http\Controllers;

use App\Models\Items;
use App\Models\Sitemaps;
use Goutte\Client;
use GuzzleHttp\Exception\ClientException;
use Illuminate\Http\Request;
use Nesk\Puphpeteer\Puppeteer;
use Nesk\Rialto\Data\JsFunction;
use Symfony\Component\BrowserKit\HttpBrowser;
use Symfony\Component\DomCrawler\Crawler;
use Symfony\Component\HttpClient\HttpClient;
use DB;

class ItemsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function puntofarma_guardar_items()
    {
        //
        //
        set_time_limit(500000);
        $links = Sitemaps::where('business_id', '=', '2')
            ->get();
        $i      = 1;
        $j      = 1;
        $items  = array();
        $client = new Client();
        $links  = [];
        // $links[0]['link'] = 'https://www.puntofarma.com.py/producto/229256/pack-sedal-shampoo-+-acondicionador-+-crema-tratamiento-de-regalo';
        foreach ($links as $link) {
            //  if($j>7500){
            if ($link['link'] == 'https://www.puntofarma.com.py') {
                continue;
            } else {
                /*
                 * $puppeteer = new Puppeteer();
                 * $browser = $puppeteer->launch();
                 * $page = $browser->newPage();
                 * $page->setDefaultNavigationTimeout(300000);
                 * $page->goto($link['link']);
                 * $html = $page->content();
                 *
                 * $crawler = new Crawler($html);
                 */
                $crawler = $client->request('GET', $link['link']);
                $crawler->filter('span.price')->each(function ($node) {
                    print $node->text() . "\n";
                });

                $priceOld = $crawler->filter('del.precio-sin-descuento')->text();
                dd($priceOld);
                //   die('f');
                $price = $crawler->filter('div.precio-con-descuento span')->text();

                if (!isset($price) || empty($price)) {
                    continue;
                }

                $price = explode(' ', $price);
                $price = $price[1];
                $price = str_replace('.', '' . $price);

                $codigo_barras = $crawler->filter('span[class="ms-2 user-select-all"]')->text();
                // dd($codigo_barras);
                if (!isset($codigo_barras) || empty($codigo_barras)) {
                    continue;
                }

                $titulo = $crawler->filter('h1')->first()->text();
                // dd($titulo);
                if (!isset($titulo) || empty($titulo)) {
                    continue;
                }

                $imagen = $crawler->filter('img[class="iiz__img   "]')->attr('src');
                //  dd($imagen);
                $item =
                    [
                        'business_id' => $link['business_id'],
                        'title'       => $titulo,
                        'sku'         => $codigo_barras,
                        'link'        => $link['link'],
                        'image'       => $imagen,
                        'price_now'   => $price
                    ];
                // dd($item);
                Items::updateOrCreate($item);

                $items[] = $item;
                echo $j . '-' . $link['link'] . ' --> OK <br> ';
            }
            // }
            $j++;
            $i++;
        }

        dd($items);
    }

    // puntofarma buscar item
    public function puntofarma_buscar_items()
    {
        $c = 1;
        $s = 1;
        $q = '';
        if (isset($_GET['q']) && !empty($_GET['q'])) {
            $q = $_GET['q'];
        } else {
            die('Debe proporcionar un termino de busqueda');
        }
        if (isset($_GET['c']) && !empty($_GET['c'])) {
            $c = $_GET['c'];
        }
        if (isset($_GET['s']) && !empty($_GET['s'])) {
            $s = $_GET['s'];
        }

        set_time_limit(500000);
        $links = Sitemaps::where('business_id', '=', '2')
            ->where('link', 'LIKE', '%' . $q . '%')
            ->get();

        // dd($links);
        foreach ($links as $link) {
            //  if($j>7500){
            if ($link['link'] == 'https://www.puntofarma.com.py') {
                continue;
            } else {
                $this->puntofarma_guardar_item($link['link']);
            }
        }
        // dd($items);
    }

    // puntofar buscar items

    public function puntofarma_guardar_item($url)
    {
        //
        //
        set_time_limit(5000000);

        $_url = '';
        $_cat = 0;
        if (is_array($url)) {
            $_url = $url['url'];
            $_cat = $url['cat'];
        } else {
            $_url = $url;
        }
        set_time_limit(500000);
        $links[]['link'] = $_url;
        $msg             = '';

        $items = array();

     

        foreach ($links as $link) {
            //  if($j>7500){
            if ($link['link'] == 'https://www.puntofarma.com.py') {
                continue;
            } else {
                echo "<a href='".$link['link']." '>".$link['link']."</a><br>";
                try{
                    $puppeteer = new Puppeteer();
                $browser = $puppeteer->launch();
                $page    = $browser->newPage();
                $page->setDefaultNavigationTimeout(3000000);
                $page->goto($link['link']);

                $data = $page->evaluate(JsFunction::createWithBody('return document.documentElement.outerHTML'));
                $browser->close();
                $crawler = new Crawler($data);
              
                $price = $crawler->filter('div.precio-con-descuento span')->text();

                // dd($price);
                if (!isset($price) || empty($price)) {
                    continue;
                }
                $price = explode(' ', $price);
                $price = $price[1];
                $price = (int) str_replace('.','', $price);

                

                //price old
                $priceOld = $crawler->filter('del.precio-sin-descuento')->text();
                // dd($price);
                if (!isset($priceOld) || empty($priceOld)) {
                    continue;
                }
                $priceOld = explode(' ', $priceOld);
                $priceOld = $priceOld[1];
                $priceOld = (int) str_replace('.','', $priceOld);


                $codigo_barras = $crawler->filter('span[class="ms-2 user-select-all"]')->text();
                // dd($codigo_barras);
                if (!isset($codigo_barras) || empty($codigo_barras)) {
                    continue;
                }

                $titulo = $crawler->filter('h1')->first()->text();
                // dd($titulo);
                if (!isset($titulo) || empty($titulo)) {
                    continue;
                }

                $imagen = $crawler->filter('img[class="iiz__img   "]')->attr('src');
               // dd($imagen);

                $item              = new Items();
                $item->business_id = 2;
                $item->title = $titulo;
                $item->sku   = $codigo_barras;
                $item->image = $imagen;
                $item->link  = $link['link'];
                if ($_cat > 0) {
                    $item->category_id = $_cat;
                }
                $item->price_now = $price;
                $item->price_old = $priceOld;
                $item->price_off = $this->dame_porc_desc($priceOld, $price);
                $item->save();

                $msg = '-' . $link['link'] . ' --> OK <br> ';
                echo $msg;
                }catch(\InvalidArgumentException $e){
                    continue;
                }
                
            }
        }
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function puntofarma_actualizar_items()
    {
        //
        //
        set_time_limit(500000);
        $links = Items::where('business_id', '=', '2')
            ->skip(1000)
            ->get();
        $i     = 1;
        $j     = 1;
        $items = array();
        // initialize an HTTP client object
        $client = new HttpClient();
        // initialize a browser-like HTTP client
        // $browser = new HttpBrowser(HttpClient::create());
        $msg       = '';
        $puppeteer = new Puppeteer();
        foreach ($links as $link) {
            //  if($j>7500){
            if ($link['link'] == 'https://www.puntofarma.com.py') {
                continue;
            } else {
                $browser = $puppeteer->launch();
                $page    = $browser->newPage();
                $page->setDefaultNavigationTimeout(300000);
                $page->goto($link['link']);
                $html = $page->content();

                // $crawler = new Crawler($html);
                $data = $page->evaluate(JsFunction::createWithBody('return document.documentElement.outerHTML'));
                $page->close();
                $crawler = new Crawler($data);
                /*$crawler = $browser->request('GET', $link['link']);
// get the response returned by the server
$response = $browser->getResponse();
//dd($response);F
// extract the HTML content and print it
$html = $response->getContent();
// /die($html);
              // dd($html);
              // $jsonData = json_decode($res->getBody(), true);

             // dd($jsonData); */
                // dd($crawler->html());
                echo $link['id'] . ' - ' . $link['link'];
                // dd($crawler->filter('span[class="price text-primary font-weight-bolder"]')->text());
                if (empty($crawler->filter('div.prices')->filter('span.price')->text())) {
                    dd($crawler);
                    continue;
                }
                $price = $crawler->filter('span[class="price text-primary font-weight-bolder"]')->text();
                // dd($orice);
                if (!isset($price) || empty($price)) {
                    continue;
                }
                $price = explode(' ', $price);
                $price = $price[1];
                $price = explode('.', $price);
                $price = $price[0] . $price[1];
                $price = intval($price);
                if ($link['price'] != $price) {
                    // code...
                    //  dd($imagen);
                    $item = Items::find($link['id']);
                    if (!is_null($item)) {
                        $item->price      = $price;
                        $item->updated_at = now();
                        $item->update();
                        $msg = 'precio actualizado';
                    } else {
                        $msg = 'precio iguak';
                    }

                    $items[] = $item;
                    echo $j . '-' . $link['link'] . ' --> OK <br> ';
                }
            }
            // }
            $j++;
            $i++;
        }

        dd($items);
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function catedral_guardar_items()
    {
        //
        //
        set_time_limit(500000);
        $links = Sitemaps::where('business_id', '=', 4)->limit(1000)->skip(200)->get()->toArray();
        // dd($links);
        $i      = 0;
        $j      = 0;
        $items  = array();
        $client = new Client();

        foreach ($links as $link) {
            if ($link['link'] == 'https://farmaciacatedral.com.py') {
                continue;
            } else {
                try {
                    // $link['link']="https://farmaciacatedral.com.py/producto/corine-baby-gel-ducha-corps-cheveux-frasco-x-500-ml18825";
                    $crawler = $client->request('GET', $link['link']);
                    // dd($crawler);
                    $url_res = $crawler->getURI();
                    // dd( $code);
                    $url = 'https://farmaciacatedral.com.py/producto/../productos';
                    if ($url_res == $url) {
                        $l = Sitemaps::where('link', '=', $link['link'])->delete();
                        echo 'saltamos ';
                        continue;
                    } else {
                        /* if (!$crawler->filter('p.product-title')->text()) {
                             echo $j . '-' . $link['link'] . ' --> ' . $msg . ' no tiene codigo de barras <br> ';
                             $s = Sitemaps::where('business_id', '=', 4)
                                 ->where('link', '=', $link['link'])
                                 ->delete();
                             continue;
                         }
                         $codigo_barras = $crawler->filter('p[class="product-title"]')->text();
                         // dd($codigo_barras);
                         if (!isset($codigo_barras) || empty($codigo_barras)) {
                             continue;
                         } else {
                             $codigo_barras = explode(' ', $codigo_barras);
                             $t             = count($codigo_barras) - 1;
                             $codigo_barras = substr($codigo_barras[$t], 2);
                             // dd($codigo_barras);
                             $price = $crawler->filter('h5.precio-ahora')->text();
                             if (!isset($price) || empty($price)) {
                                 continue;
                             }
                             $price = explode(' ', $price);
                             $price = $price[1];
                             $price = explode('.', $price);
                             $price = $price[0] . $price[1];
                             // dd($price);
                             $titulo = $crawler->filter('h1.product-title')->text();
                             if (!isset($titulo) || empty($titulo)) {
                                 continue;
                             }

                             $imagen = $crawler->filter('img.img-thumbnail')->attr('src');
                             if (empty($imagen)) {
                                 continue;
                             }
                             // dd($imagen);
                             $_item = Items::where('business_id', '=', 4)
                                 ->where('sku', '=', $codigo_barras)
                                 ->get();
                             if (count($_item) == 0) {
                                 $this->farmatotal_guardar_item($link['link']);
                             } else {
                                 // dd($_item[0]['id']);
                                 $item              = Items::find($_item[0]['id']);
                                 $item->business_id = 4;
                                 $item->title       = $titulo;
                                 $item->image       = $imagen;
                                 $item->price       = $price;
                                 $item->link        = $link['link'];
                                 $item->update();
                                 $msg = 'actualizado <br/>';
                             }
                             $items[] = $item;
                             echo $j . '-' . $link['link'] . ' --> ' . $msg . ' OK <br> ';
                         }*/
                        $this->catedral_guardar_item($link['link']);
                    }
                } catch (Exception $e) {
                    continue;
                } catch (InvalidArgumentException $e1) {
                    continue;
                }
            }

            $j++;
            $i++;
        }

        // dd($items);
    }

    public function catedral_guardar_item_array($data)
    {
        $msg = '';

        if (!is_array($data)) {
            die('Debe proporcionar un Array');
        } else {
            echo 'Farmacia Catedral:  ' . count($data) . ' items encontrados<hr>';
            foreach ($data as $node) {
                $_link = Sitemaps::where('link', '=', $node['link'])
                    ->where('business_id', '=', 4)
                    ->get()
                    ->toArray();
                if (!$_link) {
                    $link              = new Sitemaps();
                    $link->link        = $node['link'];
                    $link->business_id = 4;
                    $link->save();
                    $msg = 'el Link <a href="' . $node['link'] . '" >' . $node['title'] . '</a> fue guardao entre los Sitemaps<br>';
                }

                $_item = Items::where('link', '=', $node['link'])
                    ->where('business_id', '=', 4)
                    ->get()
                    ->toArray();
                if (!$_item) {
                    Items::Create($node);
                    $msg = 'el Item <a href="' . $node['link'] . '" >' . $node['title'] . '</a> fue guardado entre los Items<br>';
                } else {
                    $item = Items::find($_item[0]['id']);

                    $item->business_id    = 4;
                    $item->brand_id       = $node['brand_id'];
                    $item->category_id    = $node['category_id'];
                    $item->subcategory_id = $node['subcategory_id'];
                    $item->price_now      = $node['price_now'];
                    $item->price_now      = $node['price_now'];
                    $item->price_old      = $node['price_old'];
                    $item->price_off      = $node['price_off'];
                    $item->update();
                    $msg = 'el Item <a href="' . $node['link'] . '" >' . $node['title'] . '</a> fue actualizado entre los Items<br>';
                }
                echo $msg;
            }
        }
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function catedral_guardar_item($url)
    {
        //
        //

        $_url = '';
        $_cat = 0;
        if (is_array($url)) {
            $_url = $url['url'];
            $_cat = $url['cat'];
        } else {
            $_url = $url;
        }
        set_time_limit(500000);
        $links[]['link'] = $_url;

        $i      = 0;
        $j      = 0;
        $items  = array();
        $client = new Client();
        $msg    = '';
        foreach ($links as $link) {
            // dd($link);

            if ($link['link'] == 'https://farmaciacatedral.com.py') {
                continue;
            } else {
                try {
                    // $link['link']="https://farmaciacatedral.com.py/producto/corine-baby-gel-ducha-corps-cheveux-frasco-x-500-ml18825";
                    $crawler = $client->request('GET', $link['link']);
                    $url_res = $crawler->getURI();
                    // dd( $code);
                    $url = 'https://farmaciacatedral.com.py/producto/../productos';
                    if ($url_res == $url) {
                        $l = Sitemaps::where('link', '=', $link['link'])->delete();
                        echo 'saltamos ';
                        continue;
                    } else {
                        if (!$crawler->filter('p.product-title')->text()) {
                            echo $j . '-' . $link['link'] . ' --> ' . $msg . ' no tiene codigo de barras <br> ';
                            $s = Sitemaps::where('business_id', '=', 4)
                                ->where('link', '=', $link['link'])
                                ->delete();
                            continue;
                        }
                        $codigo_barras = $crawler->filter('p[class="product-title"]')->text();
                        if (!isset($codigo_barras) || empty($codigo_barras)) {
                            continue;
                        } else {
                            $codigo_barras = explode(' ', $codigo_barras);
                            $t             = count($codigo_barras) - 1;
                            $codigo_barras = substr($codigo_barras[$t], 2);
                            //  dd($codigo_barras);
                            $price = $crawler->filter('h5.precio-ahora')->text();
                            if (!isset($price) || empty($price)) {
                                continue;
                            }
                            $price = explode(' ', $price);
                            $price = $price[1];
                            $price = explode('.', $price);
                            $price = $price[0] . $price[1];
                            // dd($price);
                            $titulo = $crawler->filter('h1.product-title')->text();
                            if (!isset($titulo) || empty($titulo)) {
                                continue;
                            }

                            $imagen = $crawler->filter('img.img-thumbnail')->attr('src');
                            if (empty($imagen)) {
                                continue;
                            }

                            $off = $crawler->filter('h5.precio-desc')->text();

                            if (empty($off) || is_null($off)) {
                                continue;
                            }
                            $off = explode('%', $off);

                            $off        = $off[0];
                            $precio_old = $this->dame_precio_desc($price, $off);
                            // echo $price;
                            // dd($precio_old);

                            // dd($imagen);
                            $_item = Items::where('link', '=', $link['link'])->get();
                            if (count($_item) > 0) {
                                $item              = Items::find($_item[0]['id']);
                                $item->business_id = 4;
                                $item->title       = $titulo;
                                $item->sku         = $codigo_barras;
                                $item->image       = $imagen;

                                $item->price_now = $price;
                                $item->price_old = $precio_old;
                                $item->price_off = $off;
                                if ($_cat > 0) {
                                    $item->category_id = $_cat;
                                }
                                $item->update();
                                $msg = 'actualizado <br>';
                            } else {
                                $item              = new Items();
                                $item->business_id = 4;
                                $item->title       = $titulo;
                                $item->sku         = $codigo_barras;
                                $item->image       = $imagen;
                                $item->link        = $link['link'];
                                $item->price_now   = $price;
                                $item->price_old   = $precio_old;
                                $item->price_off   = $off;
                                if ($_cat > 0) {
                                    $item->category_id = $_cat;
                                }
                                $item->save();
                                $msg = 'creado <br>';
                            }

                            $items[] = $item;
                            $msg     = $j . '-' . $link['link'] . ' --> ' . $msg . ' OK <br> ';
                        }
                    }
                } catch (Exception $e) {
                    continue;
                } catch (InvalidArgumentException $e1) {
                    continue;
                }
            }

            $j++;
            $i++;
            echo $msg;
        }
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function catedral_actualizar_items()
    {
        //
        //
        set_time_limit(500000);
        $links = Items::where('business_id', '=', 4)
            ->get();

        $i      = 0;
        $j      = 0;
        $items  = array();
        $client = new Client();

        foreach ($links as $link) {
            // dd($link);

            if ($link['link'] == 'https://farmaciacatedral.com.py') {
                continue;
            } else {
                try {
                    // $link['link']="https://farmaciacatedral.com.py/producto/corine-baby-gel-ducha-corps-cheveux-frasco-x-500-ml18825";
                    $crawler = $client->request('GET', $link['link']);
                    $url_res = $crawler->getURI();
                    // dd( $code);
                    $url = 'https://farmaciacatedral.com.py/producto/../productos';
                    if ($url_res == $url) {
                        $l = Sitemaps::where('link', '=', $link['link'])->delete();
                        echo 'saltamos ';
                        continue;
                    } else {
                        $price = $crawler->filter('h5.precio-ahora')->text();

                        //  $categoria = $crawler->filter('ul.history li a')->children()->filter('b')->text();
                        //   $cat_id = DB::select("SELECT fn_dame_categoria_id_x_nombre('".$categoria."');");
                        // dd($cat_id);
                        // dd($categoria);
                        if (!isset($price) || empty($price)) {
                            continue;
                        }
                        $price = explode(' ', $price);
                        $price = $price[1];
                        $price = explode('.', $price);
                        $price = $price[0] . $price[1];
                        $price = intval($price);
                        $item  = Items::find($link['id']);
                        $msg   = '';
                        if ($link['price'] != $price) {
                            // dd($_item[0]['id']);

                            $item->price      = $price;
                            $item->updated_at = now();
                            $item->update();

                            $msg = 'precio actualizado <br/>';
                        } else {
                            $msg = 'precio igual <br/>';
                        }

                        $items[] = $item;
                        echo $j . '-' . $link['link'] . ' --> ' . $msg . ' OK <br> ';
                    }
                } catch (Exception $e) {
                    continue;
                } catch (InvalidArgumentException $e1) {
                    continue;
                }
            }

            $j++;
            $i++;
        }

        dd($items);
    }

    /*
     * buscador ajax catedral
     */
    function catedral_buscar_items_ajax()
    {
        $q   = $_GET['q'];
        $url = 'https://farmaciacatedral.com.py/get-productos?page=1&query_string=' . $q;
  //die($url);
        $con = curl_init();

        curl_setopt($con, CURLOPT_URL, $url);
        curl_setopt($con, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($con, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($con, CURLOPT_SSL_VERIFYPEER, 0);
        $res = curl_exec($con);
        curl_close($con);

    //     dd($res);
        $data = [];
        $res  = json_decode($res);
        //  dd($res);

        foreach ($res as $n) {
            if (isset($n->data)) {
                $i = 0;
                foreach ($n->data as $p) {
                    if(!$this->exist_url($p->url_ver)){
                continue;
            }
                    $c = 1;
                    $s = 1;
                    if (isset($_GET['c']) && !empty($_GET['c'])) {
                        $c = $_GET['c'];
                    }
                    if (isset($_GET['s']) && !empty($_GET['s'])) {
                        $s = $_GET['s'];
                    }
                    $data[$i]['title']          = $p->nombre;
                    $data[$i]['brand_id']       = $this->catedral_dame_marca($p->url_ver);
                    $data[$i]['business_id']    = 4;
                    $data[$i]['category_id']    = $c;
                    $data[$i]['subcategory_id'] = $s;
                    $data[$i]['image']          = $p->primera_imagen;
                    $data[$i]['price_now']      = $p->getPrecio;
                    $data[$i]['price_old']      = $p->getPrecioAnterior;
                    $data[$i]['price_off']      = $p->descuento_porcentual;
                    $data[$i]['link']           = $p->url_ver;
                    $data[$i]['sku']            = $this->catedral_dame_sku($p->url_ver);
                    $i++;
                }
            }
        }
        $this->catedral_guardar_item_array($data);
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function farmacenter_guardar_items()
    {
        //
        //
        set_time_limit(50000);
        $links = Sitemaps::where('business_id', '7')
            ->get();

        $i     = 0;
        $j     = 1;
        $items = array();
        // dd($links);
        $client = new Client();
        // d($client);
        foreach ($links as $link) {
            if ($link['link'] == 'https://www.farmacenter.com.py') {
                continue;
            } else {
                try {
                    $crawler  = $client->request('GET', $link['link']);
                    $response = $client->getResponse();
                    //   dd($response);
                    if ($response->getStatusCode() == 404) {
                        continue;
                    }
                    IF (!$crawler->filter('span[id="producto-ean"]')->text()) {
                        Sitemaps::where('link', $link['link'])->delete();
                        continue;
                    }
                    // dd($crawler);
                    $codigo_barras = $crawler->filter('span[id="producto-ean"]')->text();
                    // dd($codigo_barras);
                    // dd($codigo_barras);
                    if (!isset($codigo_barras) || empty($codigo_barras)) {
                        continue;
                    }
                    $codigo_barras = explode(' ', $codigo_barras);
                    $t             = count($codigo_barras) - 1;
                    $codigo_barras = $codigo_barras[$t];
                    // dd($codigo_barras);
                    $price = $crawler->filter('span[id="producto-precio-fiel"]')->text();

                    $price = explode(' ', $price);
                    // $price = $price[1];
                    $price = explode('.', $price[1]);

                    $price = $price[0] . $price[1];
                    // dd($price);
                    echo $link['id'] . '-' . $price . '<br> ';
                    if (!isset($price) || empty($price)) {
                        continue;
                    }
                    $titulo = $crawler->filter('h1[id="producto-nombre"]')->text();
                    // dd($titulo);
                    if (!isset($titulo) || empty($titulo)) {
                        continue;
                    }
                    $imagen = $crawler->filter('img.wp-post-image')->attr('data-src');

                    // dd($imagen);
                    if (empty($imagen)) {
                        continue;
                    }
                    $msg = '';
                    $_item = Items::where('business_id', '=', $link['business_id'])
                        ->where('sku', '=', $codigo_barras)
                        ->get();
                    if (count($_item) == 0) {
                        $item = [
                            'business_id' => $link['business_id'],
                            'title'       => $titulo,
                            'sku'         => $codigo_barras,
                            'image'       => $imagen,
                            'link'        => $link['link'],
                            'price'       => $price
                        ];
                        Items::create($item);
                        $msg = 'creado';
                    } else {
                        // dd($_item[0]['id']);
                        $item        = Items::find($_item[0]['id']);
                        $item->title = $titulo;
                        $item->image = $imagen;
                        $item->price = $price;
                        $item->link  = $link['link'];
                        $item->update();
                        $msg = 'actualizado';
                    }

                    $items[] = $item;
                    echo $j . '-' . $link['link'] . ' --> ' . $msg . '  OK <br> ';

                    /*
                     * echo $j."-".$link['link']." --> OK <br> ";
                     * }
                     */
                } catch (Exception $e) {
                    continue;
                } catch (ErrorException $e1) {
                    continue;
                }
            }
            $j++;
            $i++;
        }

        dd($items);
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function farmacenter_actualizar_items()
    {
        //
        //
        set_time_limit(50000);
        $links = Items::where('business_id', '7')
            ->get();

        $i     = 372;
        $j     = 1;
        $items = array();
        // dd($links);
        $client = new Client();
        // d($client);
        foreach ($links as $link) {
            if ($link['link'] == 'https://www.farmacenter.com.py') {
                continue;
            } else {
                try {
                    $crawler  = $client->request('GET', $link['link']);
                    $response = $client->getResponse();
                    //   dd($response);
                    if ($response->getStatusCode() == 404) {
                        continue;
                    }
                    IF (!$crawler->filter('span[id="producto-ean"]')->text()) {
                        Sitemaps::where('link', $link['link'])->delete();
                        continue;
                    }

                    $price = $crawler->filter('span[id="producto-precio-fiel"]')->text();

                    $price = explode(' ', $price);
                    // $price = $price[1];
                    $price = explode('.', $price[1]);

                    $price = $price[0] . $price[1];
                    // dd($price);
                    echo $link['id'] . '-' . $price . '<br> ';
                    if (!isset($price) || empty($price)) {
                        continue;
                        $msg = 'precio igual';
                    }

                    // dd($_item[0]['id']);
                    $item = Items::find($link['id']);

                    $item->price = $price;

                    $item->update();
                    $msg = 'precio actualizado';

                    $items[] = $item;
                    echo $j . '-' . $link['link'] . ' --> ' . $msg . '  OK <br> ';
                } catch (Exception $e) {
                    continue;
                } catch (ErrorException $e1) {
                    continue;
                }
            }
            $j++;
            $i++;
        }

        dd($items);
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function farmacenter_guardar_item_old($url)
    {
        //
        $_url = '';
        $_cat = 0;
        if (is_array($url)) {
            $_url = $url['url'];
            $_cat = $url['cat'];
        } else {
            $_url = $url;
        }
        set_time_limit(500000);
        $links[]['link'] = $_url;
        $i = 372;
        $j = 1;
        $items = array();
        $client = new Client(array(
            'curl' => array(
                CURLOPT_TIMEOUT        => 60,
                CURLOPT_SSL_VERIFYHOST => false,
                CURLOPT_SSL_VERIFYPEER => false,
            ),
        ));
        // dd($links);

        // curl_setopt($con, CURLOPT_SSL_VERIFYHOST, false);
        // curl_setopt($con, CURLOPT_SSL_VERIFYPEER, false);//
        dd($client);
        $msg = '';
        foreach ($links as $link) {
            if ($link['link'] == 'https://www.farmacenter.com.py') {
                continue;
            } else {
                try {
                    $crawler  = $client->request('GET', $link['link']);
                    $response = $client->getResponse();
                    //   dd($response);
                    if ($response->getStatusCode() == 404) {
                        continue;
                    }
                    IF (!$crawler->filter('span[id="producto-ean"]')->text()) {
                        Sitemaps::where('link', $link['link'])->delete();
                        continue;
                    }
                    // dd($crawler);
                    $codigo_barras = $crawler->filter('span[id="producto-ean"]')->text();
                    // dd($codigo_barras);
                    // dd($codigo_barras);
                    if (!isset($codigo_barras) || empty($codigo_barras)) {
                        continue;
                    }
                    $codigo_barras = explode(' ', $codigo_barras);
                    $t             = count($codigo_barras) - 1;
                    $codigo_barras = $codigo_barras[$t];
                    // dd($codigo_barras);
                    $price = $crawler->filter('span[id="producto-precio-fiel"]')->text();

                    $price = explode(' ', $price);
                    // $price = $price[1];
                    $price = explode('.', $price[1]);

                    $price = $price[0] . $price[1];
                    // dd($price);

                    if (!isset($price) || empty($price)) {
                        continue;
                    }
                    $titulo = $crawler->filter('h1[id="producto-nombre"]')->text();
                    // dd($titulo);
                    if (!isset($titulo) || empty($titulo)) {
                        continue;
                    }
                    $imagen = $crawler->filter('img.wp-post-image')->attr('data-src');

                    // dd($imagen);
                    if (empty($imagen)) {
                        continue;
                    }
                    $msg = '';

                    $item              = new Items();
                    $item->business_id = 7;

                    $item->title = $titulo;
                    $item->sku   = $codigo_barras;
                    $item->image = $imagen;
                    $item->link  = $link['link'];
                    if ($_cat > 0) {
                        $item->category_id = $_cat;
                    }
                    $item->price = $price;
                    $item->save();
                    $msg = 'creado';

                    $items[] = $item;
                    $msg     = $j . '-' . $link['link'] . ' --> ' . $msg . '  OK <br> ';

                    /*
                     * echo $j."-".$link['link']." --> OK <br> ";
                     * }
                     */
                } catch (Exception $e) {
                    continue;
                } catch (ErrorException $e1) {
                    continue;
                }
            }
            $j++;
            $i++;
        }

        return $msg;
    }

    // farmacenter guardar item array
    public function farmacenter_guardar_item_arrary() {}

    // frmacenter guardar item
    public function farmacenter_guardar_item($url)
    {
        //
        $_url = '';
        $_cat = 0;
        if (is_array($url)) {
            $_url = $url['url'];
            $_cat = $url['cat'];
        } else {
            $_url = $url;
        }
        set_time_limit(500000);
        $links[]['link'] = $_url;
        $i               = 372;
        $j               = 1;
        $items           = array();
        $ch              = curl_init();
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);  // Return data inplace of echoing on screen
        curl_setopt($ch, CURLOPT_URL, $_url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);  // Skip SSL Verification
        $html = curl_exec($ch);
        // die($html);
        curl_close($ch);
        $msg = '';
        try {
            $crawler = new Crawler($html);

            IF (!$crawler->filter('span[id="producto-ean"]')->text()) {
                Sitemaps::where('link', $links['link'])->delete();
                // continue;
            }
            // dd($crawler);
            $codigo_barras = $crawler->filter('span[id="producto-ean"]')->text();
            // dd($codigo_barras);
            // dd($codigo_barras);
            if (!isset($codigo_barras) || empty($codigo_barras)) {
                // continue;
            }
            $codigo_barras = explode(' ', $codigo_barras);
            $t             = count($codigo_barras) - 1;
            $codigo_barras = $codigo_barras[$t];
            //  dd($codigo_barras);
            $price = $crawler->filter('span[id="producto-precio-fiel"]')->text();

            $price = explode(' ', $price);
            // $price = $price[1];
            $price = explode('.', $price[1]);

            $price = $price[0] . $price[1];
            // dd($price);

            if (!isset($price) || empty($price)) {
                return;
            }

            $priceOld = $crawler->filter('span[id="producto-precio-lista"]')->text();

            $priceOld = explode(' ', $priceOld);
            // $price = $price[1];
            $priceOld = explode('.', $priceOld[1]);

            $priceOld = $priceOld[0] . $priceOld[1];

            if (!isset($priceOld) || empty($priceOld)) {
                return;
            }
            // dd($priceOld);
            $titulo = $crawler->filter('h1[id="producto-nombre"]')->text();
            // dd($titulo);
            if (!isset($titulo) || empty($titulo)) {
                // continue;
            }
            $imagen = $crawler->filter('img.wp-post-image')->attr('data-src');

            // dd($imagen);
            if (empty($imagen)) {
                // continue;
            }
            $msg   = '';
            $_link = Sitemaps::where('link', '=', $_url)->get()->toArray();
            if (count($_link) > 0) {
                if (count($_link) > 1) {
                    $_link = Sitemaps::find($_link[1]['id']);
                    $_link->delete();
                }
            } else {
                $_link              = new Sitemaps();
                $_link->business_id = 7;
                $_link->link        = $_url;
                $_link->save();
            }

            $_item = Items::where('link', '=', $_url)->get()->toArray();
            if (count($_item) > 0) {
                $item              = Items::find($_item[0]['id']);
                $item->business_id = 7;

                $item->title = $titulo;
                $item->sku   = $codigo_barras;
                $item->image = $imagen;
                $item->link  = $_url;
                if ($_cat > 0) {
                    $item->category_id = $_cat;
                }
                $item->price_now = $price;
                $item->price_old = $priceOld;
                $item->price_off = $this->dame_porc_desc($priceOld, $price);

                $item->update();
                $msg = 'actualizado';
            } else {
                $item              = new Items();
                $item->business_id = 7;

                $item->title = $titulo;
                $item->sku   = $codigo_barras;
                $item->image = $imagen;
                $item->link  = $_url;
                if ($_cat > 0) {
                    $item->category_id = $_cat;
                }
                $item->price_now = $price;
                $item->price_old = $priceOld;
                $item->price_off = $this->dame_porc_desc($priceOld, $price);
                $item->save();
                $msg = 'creado';
            }

            $msg = $j . '-' . $_url . ' --> ' . $msg . '  OK <br> ';

            /*
             * echo $j."-".$link['link']." --> OK <br> ";
             * }
             */
        } catch (Exception $e) {
            // continue;
        } catch (ErrorException $e1) {
            //  continue;
        }

        return $msg;
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function oliva_guardar_items()
    {
        //
        //
        set_time_limit(50000);
        $links = Sitemaps::where('business_id', '=', '11')
            ->limit(100)
            ->offset(50)
            ->get();

        $i      = 0;
        $j      = 1;
        $items  = array();
        $client = new Client();
        // d($client);
        foreach ($links as $link) {
            //  if($j>5470){
            if ($link['link'] == 'https://www.farmaoliva.com.py') {
                continue;
            } else {
                try {
                    $crawler  = $client->request('GET', $link['link']);
                    $response = $client->getResponse();
                    // dd($response);
                    if ($response->getStatusCode() == 404) {
                        continue;
                    }

                    // dd($crawler);
                    $codigo_barras = $crawler->filter('span[id="producto-ean"]')->text();

                    //  dd($codigo_barras);
                    if (!isset($codigo_barras) || empty($codigo_barras)) {
                        continue;
                    }
                    $codigo_barras = explode(' ', $codigo_barras);
                    $t             = count($codigo_barras) - 1;
                    $codigo_barras = $codigo_barras[$t];
                    $price         = $crawler->filter('span[id="producto-precio"]')->text();
                    $price         = explode(' ', $price);
                    $price         = explode('.', $price[3]);
                    $price         = $price[0] . $price[1];
                    // dd($price);

                    if (!isset($price) || empty($price)) {
                        continue;
                    }

                    $priceOld = $crawler->filter('span[id="producto-precio-anterior"]')->text();
                    // dd($priceOld);

                    $priceOld = explode(' ', $priceOld);
                    $priceOld = explode('.', $priceOld[3]);
                    $priceOld = $priceOld[0] . $priceOld[1];

                    if (!isset($priceOld) || empty($priceOld)) {
                        continue;
                    }
                    $titulo = $crawler->filter('h1.product_title')->text();
                    // dd($titulo);
                    if (!isset($titulo) || empty($titulo)) {
                        continue;
                    }
                    $imagen = $crawler->filter('img.wp-post-image')->attr('data-src');

                    // dd($imagen);
                    if (empty($imagen)) {
                        continue;
                    }
                    $msg = '';
                    $_item = Items::where('business_id', '=', $link['business_id'])
                        ->where('sku', '=', $codigo_barras)
                        ->get();
                    if (count($_item) == 0) {
                        $this->oliva_guardar_item($link['link']);

                        $msg = ' creado';
                    } else {
                        // dd($_item[0]['id']);
                        $item              = Items::find($_item[0]['id']);
                        $item->title       = $titulo;
                        $item->price_now   = $price;
                        $item->price_old   = $priceOld;
                        $item->price_off   = $this->dame_porc_desc($priceOld, $price);
                        $item->image       = $imagen;
                        $item->link        = $link['link'];
                        $item->business_id = 11;
                        $item->update();
                        $msg = ' actualizado';
                    }

                    // $items[] = $item;
                    echo $j . '-' . $link['link'] . ' --> ' . $msg . ' OK <br> ';

                    /*
                     * echo $j."-".$link['link']." --> OK <br> ";
                     * }
                     */
                } catch (Exception $e) {
                    continue;
                } catch (ErrorException $e1) {
                    continue;
                }
            }
            //  }

            $j++;
            $i++;
        }

        // return $msg;
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function oliva_guardar_item($url)
    {
        //
        //

        set_time_limit(50000);

        $_url = '';
        $_cat = 0;
        if (is_array($url)) {
            $_url = $url['url'];
            $_cat = $url['cat'];
        } else {
            $_url = $url;
        }
        $links = [];
        set_time_limit(500000);
        $links[]['link'] = $_url;
        $i               = 0;
        $j               = 1;
        $items           = array();
        $client          = new Client();
        $msg             = '';
        // d($client);
        foreach ($links as $link) {
            //  if($j>5470){
            if ($link['link'] == 'https://www.farmaoliva.com.py') {
                continue;
            } else {
                try {
                    $crawler  = $client->request('GET', $link['link']);
                    $response = $client->getResponse();
                    // dd($response);
                    if ($response->getStatusCode() == 404) {
                        continue;
                    }

                    // dd($crawler);
                    $codigo_barras = $crawler->filter('span[id="producto-ean"]')->text();

                    //  dd($codigo_barras);
                    if (!isset($codigo_barras) || empty($codigo_barras)) {
                        continue;
                    }
                    $codigo_barras = explode(' ', $codigo_barras);
                    // dd($codigo_barras);
                    $codigo_barras = $codigo_barras[0];
                    // dd($codigo_barras);
                    // $t             = count($codigo_barras) - 1;
                    // $codigo_barras = $codigo_barras[$t];
                    $price = $crawler->filter('span[id="producto-precio"]')->text();
                    $price = explode(' ', $price);
                    $price = explode('.', $price[3]);
                    $price = $price[0] . $price[1];
                    // dd($price);

                    if (!isset($price) || empty($price)) {
                        continue;
                    }

                    $off = $crawler->filter('span[class="badge badge-pill badge-success"]')->each(function ($node) {
                        return $node->text();
                    });
                    // dd($off);
                    if (empty($off)) {
                        continue;
                    } else {
                        if (count($off) == 1) {
                            $off = 0;
                        }
                    }
                    // dd($off);
                    if (count($off) > 0) {
                        // dd($off);
                        $off = explode('%', $off[1]);
                        $off = $off[0];
                        //  dd($off);
                    }

                    $precio_old = $this->dame_precio_desc($price, $off);
                    $titulo     = $crawler->filter('h1.product_title')->text();
                    // dd($off);
                    if (!isset($titulo) || empty($titulo)) {
                        continue;
                    }
                    $imagen = $crawler->filter('img.wp-post-image')->attr('data-src');

                    //  dd($imagen);
                    if (empty($imagen)) {
                        continue;
                    }

                    $item              = new Items();
                    $item->business_id = 11;

                    $item->title = $titulo;
                    $item->sku   = $codigo_barras;
                    $item->image = $imagen;
                    $item->link  = $link['link'];
                    /* if ($_cat > 0) {
                         $item->category_id = $_cat;
                     } */
                    $item->price_now = $price;
                    $item->price_old = $precio_old;
                    $item->price_off = $off;
                    $item->save();
                    $msg = 'creado';

                    // $items[] = $item;
                    $msg = $j . '-' . $link['link'] . ' --> ' . $msg . ' OK <br> ';

                    /*
                     * echo $j."-".$link['link']." --> OK <br> ";
                     * }
                     */
                } catch (Exception $e) {
                    continue;
                } catch (ErrorException $e1) {
                    continue;
                }
            }
            //  }

            $j++;
            $i++;
        }

        return $msg;
    }

    // actualizar precios oliva

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function oliva_actualizar_items()
    {
        //
        //
        set_time_limit(50000);
        $links = Items::where('business_id', '11')
            // ->where('link','ilike','%alg%')
            ->get();

        $i      = 0;
        $j      = 1;
        $items  = array();
        $client = new Client();
        // d($client);
        foreach ($links as $link) {
            //  if($j>5470){
            if ($link['link'] == 'https://www.farmaoliva.com.py') {
                continue;
            } else {
                try {
                    $crawler  = $client->request('GET', $link['link']);
                    $response = $client->getResponse();
                    // dd($response);
                    if ($response->getStatusCode() == 404) {
                        continue;
                    }

                    $price = $crawler->filter('span[id="producto-precio"]')->text();
                    $price = explode(' ', $price);
                    $price = explode('.', $price[3]);
                    $price = $price[0] . $price[1];
                    // dd($price);

                    if (!isset($price) || empty($price)) {
                        continue;
                    }
                    $price = intval($price);

                    // dd($_item[0]['id']);
                    $item = Items::find($link['id']);
                    if ($link['price'] != $price) {
                        $item->price = $price;

                        $item->updated_at = now();
                        $item->update();
                        $msg = 'precio actualizado';
                    } else {
                        $msg = 'precio igual';
                    }

                    $items[] = $item;
                    echo $j . '-' . $link['link'] . ' --> ' . $msg . ' OK <br> ';

                    echo $j . '-' . $link['link'] . ' --> OK <br> ';
                } catch (Exception $e) {
                    continue;
                } catch (ErrorException $e1) {
                    continue;
                }
            }
            //  }

            $j++;
            $i++;
        }

        dd($items);
    }

    function farmacenter_guardar_links()
    {
        $client = new Client();
        dd($client);

        // $puppeteer = new Puppeteer();

        // $client = new HttpBrowser(HttpClient::create());
        // $client = Client::createChromeClient();    // create a chrome client
        /* $browser = $puppeteer->launch();
                       $page = $browser->newPage();
                       $page->setDefaultNavigationTimeout(300000);
                       $page->goto("https://www.farmacenter.com.py/sitemap.xml");
                       $html = $page->content();


                       // $crawler = new Crawler($html);
                       $data = $page->evaluate(JsFunction::createWithBody('return document.documentElement.outerHTML'));
                         $page->close();
                       $crawler = new Crawler($data);
                     //  dd($crawler);*/
        // $sites=['']

        $crawler = $client->request(
            'GET',
            'https://www.farmacenter.com.py/sitemap.xml',
        );
        // dd($client->request('GET', 'https://www.google.com.py/search?q=seo')->getHeaders());

        $links = $crawler->filter('loc')->each(function ($node) {
            return $node->text();
        });
        dd($links);
        $i = 1;
        $d = [];

        foreach ($links as $v) {
            if ($i > 10) {
                if (!empty($v)) {
                    echo $v . '<br>';
                    $item              = new Sitemaps();
                    $item->business_id = 7;
                    $item->link        = $v;
                    $item->save();
                } else {
                    continue;
                }
            }

            $i++;
        }
    }

    // farmaoliva scrapper sitemas
    function oliva_guardar_links()
    {
        $client = new Client();
        // $client = new HttpBrowser(HttpClient::create());
        // $client = Client::createChromeClient();    // create a chrome client

        // $sites=['']
        $crawler = $client->request('GET', 'https://www.farmaoliva.com.py/sitemap.xml');
        // dd($client->request('GET', 'https://www.google.com.py/search?q=seo')->getHeaders());

        $links = $crawler->filter('loc')->each(function ($node) {
            return $node->text();
        });
        // dd(count($links));
        $i = 1;
        $d = [];
        // $puppeteer = new Puppeteer();

        foreach ($links as $value) {
            if (empty($value)) {
                continue;
            } else {
                $url              = new Sitemaps();
                $url->business_id = 11;
                $url->link        = $value;
                $url->save();

                echo $value . '<br>';
            }

            $i++;
        }
    }

    // farmaoliva scrapper sitemas
    function farmatotal_guardar_links()
    {
        // $client = new Client();
        $client = new HttpBrowser(HttpClient::create());
        // $client = Client::createChromeClient();    // create a chrome client

        // $sites=['']
        $crawler = $client->request('GET', 'http://localhost/catedral/farmatotal.xml');
        // dd($client->request('GET', 'https://www.google.com.py/search?q=seo')->getHeaders());
        // dd($crawler);
        $links = $crawler->filter('loc')->each(function ($node) {
            return $node->text();
        });
        // dd($links);
        $i = 1;
        $d = [];
        // $puppeteer = new Puppeteer();

        foreach ($links as $value) {
            if (empty($value)) {
                continue;
            } else {
                $url              = new Sitemaps();
                $url->business_id = 15;
                $url->link        = $value;
                $url->save();

                echo $value . '<br>';
            }

            $i++;
        }
    }

    /**
     * Display a listing of the resource.
     * tal
     * @return \Illuminate\Http\Response
     */
    function farmatotal_guardar_items()
    {
        //
        //
        set_time_limit(60000);
        $links = Sitemaps::where('business_id', '15')
            // ->where('link', 'like', '%col%')
            ->limit(1000)
            ->offset(22)
            ->get()
            ->toArray();

        $i      = 0;
        $j      = 2195;
        $items  = array();
        $client = new Client();
        //  dd($links);
        foreach ($links as $link) {
            if ($j > 2200) {
                if ($link['link'] == 'https://www.farmatotal.com.py') {
                    continue;
                } else {
                    try {
                        $crawler  = $client->request('GET', $link['link']);
                        $response = $client->getResponse();
                        //  dd($response);
                        if ($response->getStatusCode() == 404) {
                            continue;
                        }

                        // dd($crawler);
                        $codigo_barras = $crawler->filter('span[class="sku"]')->text();

                        // dd($codigo_barras);
                        if (!isset($codigo_barras) || empty($codigo_barras)) {
                            continue;
                        }
                        $codigo_barras = explode(' ', $codigo_barras);
                        $t             = count($codigo_barras) - 1;
                        $codigo_barras = substr($codigo_barras[$t], 2);
                        $price         = $crawler->filter('span[class="woocommerce-Price-amount amount"]')->eq(1)->text();
                        // dd($price);

                        // imagen
                        if (!$crawler->filter('img.wp-post-image')) {
                            dd($crawler);
                        }
                        $imagen = $crawler->filter('img[class="wp-post-image"]')->attr('src');
                        //  dd($imagen);
                        $price = explode('₲', $price);
                        // dd($price);
                        // $price = explode(' ', $price[1]);
                        $price = explode(' ', $price[1]);
                        // dd($price);
                        $price = substr($price[0], 2);
                        $price = explode('.', $price);
                        $price = $price[0] . $price[1];
                        // dd($price);

                        if (!isset($price) || empty($price)) {
                            continue;
                        }
                        $titulo = $crawler->filter('h1.product_title')->text();
                        // dd($titulo);
                        if (!isset($titulo) || empty($titulo)) {
                            continue;
                        }
                        $msg = '';
                        $_item = Items::where('business_id', '=', 15)
                            ->where('sku', '=', $codigo_barras)
                            ->get();
                        if (count($_item) == 0) {
                            /*
                             * $item = [
                             *     'business_id' => 15,
                             *     'title'       => $titulo,
                             *     'sku'         => $codigo_barras,
                             *     'link'        => $link['link'],
                             *     'price_now'   => $price,
                             *     'image'       => $imagen
                             * ];
                             * Items::create($item);
                             */
                            // dd($link['link']);
                            $this->farmatotal_guardar_item($link['link']);
                            $msg = 'creado';
                        } else {
                            // dd($_item[0]['id']);
                            $item            = Items::find($_item[0]['id']);
                            $item->title     = $titulo;
                            $item->price_now = $price;
                            $item->link      = $link['link'];
                            $item->image     = $imagen;
                            $item->update();
                            $msg = 'actualizado';
                        }

                        //    $items[] = $item;
                        echo $j . '-' . $link['link'] . ' --> ' . $msg . ' OK <br> ';

                        /*
                         * echo $j."-".$link['link']." --> OK <br> ";
                         * }
                         */
                    } catch (Exception $e) {
                        continue;
                    } catch (ErrorException $e1) {
                        continue;
                    }
                }
            }

            $j++;
            $i++;
        }

        // dd($items);
    }

    /**
     * Display a listing of the resource.
     * tal
     * @return \Illuminate\Http\Response
     */
    public function farmatotal_guardar_item($url)
    {
        $_url = '';
        $_cat = 1;
        $_sub = 1;
        if (is_array($url)) {
            $_url = $url['url'];
            if (array_key_exists('cat', $url)) {
                $_cat = $url['cat'];
            }
            if (array_key_exists('sub', $url)) {
                $_sub = $url['sub'];
            }
        } else {
            $_url = $url;
        }

         
        set_time_limit(500000);
        $links[]['link'] = $_url;

      
         // dd($links);
       
        // dd($client);
        foreach ($links as $link) {
            if ($link['link'] == 'https://www.farmatotal.com.py') {
                continue;
            } else {
               
                try {
                     $msg= '';
                    $existe = Sitemaps::where('link', '=', $link['link'])->get()->toArray();
                    if (!$existe) {
                        $_link              = new Sitemaps();
                        $_link->business_id = 15;
                        $_link->link        = $link['link'];
                        $_link->save();
                    }
                      $client = new Client();
                    $crawler  = $client->request('GET', $link['link']);
                    $response = $client->getResponse();
                    // dd($response);
                    if ($response->getStatusCode() == 404) {
                        continue;
                    }
                    
                    // dd($crawler);
                    $codigo_barras = $crawler->filter('span[class="sku"]')->text('0');

                   //  dd($codigo_barras);
                    if (!isset($codigo_barras) || empty($codigo_barras)) {
                        return ;
                    }
                    $codigo_barras = explode(' ', $codigo_barras);
                    $codigo_barras = $codigo_barras[0];
                    $codigo_barras = trim($codigo_barras);
                   //  dd($codigo_barras);
                    $price = $crawler->filter('p.price > ins > span')->eq(0)->text();
                    // dd($codigo_barras);

                     //dd($price);
                    if (!$crawler->filter('img.wp-post-image')) {
                        continue;
                    }
                    $imagen = $crawler->filter('img[class="wp-post-image"]')->attr('src');
                    //  dd($imagen);
                  //  dd($price);
                    $price = explode(':', $price);
                    //dd($price);
                    $price = explode(' ', $price[1]);
                        //dd($price);
                    $price= explode(' ',$price[1]);
                    $price= (string) $price[0];
                   //dd($price);
                   $price = substr(trim($price), 5);
                   $price = str_replace(".",'',$price);
                                      
                  $price = (int) $price;
               
                   // dd($price);

                    if (!isset($price) || empty($price)) {
                        continue;
                    }

                    $price_old = $crawler->filter('p.price > del > span')->eq(0)->text();
                    // dd($price_old);
                    $price_old = explode('₲', $price_old);
                    // dd($price);
                    $price_old = $price_old[1];
                    $price_old = explode(' ', $price_old);
                    $price_old = $price_old[0];

                    $price_old = str_replace('.', '', $price_old);
                    $price_old = str_replace(' ', '', $price_old);
                    $price_old = substr(trim($price_old),2);
                
                    if (empty($price_old)) {
                        continue;
                    }
                    $price_old = (int) $price_old;
                    // dd($price_old);

                    $price_off = $this->dame_porc_desc($price_old, $price);

                    $titulo = $crawler->filter('h1.product_title')->text();
                    // dd($titulo);
                    if (!isset($titulo) || empty($titulo)) {
                        continue;
                    }

                    $_item = Items::where('link', '=', $link['link'])->get()->toArray();
                    // dd();
                    if (count($_item) > 0) {
                        if (count($_item) > 1) {
                            $item = Items::find($_item[1]['id']);
                            $item->delete();
                        }
                        $item = Items::find($_item[0]['id']);
                     ; 
                        $item->price_now = $price;
                        $item->price_old = $price_old;
                        $item->price_off = $this->dame_porc_desc($price_old, $price);
                        $item->update();
                        $msg = ' fue actualizado con exito';
                         //echo  'el item <a href="' . $link['link'] . '">'.$titulo.' </a>   ' . $msg . ' <br> ';
                          
                    } else {
                        // dd($_item[0]['id']);
                        $item                 = new Items();
                        $item->sku            = $codigo_barras;
                        $item->business_id    = 15;
                        $item->title          = $titulo;
                        $item->price_now      = $price;
                        $item->price_old      = $price_old;
                        $item->price_off      = $this->dame_porc_desc($price_old, $price);
                        $item->link           = $link['link'];
                        $item->category_id    = $_cat;
                        $item->subcategory_id = $_sub;
                        $item->image          = $imagen;
                        $item->save();
                      
                        $msg = ' fue creado con exito';
                     
                          
                    }

                       echo  'el item <a href="' . $link['link'] . '">'.$titulo.' </a>   ' . $msg . ' <br> ';

                  

                    
                } catch (Exception $e) {
                    continue;
                } catch (ErrorException $e1) {
                    continue;
                }
            }
        }
    }

    function APIItemsListar()
    {
        // $data = DB::select('SELECT t1.title, t1.sku, t1.image, t1.category_id, t1.business_id, fn_dame_negocio_nombre(t1.business_id) AS business, t1.link, t1.price_now FROM items AS t1 ORDER BY  t1.price_now ASC, t1.title ASC');
        $data = DB::select('CALL pro_items_listar(500, 0, 0);');
        // dd($data);

        $result = [];
        foreach ($data as $node) {
            // code...
            $result[] = (array) $node;
        }

        $res = $this->groupArray($result, 'sku');

        //  dd($res);
        $final = [];

        $final = [];
        foreach ($res as $node) {
            //  $final[$i]['']
            $i = 0;

            foreach ($node['collections'] as $c) {
                if ($i == 0) {
                    $final[] = $c;
                }
                $i++;
            }
        }

        $order = $this->array_orderby($final, 'price_now', SORT_ASC, 'title', SORT_ASC);
        // dd($final);
        return $order;
    }

    // lista items por cat
    function APIItemsListarCat($cat, $sub, $limit)
    {
        // $data = DB::select('SELECT t1.title, t1.sku, t1.image, t1.category_id, t1.business_id, fn_dame_negocio_nombre(t1.business_id) AS business, t1.link, t1.price_now FROM items AS t1 ORDER BY  t1.price_now ASC, t1.title ASC');
        $data = DB::select('CALL pro_items_listar(' . $limit . ',' . $cat . ',' . $sub . ');');
        // dd($data);

        $result = [];
        foreach ($data as $node) {
            // code...
            $result[] = (array) $node;
        }

        $res = $this->groupArray($result, 'sku');

        //  dd($res);
        $final = [];

        $final = [];
        foreach ($res as $node) {
            //  $final[$i]['']
            $i = 0;

            foreach ($node['collections'] as $c) {
                if ($i == 0) {
                    $final[] = $c;
                }
                $i++;
            }
        }

        $order = $this->array_orderby($final, 'price_now', SORT_ASC, 'title', SORT_ASC);
        // dd($final);
        return $order;
    }

    function APIItemsVer($sku)
    {
        /* $items = DB::select("SELECT t1.title, t1.sku, t1.image, t1.business_id, fn_dame_negocio_nombre(t1.business_id) AS business, t1.link, t1.price_now FROM items AS t1 WHERE t1.sku='".$sku."' ");
        // dd($items);
         $data=[];
        /* foreach ($items as $item) {
             // code...
         }
         return $items*/
        // $items = DB::select("SELECT t1.title, t1.sku, t1.image, t1.category_id, fn_dame_categoria_nombre_x_id(t1.category_id) as category,t1.business_id, fn_dame_negocio_nombre(t1.business_id) AS business, t1.link, t1.price_now FROM items AS t1 WHERE t1.sku='" . $sku . "' ORDER BY t1.price_now ASC");
        $items = DB::select("CALL pro_items_ver('" . $sku . "')");
        // dd($items);
        $catedral    = [];
        $puntofarma  = [];
        $oliva       = [];
        $farmacenter = [];
        $farmatotal  = [];

        $header = [];
        $body   = [];
        $result = [];

        foreach ($items as $item) {
            switch ($item->business_id) {
                case '2':
                    $puntofarma['sku']       = $item->sku;
                    $puntofarma['business']  = $item->business;
                    $puntofarma['price_now'] = $item->price_now;
                    $puntofarma['link']      = $item->link;
                    $puntofarma['image']     = $item->image;
                    $puntofarma['title']     = $item->title;
                    $body[]                  = $puntofarma;
                    break;
                case '4':
                    // code...
                    $catedral['sku']       = $item->sku;
                    $catedral['business']  = $item->business;
                    $catedral['price_now'] = $item->price_now;
                    $catedral['link']      = $item->link;
                    $catedral['image']     = $item->image;
                    $catedral['title']     = $item->title;

                    $body[] = $catedral;
                    break;

                case '7':
                    $farmacenter['sku']       = $item->sku;
                    $farmacenter['business']  = $item->business;
                    $farmacenter['price_now'] = $item->price_now;
                    $farmacenter['link']      = $item->link;
                    $farmacenter['image']     = $item->image;
                    $farmacenter['title']     = $item->title;

                    $body[] = $farmacenter;
                    break;

                case '11':
                    // code..
                    $oliva['sku']       = $item->sku;
                    $oliva['business']  = $item->business;
                    $oliva['price_now'] = $item->price_now;
                    $oliva['link']      = $item->link;
                    $oliva['image']     = $item->image;
                    $oliva['title']     = $item->title;

                    $body[] = $oliva;
                    break;

                case '15':
                    $farmatotal['sku']       = $item->sku;
                    $farmatotal['business']  = $item->business;
                    $farmatotal['price_now'] = $item->price_now;
                    $farmatotal['link']      = $item->link;
                    $farmatotal['image']     = $item->image;
                    $farmatotal['title']     = $item->title;

                    $body[] = $farmatotal;

                    break;
            }
        }  // dd($body);
        // dd($items);
        $header['sku']   = $items[0]->sku;
        $header['title'] = $items[0]->title;
        $header['image'] = $items[0]->image;
        $keys            = array_column($body, 'price_now');
        array_multisort($keys, SORT_ASC, $body);
        $result['header'] = $header;
        $result['body']   = $body;
        // ($result);
        // dd($items);

        $order  = $this->array_orderby($body, 'price_now', SORT_ASC, 'title', SORT_DESC);
        $result = $this->groupArray($order, 'sku');
        //
        return $items;  // $result[0]['collections'];
    }


    function APIItemsDetalle($sku)
    {
        /* $items = DB::select("SELECT t1.title, t1.sku, t1.image, t1.business_id, fn_dame_negocio_nombre(t1.business_id) AS business, t1.link, t1.price_now FROM items AS t1 WHERE t1.sku='".$sku."' ");
        // dd($items);
         $data=[];
        /* foreach ($items as $item) {
             // code...
         }
         return $items*/
        // $items = DB::select("SELECT t1.title, t1.sku, t1.image, t1.category_id, fn_dame_categoria_nombre_x_id(t1.category_id) as category,t1.business_id, fn_dame_negocio_nombre(t1.business_id) AS business, t1.link, t1.price_now FROM items AS t1 WHERE t1.sku='" . $sku . "' ORDER BY t1.price_now ASC");
        $items = DB::select("CALL pro_items_ver('" . $sku . "')");
       // dd($items[0]);
        $data[] =$items[0];
        return $data;  // $result[0]['collections'];
    }

 function APIItemsRelacionados($sku) {
           $items = DB::select("CALL pro_items_listar_relacionados_x_categoria('" . $sku . "', '24');");
       // dd($items[0]);
      ;
        return $items; 
    }

    // listar
    public function web_items_listar()
    {
        $items = DB::select('CALL pro_items_listar(100,0,0);');
        // dd($items);
        $data = [];
        foreach ($items as $item) {
            // code...
            $data[] = (array) $item;
        }
        $res = $this->groupArray($data, 'sku');
        // dd($res);
        return $items;
    }

    // buscador
    public function web_items_buscar()
    {
        $q     = $_GET['q'];
        $items = DB::select("SELECT
            t1.sku AS sku,
    t1.category_id AS category_id,
    fn_dame_categoria_nombre_x_id(t1.category_id) AS category,
        t1.business_id AS business_id,
        fn_dame_negocio_nombre(t1.business_id) AS business,
        t1.title AS title,
        t1.image as image,
        t1.link AS link,
        t1.price_now as price
    FROM items AS t1
    where t1.title like concat('%','" . $q . "','%')  OR t1.sku='" . $q . "' order by t1.price_now ASC, t1.title DESC  limit 1000");
        // dd($items);
        $catedral    = [];
        $puntofarma  = [];
        $oliva       = [];
        $farmacenter = [];
        $farmatotal  = [];

        $header = [];
        $body   = [];
        $result = [];

        $data = [];
        foreach ($items as $item) {
            $data[] = (array) $item;

            /*switch ($item->business_id) {
                case '2':
                    $puntofarma['sku'] = $item->sku;
                    $puntofarma['business'] = $item->business;
                    $puntofarma['price'] = $item->price;
                    $puntofarma['link'] = $item->link;
                    $puntofarma['image'] = $item->image;
                    $puntofarma['title'] = $item->title;
                    $body[] = $puntofarma;
                    break;
                case '4':
                    // code...
                    $catedral['sku'] = $item->sku;
                    $catedral['business'] = $item->business;
                    $catedral['price'] = $item->price;
                    $catedral['link'] = $item->link;
                    $catedral['image'] = $item->image;
                    $catedral['title'] = $item->title;

                    $body[] = $catedral;
                    break;

                case '7':
                    $farmacenter['sku'] = $item->sku;
                    $farmacenter['business'] = $item->business;
                    $farmacenter['price'] = $item->price;
                    $farmacenter['link'] = $item->link;
                    $farmacenter['image'] = $item->image;
                    $farmacenter['title'] = $item->title;

                    $body[] = $farmacenter;
                    break;

                case '11':
                    // code..
                    $oliva['sku'] = $item->sku;
                    $oliva['business'] = $item->business;
                    $oliva['price'] = $item->price;
                    $oliva['link'] = $item->link;
                    $oliva['image'] = $item->image;
                    $oliva['title'] = $item->title;

                    $body[] = $oliva;
                    break;

                case '15':
                    $farmatotal['sku'] = $item->sku;
                    $farmatotal['business'] = $item->business;
                    $farmatotal['price'] = $item->price;
                    $farmatotal['link'] = $item->link;
                    $farmatotal['image'] = $item->image;
                    $farmatotal['title'] = $item->title;

                    $body[] = $farmatotal;

                    break;
            }*/
        }
        // $inter = array_intersect_assoc($puntofarma, $catedral, $oliva, $farmacenter, $farmatotal);
        $inter = $this->groupArray($data, 'sku');
        dd($data);
        // dd($items);
        $header['sku']   = $items[0]->sku;
        $header['title'] = $items[0]->title;
        $header['image'] = $items[0]->image;
        $keys            = array_column($body, 'price');
        array_multisort($keys, SORT_ASC, $body);
        $result['header'] = $header;
        $result['body']   = $body;
        // dd($result);
        $it   = [];
        $it[] = (array) $items;
        // dd($it);
        $it[] = $it[0];
        // dd($data);
        // $it=compact($it);
        $grupo = $this->groupArray($data, 'sku');

        // dd($grupo);
        return view('frontend.items.buscador', ['data' => $grupo]);
    }

    // listar
    public function api_items_listar()
    {
        $res = DB::select('SELECT
            distinct(t1.sku) AS sku,
    t1.category_id AS category_id,
    fn_dame_categoria_nombre_x_id(t1.category_id) AS category,
        t1.business_id AS business_id,
        fn_dame_negocio_nombre(t1.business_id) AS business,
        t1.title AS title,
        t1.link AS link,
        t1.image as image,
        t1.price_now as price
    FROM items AS t1
    where t1.category_id=2 And t1.business_id =4
    order by t1.price_now ASC, t1.title DESC
    limit 1000');
        return $res;
    }

    // buscador
    public function api_items_buscar()
    {
        $q = $_GET['q'];
        $c = 0;
        $l = 100;
        if (isset($_GET['c'])) {
            $c = $_GET['c'];
        }

        if (isset($_GET['l'])) {
            $l = $_GET['l'];
        }
        $res = DB::select("CALL pro_items_buscar('" . $q . "'," . $c . ',' . $l . ')');
        return $res;
    }

    function groupArray($array, $groupkey)
    {
        if (count($array) > 0) {
            $keys = array_keys($array[0]);

            //    $title = $array[0]['title'];
            //  $image = $array[0]['image'];
            // dd($title);
            $removekey = array_search($groupkey, $keys);
            if ($removekey === false)
                return array("Clave \"$groupkey\" no existe");
            else
                // unset($keys[$removekey]);
                $groupcriteria = array();
            $return = array();
            foreach ($array as $value) {
                $item = null;
                foreach ($keys as $key) {
                    $item[$key] = $value[$key];

                    // dd($item);
                }

                $busca = array_search($value[$groupkey], $groupcriteria);
                if ($busca === false) {
                    $groupcriteria[] = $value[$groupkey];
                    $return[]        = array($groupkey => $value[$groupkey], 'collections' => array());
                    $busca           = count($return) - 1;
                }

                $return[$busca]['collections'][] = $item;
                // $return[$busca]['title']                 = $item['title'];
            }
            return $return;
        } else
            return array();
    }

    // arr url items
    function web_items_add_url(Request $req)
    {
        $res = DB::select('SELECT t1.id As category_id, fn_dame_categoria_nombre_x_id(t1.id) as category FROM categories As t1');
        // dd($cats);
        $cats    = [];
        $cats[0] = 'Ninguna';
        foreach ($res as $cat) {
            // code...
            $cats[$cat->category_id] = $cat->category;
        }
        // dd($cats);
        return view('backend.items.add-url', ['categories' => $cats]);
    }

    // save items from url
    function web_items_save_url(Request $req)
    {
        $data = $req->all();
        // dd($data);
        $url         = $data['item_url'];
        $business_id = 0;
        if (str_contains($url, 'farmaciacatedral.com.py')) {
            $business_id = 4;
        } elseif (str_contains($url, 'farmaoliva.com.py')) {
            $business_id = 11;
        } elseif (str_contains($url, 'puntofarma.com.py')) {
            $business_id = 2;
        } elseif (str_contains($url, 'farmacenter.com.py')) {
            $business_id = 7;
        } elseif (str_contains($url, 'farmatotal.com.py')) {
            $business_id = 15;
        }
        $existe = Sitemaps::where('link', '=', $url)->get();
        if (!$existe) {
            $sitemap              = new Sitemaps();
            $sitemap->business_id = $business_id;
            $sitemap->link        = $url;
            $sitemap->save();
        }

        $msg         = '';
        $link['url'] = $data['item_url'];

        $link['cat'] = $data['category_id'];
        switch ($business_id) {
            case 2:
                // code...

                $msg = $this->puntofarma_guardar_item($url);
                break;

            case 4:
                // code...
                $msg = $this->catedral_guardar_item($url);
                break;
            case 7:
                // code...
                $msg = $this->farmacenter_guardar_item($url);
                break;
            case 11:
                // code...
                $msg = $this->oliva_guardar_item($url);
                break;
            case 15:
                // code...
                $msg = $this->farmatotal_guardar_item($url);
                break;
        }
        $res['msg'] = $msg;
        return $res;
    }

    // verify stock
    function ajax_items_verifify_url(Request $req)
    {
        $data       = $req->all();
        $url        = trim($data['url']);
        $link       = Sitemaps::where('link', '=', $url)->get();
        $item       = Items::where('link', '=', $url)->get();
        $res        = [];
        $res['msg'] = '';

        if (count($item) == 0) {
            $msg = 'No existe esta URL en la base de datos de Items';
        } else {
            $msg = 'Existe esta URL en la base de datos de Items';
        }

        if (count($link) == 0) {
            $msg .= ' y No existe esta URL en la base de datos de Sitemaps';
        } else {
            $msg .= ' y si Existe esta URL en la base de datos de Sitemaps';
        }

        $res['msg'] = $msg;

        return $res;
    }

    // viwq detail
    function web_items_details($sku)
    {
        $items       = DB::select("CALL pro_items_ver('" . $sku . "');");
        $catedral    = [];
        $puntofarma  = [];
        $oliva       = [];
        $farmacenter = [];
        $farmatotal  = [];

        $header = [];
        $body   = [];
        $result = [];

        $data = [];

        foreach ($items as $item) {
            $data[] = (array) $item;
        }
        // dd($data);
        $grupo = $this->groupArray($data, 'sku');
        // dd($grupo);
        return view('frontend.items.view', ['data' => $grupo]);
    }

    function web_items_comparativa($sku)
    {
        $items = DB::select("CALL pro_items_ver('" . $sku . "');");

        foreach ($items as $item) {
            $data[] = (array) $item;
        }
        // dd($data);
        $grupo = $this->groupArray($data, 'sku');
        // dd($grupo);
        return view('frontend.items.view', ['data' => $grupo]);
    }

    // add links from
    public function web_links_add_sitemap()
    {
        $res = DB::select('SELECT t1.id As business_id, t1.name as business FROM business As t1');
        // dd($cats);
        $bus = [];

        foreach ($res as $node) {
            // code...
            $bus[$node->business_id] = $node->business;
        }
        // dd($cats);
        return view('backend.links.add-sitemap', ['business' => $bus]);
    }
    // add links from

    public function web_links_save_sitemap(Request $req)
    {
        $data     = $req->all();
        $links    = [];
        $file     = $req->file('sitemap_file');
        $fileName = $file->getClientOriginalName();
        // Display File Name
        echo 'File Name: ' . $file->getClientOriginalName();
        echo '<br>';

        // Display File Extension
        echo 'File Extension: ' . $file->getClientOriginalExtension();
        echo '<br>';

        // Display File Real Path
        echo 'File Real Path: ' . $file->getRealPath();
        echo '<br>';

        // Display File Size
        echo 'File Size: ' . $file->getSize();
        echo '<br>';

        // Display File Mime Type
        echo 'File Mime Type: ' . $file->getMimeType();

        // Move Uploaded File
        $destinationPath = 'uploads';
        $file->move($destinationPath, $file->getClientOriginalName());

        echo $fileName . ' -- ' . $destinationPath . '<br>';
        $crawler = new Crawler(file_get_contents($destinationPath . '/' . $fileName));
        $links = $crawler->filter('loc')->each(function ($node) {
            return $node->text();
        });
        // dd($links);

        $i = 1;
        $d = [];

        foreach ($links as $v) {
            if ($i > 23) {
                if (!empty($v)) {
                    echo $v;
                    $item              = new Sitemaps();
                    $item->business_id = 7;
                    $item->link        = $v;
                    $item->save();
                    echo 'creado ..<br>';
                } else {
                    continue;
                }
            }

            $i++;
        }
    }

    function ellipse($text, $maxlen, $ellip = '...', $towords = TRUE)
    {
        // trim whitespace
        $text = trim($text);

        // do nothing if we're shorter than maxlen
        if (strlen($text) <= $maxlen) {
            return $text;
        }

        // if maxlen is less than the ellip symbol, make maxlen = length of ellip
        $maxlen = strlen($ellip) > $maxlen ? strlen($ellip) : $maxlen;

        // we're longer than maxlen. First thing we do is shorten to maxlen - $ellip
        $_text = substr($text, 0, $maxlen - strlen($ellip));

        if ($towords) {
            $_text = strrev($_text);
            // if we're matching to complete words we look for the last instance of a
            // sentence terminator
            $pattern = '/\s/';
            $count   = preg_match($pattern, $_text, $matches);
            $_text   = strrev(substr($_text, strpos($_text, $matches[0])));
            return $_text . $ellip;
        } else {
            // Rules
            // 1. If the last char in a shortened string is inside a just append the ellipsis, e.g. hello => hel...
            // 2. If the last char in a shortened string is a space, append the ellipsis after the space e.g. hello how => hello ...
            // 3. If the last char in a shortended string is the last letter in a word, remove an extra character from the string e.g. hello => hell...

            // we decide what to do here based on the last character of the shortened message
            // and the character which FOLLOWS the last character in the shortened message
            $last_char   = $text[$maxlen - strlen($ellip) - 1];
            $switch_char = $text[$maxlen - strlen($ellip)];

            // last character is a space or both are non-terminating characters
            $terminators = array('.', ',', '!', '?', '%');
            if (($last_char == ' ') || (!in_array($last_char, $terminators) && !in_array($switch_char, $terminators) && $switch_char != ' '))
                return $_text . $ellip;
            elseif (!in_array($last_char, $terminators) && (in_array($switch_char, $terminators) || $switch_char == ' '))
                return substr($_text, 0, strlen($_text) - 1) . $ellip;
            elseif (!in_array($last_char, $terminators) && !in_array($switch_char, $terminators) && $switch_char != ' ')
                return $_text . $ellip;
            else {
                // we get here if the last char and switch char are both terminators. e.g. '. '
                // in this situation we run ourselves again but with the characters trimmed off
                return ellipse($text, $maxlen - 1, $ellip, $towords);
            }
        }
    }

    // buscador ajax farmaatotal
    function farmatotal_buscar_items_ajax()
    {
        $q   = $_GET['q'];
        $url = 'https://www.farmatotal.com.py/core/modules/29aff22752/includes/Engines/TNTSearchMySQL/Endpoints/search.php?s=' . $q;
        $con = curl_init();

        curl_setopt($con, CURLOPT_URL, $url);
        curl_setopt($con, CURLOPT_RETURNTRANSFER, true);

        $res = curl_exec($con);
        curl_close($con);
        $data = [];
        $res  = json_decode($res);
        $data = (array) $res;
    //   dd($data);
        $total  = count($data['suggestions']);
        echo "<hr> Farmatotal: ".$total." items econtrados <hr>" ;
        $_data=[];
        foreach ($data['suggestions'] as $node) {
            if (property_exists($node, 'url')) {
                // echo $node->url."<br>";
                $l = $node->url;

                $c = 1;
                $s = 1;
                if (isset($_GET['c']) && !empty($_GET['c'])) {
                    $c = $_GET['c'];
                }
                if (isset($_GET['s']) && !empty($_GET['s'])) {
                    $s = $_GET['s'];
                }
                $_url        = [];
                $_url['url'] = $l;
                $_url['çat'] = $c;
                $_url['sub'] = $s;
               // $_data[]=$_url;
                 $this->farmatotal_guardar_item($_url);
            }

            //
        }
       echo "<hr>";
       //dd($_data);
        // dd($data['suggestions']);
        // return $data['suggestions'];
    }

    // buscador ajax farmaatotal
    function puntofarma_buscar_items_ajax()
    {
        $q                    = $_GET['q'];
        $url                  = 'https://dev.puntofarma.com.py:3089/api/productos/buscar?limit=5&buscador=true&q=' . $q;
        $con                  = curl_init();
        $_SERVER['HTTP_HOST'] = 'puntofarma.com.py';
        // dd($_SERVER);
        curl_setopt($con, CURLOPT_URL, $url);
        curl_setopt($con, CURLOPT_AUTOREFERER, true);
        curl_setopt($con, CURLOPT_CUSTOMREQUEST, 'OPTIONS');  // HTTP request is 'OPTIONS'
        curl_setopt($con, CURLOPT_HEADER, true);
        curl_setopt($con, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($con, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($con, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($con, CURLOPT_HTTPHEADER, array(
            'Origin: http://localhost/comparapp/public/puntofarma/buscar/items',
            'Pragma: no-cache',
            'Access-Control-Allow-Origin: http://localhost/comparapp/public/puntofarma/buscar/items',
            'Access-Control-Allow-Credentials: true',
            'Referer: http://localhost/comparapp/public/puntofarma/buscar/items',
            'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36'
        ));

        $res = curl_exec($con);
        curl_close($con);
        // dd($res);
        $data = [];
        $res  = json_decode($res);
        $data = (array) $res;
        foreach ($data['suggestions'] as $node) {
            if (property_exists($node, 'url')) {
                echo $node->url . '<br/>';
            }
            if (property_exists($node, 'sku')) {
                echo $node->sku . '<br/>';
            }
        }
        // dd($data['suggestions']);
        return $data->suggestions;
    }

    function farmacenter_buscar_items_ajax()
    {
        $q   = urldecode($_GET['q']);
        $url = 'https://www.farmacenter.com.py/ajax-buscar-productos?term=' . $q;
        //dd($url);
        $con = curl_init();

        curl_setopt($con, CURLOPT_URL, $url);
        curl_setopt($con, CURLOPT_RETURNTRANSFER, true);

        curl_setopt($con, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($con, CURLOPT_SSL_VERIFYPEER, false);
        $res = curl_exec($con);

        curl_close($con);
        $res = json_decode($res);
        $res = (array) $res;
         //dd($res);
        
        $items = [];
        foreach ($res as $node) {
            // code...
            $items[] = $node->data;
        }

        
       //  dd($items);
        $items = array_slice($items, 0, -1);
         //dd($items);
        $i = 0;
        $data  = array();
        foreach ($items as $node) {
            $c = 1;
            $s = 1;
            if (isset($_GET['c']) && !empty($_GET['c'])) {
                $c = $_GET['c'];
            }
            if (isset($_GET['s']) && !empty($_GET['s'])) {
                $s = $_GET['s'];
            }

            $sku='0';

            $l                          = 'https://www.farmacenter.com.py/' . $node->vinculo;
            if($this->exist_url($l)==false){
               continue;
            }
            $sku= $this->farmacenter_dame_sku($l);
            if($sku=='0'){
                continue;
            }
            $data[$i]['business_id']    = 7;
            $data[$i]['category_id']    = $c;
            $data[$i]['subcategory_id'] = $s;
            $data[$i]['title']          = $node->nombre;
            $data[$i]['sku']            = $sku;
            $data[$i]['link']           = $l;
            $data[$i]['image']          = $node->thumb;
            $data[$i]['price_now']      = $node->precio_lista;
            $data[$i]['price_old']      = $node->precio_fiel;
            $data[$i]['price_off']      = $this->dame_porc_desc($node->precio_lista, $node->precio_fiel);
            $i++;
           // dd($data);
        }

        //dd($data);
        $this->farmacenter_guardar_item_array($data);
    }

    // farmacenter guardar item array

    public function farmacenter_guardar_item_array($data)
    {
        $msg = '';

        if (!is_array($data)) {
            die('Debe proporcionar un Array');
        } else {
            echo 'Farmacenter: ' . count($data) . ' items encontrados<hr>';
            foreach ($data as $node) {

                $_link = Sitemaps::where('link', '=', $node['link'])
                    ->where('business_id', '=', 7)
                    ->get()
                    ->toArray();
                if (!$_link) {
                    $link              = new Sitemaps();
                    $link->link        = $node['link'];
                    $link->business_id = 7;
                    $link->save();
                    $msg = 'el Link <a href="' . $node['link'] . '" >' . $node['title'] . '</a> fue guardao entre los Sitemaps<br>';
                }
                $_item = Items::where('link', '=', $node['link'])
                    ->where('business_id', '=', 16)
                    ->get()
                    ->toArray();
                if (!$_item) {
                    Items::Create($node);
                    $msg = 'el Item <a href="' . $node['link'] . '" >' . $node['title'] . '</a> fue guardado entre los Items<br>';
                } else {
                    $item                 = Items::find($_item[0]['id']);
                    $item->category_id    = $node['category_id'];
                    $item->subcategory_id = $node['subcategory_id'];
                    $item->price_now      = $node['price_now'];
                    $item->price_now      = $node['price_now'];
                    $item->price_old      = $node['price_old'];
                    $item->price_off      = $node['price_off'];
                    $item->update();
                    $msg = 'el Item <a href="' . $node['link'] . '" >' . $node['title'] . '</a> fue actualizado entre los Items<br>';
                }
                echo $msg;
            }
        }
        echo '<hr>';
    }

    public function oliva_buscar_items_ajax()
    {
        $q   = $_GET['q'];
        $url = 'https://www.farmaoliva.com.py/ajax-buscar-productos?term=' . $q;

        $con = curl_init();

        curl_setopt($con, CURLOPT_URL, $url);
        curl_setopt($con, CURLOPT_RETURNTRANSFER, true);

        $res = curl_exec($con);
        curl_close($con);
        $data  = [];
        $res   = json_decode($res);
        $res   = (array) $res;
        $items = [];
        foreach ($res as $node) {
            // code...
            $items[] = $node->data;
        }
        $items = array_slice($items, 0, -1);
        //  dd($items);
        $i = 0;
        foreach ($items as $node) {
            $c = 1;
            $s = 1;
            if (isset($_GET['c']) && !empty($_GET['c'])) {
                $c = $_GET['c'];
            }
            if (isset($_GET['s']) && !empty($_GET['s'])) {
                $s = $_GET['s'];
            }
            $l                          = 'https://www.farmaoliva.com.py/' . $node->vinculo;
            if(!$this->exist_url($l)){
                continue;
            }
            $data[$i]['business_id']    = 7;
            $data[$i]['category_id']    = $c;
            $data[$i]['subcategory_id'] = $s;
            $data[$i]['title']          = $node->nombre;
            $data[$i]['sku']            = $this->oliva_dame_sku($l);
            $data[$i]['link']           = $l;
            $data[$i]['image']          = $node->imagenes->original;
            $data[$i]['price_now']      = $node->precio_lista;
            $data[$i]['price_old']      = $node->precio;
            $data[$i]['price_off']      = $this->dame_porc_desc($node->precio_lista, $node->precio);
            $i++;
        }

        $this->oliva_guardar_item_array($data);
    }

    public function oliva_guardar_item_array($data)
    {
        $msg = '';

        if (!is_array($data)) {
            die('Debe proporcionar un Array');
        } else {
            echo 'Farma Oliva: ' . count($data) . ' items encontrados<hr>';
            foreach ($data as $node) {
                $_link = Sitemaps::where('link', '=', $node['link'])
                    ->where('business_id', '=', 11)
                    ->get()
                    ->toArray();
                if (!$_link) {
                    $link              = new Sitemaps();
                    $link->link        = $node['link'];
                    $link->business_id = 11;
                    $link->save();
                    $msg = 'el Link <a href="' . $node['link'] . '" >' . $node['title'] . '</a> fue guardao entre los Sitemaps<br>';
                }
                $_item = Items::where('link', '=', $node['link'])
                    ->where('business_id', '=', 11)
                    ->get()
                    ->toArray();
                if (!$_item) {
                    Items::Create($node);
                    $msg = 'el Item <a href="' . $node['link'] . '" >' . $node['title'] . '</a> fue guardado entre los Items<br>';
                } else {
                    $item                 = Items::find($_item[0]['id']);
                    $item->business_id    = 11;
                    $item->category_id    = $node['category_id'];
                    $item->subcategory_id = $node['subcategory_id'];
                    $item->price_now      = $node['price_now'];
                    $item->price_now      = $node['price_now'];
                    $item->price_old      = $node['price_old'];
                    $item->price_off      = $node['price_off'];
                    $item->update();
                    $msg = 'el Item <a href="' . $node['link'] . '" >' . $node['title'] . '</a> fue actualizado entre los Items<br>';
                }
                echo $msg;
            }
        }
        echo '<hr>';
    }

    function dame_precio_desc($precio, $off)
    {
        //  precio - 100
        // off - x

        $x = $precio / (1 - ($off / 100));
        return $x;
    }

    function dame_porc_desc($precioOriginal, $precioActual)
    {
        if ($precioOriginal == 0) {
            return 0;  // Evitar división por cero
        }
        $descuento = (($precioOriginal - $precioActual) / $precioOriginal) * 100;
        return round($descuento, 0);
        // return $des // Redondeamos a dos decimales
    }

    function array_orderby()
    {
        $args = func_get_args();
        $data = array_shift($args);
        foreach ($args as $n => $field) {
            if (is_string($field)) {
                $tmp = array();
                foreach ($data as $key => $row)
                    $tmp[$key] = $row[$field];
                $args[$n] = $tmp;
            }
        }
        $args[] = &$data;
        call_user_func_array('array_multisort', $args);
        return array_pop($args);
    }

    // buscador ajax farmaatotal

    function biggie_buscar_items_ajax()
    {
        // Inicializa cURL
        $q   = $_GET['q'];
        $ch  = curl_init();
        $url = 'https://api.app.biggie.com.py/api/articles?query=' . $q . '&take=500&skip=0&classificationId=0&t=offer';
        // Configura las opciones de cURL
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Authorization: Bearer 249374|YyeR6JjlnemezUSI3tX7wyJMkfcrHrdpeM1GTCem',
            'Content-Type: application/json'
        ]);

        // Ejecuta la solicitud
        $response = curl_exec($ch);

        // Cierra la conexión
        curl_close($ch);

        // dd($response);
        $data = [];
        $data = json_decode($response);
        // dd($data);
        // echo $data['items'][0]->name;
        // echo $this->sanitizeString($data['items'][0][''])

        $res = [];
        $i   = 0;
        $c   = 1;
        $s   = 1;
        if (isset($_GET['c']) && !empty($_GET['c'])) {
            $c = $_GET['c'];
        }
        if (isset($_GET['s']) && !empty($_GET['s'])) {
            $s = $_GET['s'];
        }
        foreach ($data->items as $item) {
            $link = 'https://biggie.com.py/item/' . $this->sanitizeString($item->name . ' ' . $item->code);
            // $price = $item-?
            $price                  = $item->price;
            $res[$i]['business_id'] = 16;
            $res[$i]['link']        = $link;
            $res[$i]['title']       = $item->name;

            $res[$i]['price_now'] = $price;
            if (is_null($item->discountPercent)) {
                $res[$i]['price_old'] = $price;
                $res[$i]['price_off'] = 0;
            } else {
                $res[$i]['price_old'] = $this->dame_precio_desc($price, $item->discountPercent);
                $res[$i]['price_off'] = $item->discountPercent;
            }
            $res[$i]['sku']      = $item->code;
            $res[$i]['brand_id'] = $this->dame_marca_id_x_nombre($item->brand->name);

            $res[$i]['category_id'] = $c;

            $res[$i]['subcategory_id'] = $s;

            if (count($item->images) == 0) {
                $res[$i]['image'] = null;
            } else {
                // dd($item->images);
                $res[$i]['image'] = $item->images[0]->src;
            }

            $i++;
        }
        $this->biggie_guardar_item_array($res);
        // return response()->json(json_decode($response));
    }

    public function biggie_guardar_item_array($data)
    {
        $msg = '';

        if (!is_array($data)) {
            die('Debe proporcionar un Array');
        } else {
            echo 'Biggie Express: ' . count($data) . ' items encontrados<hr>';
            foreach ($data as $node) {
                $_link = Sitemaps::where('link', '=', $node['link'])
                    ->where('business_id', '=', 16)
                    ->get()
                    ->toArray();
                if (!$_link) {
                    $link              = new Sitemaps();
                    $link->link        = $node['link'];
                    $link->business_id = 16;
                    $link->save();
                    $msg = 'el Link <a href="' . $node['link'] . '" >' . $node['title'] . '</a> fue guardao entre los Sitemaps<br>';
                }
                $_item = Items::where('link', '=', $node['link'])
                    ->where('business_id', '=', 16)
                    ->get()
                    ->toArray();
                if (!$_item) {
                    Items::Create($node);
                    $msg = 'el Item <a href="' . $node['link'] . '" >' . $node['title'] . '</a> fue guardado entre los Items<br>';
                } else {
                    $item                 = Items::find($_item[0]['id']);
                    $item->category_id    = $node['category_id'];
                    $item->subcategory_id = $node['subcategory_id'];
                    $item->price_now      = $node['price_now'];
                    $item->price_now      = $node['price_now'];
                    $item->price_old      = $node['price_old'];
                    $item->price_off      = $node['price_off'];
                    $item->update();
                    $msg = 'el Item <a href="' . $node['link'] . '" >' . $node['title'] . '</a> fue actualizado entre los Items<br>';
                }
                echo $msg;
            }
        }
        echo '<hr>';
    }

    public function biggie_guardar_item()
    {
        $url       = 'https://biggie.com.py/item/p-7791293048000';
        $puppeteer = new Puppeteer([
            'read_timeout'=> 350,
            'idle_timeout'=> 350
        ]);

        $browser = $puppeteer->launch(
            ['headless'=> true ]
        );
        $page    = $browser->newPage();
        $page->setViewport([ 
            'width'=> 1200, 
            'height'=> 800,
            'deviceScaleFactor'=>  1,
            'isMobile'=> true 
          ]);
        $page->setDefaultNavigationTimeout(0);
        $page->goto($url);
        // $html = $page->content();

        // $crawler = new Crawler($html);
        $data = $page->evaluate(JsFunction::createWithBody('return document.documentElement.outerHTML'));

        $crawler = new Crawler($data);
        // dd($crawler);

        $titulo        = $crawler->filter('div.v-card__title > span')->text();
        $codigo_barras = $crawler->filter('div.v-card__subtitle > span')->text();

        // $page->close();
        echo $titulo;

        echo $codigo_barras;
    }

    function sanitizeString($string)
    {
        // Normalizar caracteres con tildes o especiales a su forma básica
        $string = iconv('UTF-8', 'ASCII//TRANSLIT', $string);

        // Eliminar cualquier carácter que no sea letra, número o espacio
        $string = preg_replace('/[^a-zA-Z0-9\s]/', '-', $string);

        // Reemplazar espacios y caracteres repetidos por un único guion
        $string = preg_replace('/[\s-]+/', '-', $string);

        // Convertir todo a minúsculas
        $string = strtolower($string);

        // Eliminar guiones del inicio y del final
        $string = trim($string, '-');

        return $string;
    }

    // Bearer 249374|YyeR6JjlnemezUSI3tX7wyJMkfcrHrdpeM1GTCem
    //
    public function superseis_buscar_items()
    {
        // Inicializa cURL
        $q = $_GET['q'];
        // global $c=1;

        $ch  = curl_init();
        $url = 'https://www.superseis.com.py/search.aspx?searchterms=' . $q;
        // Configura las opciones de cURL
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        /* curl_setopt($ch, CURLOPT_HTTPHEADER, [
             'Authorization: Bearer 249374|YyeR6JjlnemezUSI3tX7wyJMkfcrHrdpeM1GTCem',
             'Content-Type: application/json'
         ]);*/

        // Ejecuta la solicitud
        $response = curl_exec($ch);
        // Cierra la conexión
        curl_close($ch);
        $crawler = new Crawler($response);
        $results = $crawler->filter('div.product-item')->each(function ($node) {
            // return $node->html();

            $c = 1;
            $s = 1;
            if (isset($_GET['c']) && !empty($_GET['c'])) {
                $c = $_GET['c'];
            }
            if (isset($_GET['s']) && !empty($_GET['s'])) {
                $s = $_GET['s'];
            }
            $title = $node->filter('h2.product-title > a')->text();
            $link  = $node->filter('h2.product-title > a.product-title-link')->attr('href');

            $prices = $node->filter('div.prices > span')->each(function ($node) {
                return $node->text();
            });
            // dd($prices);
            if (count($prices) == 2) {
                $price    = $node->filter('span.productPrice > span.price-label')->text();
                $priceOld = $node->filter('span.oldproductPrice > span.price-label')->text();
            } else {
                $price    = $node->filter('span.productPrice > span.price-label')->text();
                $priceOld = $price;
            }

            // dd($priceOld);
            $image = $node->filter('div.picture > a.picture-link > img')->attr('src');
            // $brand = $node->filter('div.product-brand > a')->text();
            //           echo $brand."<br>";
            /* echo $image."<br>";
          echo $title."<br>";
          echo $link."<br>";
          echo $price."<br>";
          echo $priceOld."<br>"; */
            $price    = str_replace('.', '', $price);
            $priceOld = str_replace('.', '', $priceOld);
            $sku      = $this->superseis_dame_sku($link);
            $this->superseis_guardar_item_full($sku, $title, $image, $price, $priceOld, $link, $c, $s);
            echo '<hr>';
        });

        /*
         * $title = $results->filter('h2.product-title > a')->text();
         *             $link = $results->filter('h2.product-title > a.product-title-link')->attr('href');
         *         $price = $results->filter('span.productPrice > span.price-label')->text();
         * $priceOld = $results->filter('span.productPrice > span.price-label')->text();
         * $image = $results->filter('div.picture > a.picture-link > img')->attr('src');
         */
    }

    public function superseis_guardar_item_full($sku, $title, $image, $price_now, $price_old, $linkie, $cat, $sub)
    {
        $msg = '';
        // verificamos que tenemos ese link de su sitemap
        $_link = Sitemaps::where('link', '=', $linkie)->where('business_id', '=', 17)->get()->toArray();
        // si  lo tenemos
        // dd($_link);
        if ($_link && !is_null($_link)) {
            // dd($_link);
            //  dd($_link);
            $link              = Sitemaps::find($_link[0]['id']);
            $link->business_id = 17;
            $link->link        = $linkie;
            $link->update();
            $msg = 'el link ' . $link . ' fue actualizado Sitemaps <br>';
            // sino   lio creamos
        } else {
            $link              = new Sitemaps();
            $link->business_id = 17;
            $link->link        = $linkie;
            $link->save();
            $msg = 'el link ' . $link . ' fue creado dentro de Sitemaps<br>';
        }

        // verifuicamos que tenemos ese item
        $_item = Items::where('link', '=', $link)->where('business_id', '=', 17)->get()->toArray();
        if ($_item) {
            $item                 = Items::findOrFail($_item[0]['id']);
            $item->business_id    = 17;
            $item->category_id    = $cat;
            $item->subcategory_id = $sub;
            $item->link           = $linkie;
            $item->image          = $image;
            $item->sku            = $sku;
            $item->title          = $title;
            $item->price_now      = $price_now;
            $item->price_old      = $price_old;
            $item->price_off      = $this->dame_porc_desc($price_old, $price_now);
            $item->update();
            $msg = ' el item  <a href="' . $link . '">' . $title . '</a> fue actualizado dentro de Items <br>';
        } else {
            $item                 = new Items();
            $item->business_id    = 17;
            $item->link           = $linkie;
            $item->title          = $title;
            $item->category_id    = $cat;
            $item->subcategory_id = $sub;
            $item->image          = $image;
            $item->sku            = $sku;
            $item->price_now      = $price_now;
            $item->price_old      = $price_old;
            $item->price_off      = $this->dame_porc_desc($price_old, $price_now);
            $item->save();
            $msg = ' el item  <a href="' . $link . '">' . $title . '</a> fue creado dentro de Items <br>';
        }

        echo $msg;
    }

    public function superseis_dame_sku($link)
    {
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $link);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        /* curl_setopt($ch, CURLOPT_HTTPHEADER, [
             'Authorization: Bearer 249374|YyeR6JjlnemezUSI3tX7wyJMkfcrHrdpeM1GTCem',
             'Content-Type: application/json'
         ]);*/

        // Ejecuta la solicitud
        $response = curl_exec($ch);
        $crawler  = new Crawler($response);
        $sku      = $crawler->filter('div.sku')->text();
        $sku      = explode(':', $sku);
        $sku      = $sku[1];

        return trim($sku);
    }

    // stock
    // Bearer 249374|YyeR6JjlnemezUSI3tX7wyJMkfcrHrdpeM1GTCem
    //
    public function stock_buscar_items()
    {
        // Inicializa cURL
        $q = $_GET['q'];
        // global $c=1;

        $ch  = curl_init();
        $url = 'https://www.stock.com.py/search.aspx?searchterms=' . $q;
        // Configura las opciones de cURL
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        /* curl_setopt($ch, CURLOPT_HTTPHEADER, [
             'Authorization: Bearer 249374|YyeR6JjlnemezUSI3tX7wyJMkfcrHrdpeM1GTCem',
             'Content-Type: application/json'
         ]);*/

        // Ejecuta la solicitud
        $response = curl_exec($ch);
        // Cierra la conexión
        curl_close($ch);

        $crawler = new Crawler($response);
        $results = $crawler->filter('div.product-item')->each(function ($node) {
            // return $node->html();

            $c = 1;
            $s = 1;
            if (isset($_GET['c']) && !empty($_GET['c'])) {
                $c = $_GET['c'];
            }
            if (isset($_GET['s']) && !empty($_GET['s'])) {
                $s = $_GET['s'];
            }
            $title = $node->filter('h2.product-title > a')->text();
            $link  = $node->filter('h2.product-title > a.product-title-link')->attr('href');
            // dd($link);
            $prices = $node->filter('div.prices > span')->each(function ($node) {
                return $node->text();
            });
            // dd($prices);
            if (count($prices) == 2) {
                $price    = $node->filter('span.productPrice > span.price-label')->text();
                $priceOld = $node->filter('span.oldproductPrice > span.price-label')->text();
            } else {
                $price    = $node->filter('span.productPrice > span.price-label')->text();
                $priceOld = $price;
            }

            // dd($priceOld);
            $image = $node->filter('div.picture > a.picture-link > img')->attr('src');

            $price    = str_replace('.', '', $price);
            $priceOld = str_replace('.', '', $priceOld);
            $sku      = $this->stock_dame_sku($link);
            $this->stock_guardar_item_full($sku, $title, $image, $price, $priceOld, $link, $c, $s);
            echo '<hr>';
        });
    }

    public function stock_guardar_item_full($sku, $title, $image, $price_now, $price_old, $linkie, $cat, $sub)
    {
        $msg = '';
        // verificamos que tenemos ese link de su sitemap
        $_link = Sitemaps::where('link', '=', $linkie)->where('business_id', '=', 18)->get()->toArray();
        // si  lo tenemos
        // dd($_link);
        if ($_link && !is_null($_link)) {
            // dd($_link);
            //  dd($_link);
            $link              = Sitemaps::find($_link[0]['id']);
            $link->business_id = 18;
            $link->link        = $linkie;
            $link->update();
            $msg = 'el link ' . $link . ' fue actualizado Sitemaps <br>';
            // sino   lio creamos
        } else {
            $link              = new Sitemaps();
            $link->business_id = 18;
            $link->link        = $linkie;
            $link->save();
            $msg = 'el link ' . $link . ' fue creado dentro de Sitemaps<br>';
        }

        // verifuicamos que tenemos ese item
        $_item = Items::where('link', '=', $link)->where('business_id', '=', 18)->get()->toArray();
        if ($_item) {
            $item                 = Items::findOrFail($_item[0]['id']);
            $item->business_id    = 18;
            $item->category_id    = $cat;
            $item->subcategory_id = $sub;
            $item->link           = $linkie;
            $item->image          = $image;
            $item->sku            = $sku;
            $item->title          = $title;
            $item->price_now      = $price_now;
            $item->price_old      = $price_old;
            $item->price_off      = $this->dame_porc_desc($price_old, $price_now);
            $item->update();
            $msg = ' el item  <a href="' . $link . '">' . $title . '</a> fue actualizado dentro de Items <br>';
        } else {
            $item                 = new Items();
            $item->business_id    = 18;
            $item->link           = $linkie;
            $item->title          = $title;
            $item->category_id    = $cat;
            $item->subcategory_id = $sub;
            $item->image          = $image;
            $item->sku            = $sku;
            $item->price_now      = $price_now;
            $item->price_old      = $price_old;
            $item->price_off      = $this->dame_porc_desc($price_old, $price_now);
            $item->save();
            $msg = ' el item  <a href="' . $link . '">' . $title . '</a> fue creado dentro de Items <br>';
        }

        echo $msg;
    }

    public function stock_dame_sku($link)
    {
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $link);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        // Ejecuta la solicitud
        $response = curl_exec($ch);
        $crawler  = new Crawler($response);
        $sku      = $crawler->filter('div.sku')->text();
        $sku      = explode(':', $sku);
        $sku      = $sku[1];

        return trim($sku);
    }

    // farmacenter dame sku
    public function oliva_dame_sku($link)
    {
        $ch = curl_init();
        // echo $link;
        curl_setopt($ch, CURLOPT_URL, $link);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($ch);

        $crawler  = new Crawler($response);
        $sku      = $crawler->filter('span[id="producto-codigo"]')->text();
        // dd($sku);
        return trim($sku);
    }

    public function farmacenter_dame_sku($link)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $link);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        
        $response = curl_exec($ch);
        $sku = '0';
        $info = curl_getinfo($ch);
        if($info['http_code']==200){

            $crawler  = new Crawler($response);
              
            $sku      = $crawler->filter('span.sku')->text();

        }
        
        return trim($sku);
    }

    // catedral dame sku
    public function catedral_dame_sku($link)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $link);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($ch);
        $crawler  = new Crawler($response);
        $sku      = $crawler->filter('p.barra-ficha')->text();
        $sku      = explode(':', $sku);
        $sku      = $sku[1];
        return trim($sku);
    }

    // catedral dame marca
    public function catedral_dame_marca($link)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $link);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($ch);
        $crawler  = new Crawler($response);
        $brand    = $crawler->filter('a.title-marca')->text('0');
        $brand_id = (int) $this->dame_marca_id_x_nombre($brand);
        return $brand_id;
    }

    // funcion para sabere el id de la marca por el nombre
    public function dame_marca_id_x_nombre($brand)
    {
        $res = DB::select("select fn_dame_marca_id_x_nombre('" . $brand . "') as brand_id");
        if ($res && is_array($res)) {
            $res = $res[0];
            return $res->brand_id;
        } else {
            return 1;
        }
    }

    // casarica buscar
    public function casarica_buscar_items_ajax()
    {
        $q   = $_GET['q'];
        $url = 'https://www.casarica.com.py/ajax-buscar-productos?term=' . $q;

        $con = curl_init();

        curl_setopt($con, CURLOPT_URL, $url);
        curl_setopt($con, CURLOPT_RETURNTRANSFER, true);

        $res = curl_exec($con);
        curl_close($con);
        $data = [];
        $res  = json_decode($res);
        $res  = (array) $res;
        // dd($res);
        $items = [];
        foreach ($res as $node) {
            // code...
            $items[] = $node->data;
        }
        // dd($items);
        $items = array_slice($items, 0, -1);
        //  dd($items);
        $i = 0;
        foreach ($items as $node) {
            $c = 1;
            $s = 1;
            if (isset($_GET['c']) && !empty($_GET['c'])) {
                $c = $_GET['c'];
            }
            if (isset($_GET['s']) && !empty($_GET['s'])) {
                $s = $_GET['s'];
            }
            $l      = 'https://www.casarica.com.py/' . $node->vinculo;
            $prices = $this->casarica_dame_precios($l);
            // if(count($prices)>1){
            //  dd($prices);
            // }
            $priceNow = 0;
            $priceOld = 0;
            $priceOff = 0;
            if (count($prices) == 3) {
                $priceNow = $prices[0];
                $priceOld = $prices[2];
                $priceOff = $this->dame_porc_desc($priceOld, $priceNow);
            } else if (count($prices) == 1) {
                $priceNow = $prices[0];
                $priceOld = $priceNow;
            }
            $data[$i]['business_id']    = 19;
            $data[$i]['category_id']    = $c;
            $data[$i]['subcategory_id'] = $s;
            $data[$i]['title']          = $node->nombre;
            $data[$i]['sku']            = $this->casarica_dame_sku($l);
            $data[$i]['link']           = $l;
            $data[$i]['image']          = $node->thumb;
            $data[$i]['price_now']      = $priceNow;
            $data[$i]['price_old']      = $priceOld;
            $data[$i]['price_off']      = $priceOff;
            $i++;
        }
        // dd($data);
        $this->casarica_guardar_item_array($data);
    }

    public function casarica_dame_precios($link)
    {
        $ch = curl_init();
        // echo $link;
        curl_setopt($ch, CURLOPT_URL, $link);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($ch);
        $crawler = new Crawler($response);
        $price = $crawler->filter('p.price span')->each(function ($n) {
            $r = explode(' ', $n->text());
            $r = str_ireplace('.', '', $r[1]);
            return $r;
        });

        // dd($price);
        return $price;
    }

    public function casarica_dame_sku($link)
    {
        $ch = curl_init();
        // echo $link;
        curl_setopt($ch, CURLOPT_URL, $link);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($ch);
        $crawler  = new Crawler($response);
        $sku      = $crawler->filter('span[id="producto-codigo"]')->text();
        // dd($sku);
        return trim($sku);
    }

    // casarica rica guardar item array
    public function casarica_guardar_item_array($data)
    {
        $msg = '';

        if (!is_array($data)) {
            die('Debe proporcionar un Array');
        } else {
            echo 'Casa Rica: ' . count($data) . ' items encontrados<hr>';
            foreach ($data as $node) {
                $_link = Sitemaps::where('link', '=', $node['link'])
                    ->where('business_id', '=', 19)
                    ->get()
                    ->toArray();
                if (!$_link) {
                    $link              = new Sitemaps();
                    $link->link        = $node['link'];
                    $link->business_id = 19;
                    $link->save();
                    $msg = 'el Link <a href="' . $node['link'] . '" >' . $node['title'] . '</a> fue guardao entre los Sitemaps<br>';
                }
                $_item = Items::where('link', '=', $node['link'])
                    ->where('business_id', '=', 19)
                    ->get()
                    ->toArray();
                if (!$_item) {
                    Items::Create($node);
                    $msg = 'el Item <a href="' . $node['link'] . '" >' . $node['title'] . '</a> fue guardado entre los Items<br>';
                } else {
                    $item                 = Items::find($_item[0]['id']);
                    $item->business_id    = 19;
                    $item->category_id    = $node['category_id'];
                    $item->subcategory_id = $node['subcategory_id'];
                    $item->price_now      = $node['price_now'];
                    $item->price_now      = $node['price_now'];
                    $item->price_old      = $node['price_old'];
                    $item->price_off      = $node['price_off'];
                    $item->update();
                    $msg = 'el Item <a href="' . $node['link'] . '" >' . $node['title'] . '</a> fue actualizado entre los Items<br>';
                }
                echo $msg;
            }
        }
        echo '<hr>';
    }

    //fvs buscar

    function fvs_buscar_items_ajax()
    {
        $q   = $_GET['q'];
        $url = 'https://www.fvs.com.py/buscar?term=' . $q.'&ajax=true';

        $con = curl_init();

        curl_setopt($con, CURLOPT_URL, $url);
        curl_setopt($con, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($con, CURLOPT_HTTPHEADER, ['Content-Type: application/json', 'X-Requested-With: XMLHttpRequest']);

        $res = curl_exec($con);
        $info = curl_getinfo($con);
        curl_close($con);

        //dd($res);
        $data = array();
        // die($res);
        $res = json_decode($res);
         dd($res);
          $i = 0;
        foreach ($res as $n) {
        
            if (isset($n->data)) {


              
               
                    $c = 1;
                    $s = 1;
                    if (isset($_GET['c']) && !empty($_GET['c'])) {
                        $c = $_GET['c'];
                    }
                    if (isset($_GET['s']) && !empty($_GET['s'])) {
                        $s = $_GET['s'];
                    }
                    //dd($n->data->url);
                    $json = $this->fvs_ldjson_scrap($n->data->url);
                    $price =  $json->offers->price;
                    $price = (int) $price;
                    $priceOld = (int) $this->fvs_dame_precio_old($n->data->url);
                    if($priceOld=='0'){
                      $priceOld = $price;
                      $priceOff  =0;
                    }else{
                       $priceOff = $this->dame_porc_desc($price, $priceOld);    
                     
                    }
                       // $this->fvs_dame_precios('https://www.fvs.com.py/p/sedal-trat-cap-300-ml-nutre-8071');
                    
                    
                   // dd($n->data);


                    $data[$i]['title']          = $n->data->name;
                    $data[$i]['business_id']    = 13;
                    $data[$i]['brand_id'] = $this->dame_marca_id_x_nombre($json->brand->name);
                    $data[$i]['category_id']    = $c;
                    $data[$i]['subcategory_id'] = $s;
                    $data[$i]['image']          = $json->image;
                    $data[$i]['price_now']      = $price;
                    $data[$i]['price_old']      = $priceOld;
                    $data[$i]['price_off']      = $priceOff;
                    $data[$i]['link']           = $n->data->url;
                    $data[$i]['sku']            = $json->sku;

                 //   dd($data);
                    $i++;
               
            }
        }
        $this->fvs_guardar_item_array($data);
    }
 
    function fvs_buscar_items()
    {
        $q   = $_GET['q'];
        $q = urldecode($q);
        $url = 'https://www.fvs.com.py/buscar?q=' . $q;

        $con = curl_init();

        curl_setopt($con, CURLOPT_URL, $url);
        curl_setopt($con, CURLOPT_RETURNTRANSFER, true);
       //curl_setopt($con, CURLOPT_HTTPHEADER, ['Content-Type: application/json', 'X-Requested-With: XMLHttpRequest']);

        $res = curl_exec($con);
        $info = curl_getinfo($con);
        curl_close($con);

       //die($res);
        $data = array();

      $crawler = new Crawler($res);

      $productos=$crawler->filter('div[class="border rounded-4 box-producto d-none d-md-block"]')->each(function($n){
          $html  = $n->html();
           return $html;

      });

     

      
      
         dd($productos);
        $res = json_decode($res);
        // dd($res);
          $i = 0;
        foreach ($res as $n) {
        
            if (isset($n->data)) {


              
               
                    $c = 1;
                    $s = 1;
                    if (isset($_GET['c']) && !empty($_GET['c'])) {
                        $c = $_GET['c'];
                    }
                    if (isset($_GET['s']) && !empty($_GET['s'])) {
                        $s = $_GET['s'];
                    }
                    //dd($n->data->url);
                    $json = $this->fvs_ldjson_scrap($n->data->url);
                    $price =  $json->offers->price;
                    $price = (int) $price;
                    $priceOld = (int) $this->fvs_dame_precio_old($n->data->url);
                    if($priceOld=='0'){
                      $priceOld = $price;
                      $priceOff  =0;
                    }else{
                       $priceOff = $this->dame_porc_desc($price, $priceOld);    
                     
                    }
                       // $this->fvs_dame_precios('https://www.fvs.com.py/p/sedal-trat-cap-300-ml-nutre-8071');
                    
                    
                   // dd($n->data);


                    $data[$i]['title']          = $n->data->name;
                    $data[$i]['business_id']    = 13;
                    $data[$i]['brand_id'] = $this->dame_marca_id_x_nombre($json->brand->name);
                    $data[$i]['category_id']    = $c;
                    $data[$i]['subcategory_id'] = $s;
                    $data[$i]['image']          = $json->image;
                    $data[$i]['price_now']      = $price;
                    $data[$i]['price_old']      = $priceOld;
                    $data[$i]['price_off']      = $priceOff;
                    $data[$i]['link']           = $n->data->url;
                    $data[$i]['sku']            = $json->sku;

                 //   dd($data);
                    $i++;
               
            }
        }
        $this->fvs_guardar_item_array($data);
    } 

    public function fvs_dame_precio_old($url){
        
        $con = curl_init();
        curl_setopt($con, CURLOPT_URL, $url);
        curl_setopt($con, CURLOPT_RETURNTRANSFER, true);
      //  curl_setopt($con, CURLOPT_HTTPHEADER, ['Content-Type: application/json', 'X-Requested-With: XMLHttpRequest']);

        $res = curl_exec($con);
        $info = curl_getinfo($con);
        curl_close($con);

       

             $crawler = new Crawler($res);

            
             $priceNow = $crawler->filter('span.precio-producto')->text('0');
             $priceOld = $crawler->filter('span.text-decoration-line-through')->text('0');
             return $priceOld;
           
        


        

    }


    //fvs guardar
     public function fvs_guardar_item_array($data)
    {
        $msg = '';

        if (!is_array($data)) {
            die('Debe proporcionar un Array');
        } else {
            echo 'Farmacia Vicente Scavonne:  ' . count($data) . ' items encontrados<hr>';
            foreach ($data as $node) {
                $_link = Sitemaps::where('link', '=', $node['link'])
                    ->where('business_id', '=', 13)
                    ->get()
                    ->toArray();
                if (!$_link) {
                    $link              = new Sitemaps();
                    $link->country_id=1;
                    $link->link        = $node['link'];
                    $link->business_id = 13;
                    $link->save();
                    $msg = 'el Link <a href="' . $node['link'] . '" >' . $node['title'] . '</a> fue guardao entre los Sitemaps<br>';
                }

                $_item = Items::where('link', '=', $node['link'])
                    ->where('business_id', '=', 13)
                    ->get()
                    ->toArray();
                if (!$_item) {
                    Items::Create($node);
                    $msg = 'el Item <a href="' . $node['link'] . '" >' . $node['title'] . '</a> fue guardado entre los Items<br>';
                } else {
                    $item = Items::find($_item[0]['id']);
                    $item->country_id=1;
                    $item->business_id    = 13;
                    $item->brand_id       = $node['brand_id'];
                    $item->category_id    = $node['category_id'];
                    $item->subcategory_id = $node['subcategory_id'];
                    $item->price_now      = $node['price_now'];
                    $item->price_now      = $node['price_now'];
                    $item->price_old      = $node['price_old'];
                    $item->price_off      = $node['price_off'];
                    $item->update();
                    $msg = 'el Item <a href="' . $node['link'] . '" >' . $node['title'] . '</a> fue actualizado entre los Items<br>';
                }
                echo $msg;
            }
        }
    }


    public function catedral_dame_precios($link){

        $ch = curl_init();
        curl_setopt(CURLOPT_URL, $link);
        curl_setopt(CURLOPT_RETURNTRANSFER, true);
        $res = curl_exec($ch);
        curl_close($ch);


        
    }

    public function fvs_ldjson_scrap()
    {
        $url = 'https://www.fvs.com.py/p/sedal-trat-cap-300-ml-nutre-8071';
        $con = curl_init();

        curl_setopt($con, CURLOPT_URL, $url);
        curl_setopt($con, CURLOPT_RETURNTRANSFER, true);
        // curl_setopt($con, CURLOPT_HTTPHEADER, ['Content-Type: application/json','X-Requested-With: XMLHttpRequest']);

        $res = curl_exec($con);
        curl_close($con);
        $crawler = new Crawler($res);
        $jsonLdElements = $crawler->filter('script[type="application/ld+json"]')->each(function ($node) {
            return $node->text();
        });

        //  $element = json_decode($jsonLdElements);

        $jsonLd = $crawler->filter('script[type="application/ld+json"]')->each(function ($node) {
            return [
                'property' => 'script',
                'name'     => 'jsonLd',
                'content'  => $node->text(),
            ];
        });
           
        $data = json_decode($jsonLd[0]['content']);
       // dd($data);
        return json_decode($jsonLd[0]['content']);
    }

    // arete supermercados
    public function arete_guardar_links()
    {
        $url = 'https://www.arete.com.py/sitemap.xml';
        $con = curl_init();

        curl_setopt($con, CURLOPT_URL, $url);
        curl_setopt($con, CURLOPT_RETURNTRANSFER, true);
        $res = curl_exec($con);
        curl_close($con);
        $crawler = new Crawler($res);

        $links = $crawler->filter('loc')->each(function ($node) {
            return $node->text();
        });
        $i = 1;

        echo 'Arete Supermercados: ' . count($links) . ' links encontrados..<hr>';
        foreach ($links as $value) {
            if (empty($value)) {
                continue;
            } else {
                $url              = new Sitemaps();
                $url->business_id = 20;
                $url->link        = $value;
                $url->save();
                echo 'Link <a href="' . $value . '">' . $value . '</a><br>';
            }

            $i++;
        }
        echo '<hr>';
    }

    public function arete_buscar_items_ajax()
    {
        $q   = $_GET['q'];
        $url = 'https://www.arete.com.py/ajax-buscar-productos?term=' . $q;

        $con = curl_init();

        curl_setopt($con, CURLOPT_URL, $url);
        curl_setopt($con, CURLOPT_RETURNTRANSFER, true);

        $res = curl_exec($con);
        curl_close($con);
        $data = [];
        $res  = json_decode($res);
        $res  = (array) $res;
        // dd($res);
        $items = [];
        foreach ($res as $node) {
            // code...
            $items[] = $node->data;
        }
        // dd($items);
        $items = array_slice($items, 0, -1);
        //  dd($items);
        $i = 0;
        foreach ($items as $node) {
            $c = 1;
            $s = 1;
            if (isset($_GET['c']) && !empty($_GET['c'])) {
                $c = $_GET['c'];
            }
            if (isset($_GET['s']) && !empty($_GET['s'])) {
                $s = $_GET['s'];
            }
            $l      = 'https://www.arete.com.py/' . $node->vinculo;
            $prices = $this->casarica_dame_precios($l);
            // if(count($prices)>1){
            //  dd($prices);
            // }
            $priceNow = 0;
            $priceOld = 0;
            $priceOff = 0;
            if (count($prices) == 3) {
                $priceNow = $prices[0];
                $priceOld = $prices[2];
                $priceOff = $this->dame_porc_desc($priceOld, $priceNow);
            } else if (count($prices) == 1) {
                $priceNow = $prices[0];
                $priceOld = $priceNow;
            }
            $data[$i]['business_id']    = 20;
            $data[$i]['category_id']    = $c;
            $data[$i]['subcategory_id'] = $s;
            $data[$i]['title']          = $node->nombre;
            $data[$i]['sku']            = substr($node->imagen, 0, -4);
            $data[$i]['link']           = $l;
            $data[$i]['image']          = $node->thumb;
            $data[$i]['price_now']      = $priceNow;
            $data[$i]['price_old']      = $priceOld;
            $data[$i]['price_off']      = $priceOff;
            $i++;
        }
        // dd($data);
        $this->arete_guardar_item_array($data);
    }

    // arete guardar item array

    public function arete_guardar_item_array($data)
    {
        $msg = '';

        if (!is_array($data)) {
            die('Debe proporcionar un Array');
        } else {
            echo 'Arete Supermercados:  ' . count($data) . ' items encontrados<hr>';
            foreach ($data as $node) {
                $_link = Sitemaps::where('link', '=', $node['link'])
                    ->where('business_id', '=', 20)
                    ->get()
                    ->toArray();
                if (!$_link) {
                    $link              = new Sitemaps();
                    $link->link        = $node['link'];
                    $link->business_id = 20;
                    $link->save();
                    $msg = 'el Link <a href="' . $node['link'] . '" >' . $node['title'] . '</a> fue guardao entre los Sitemaps<br>';
                }

                $_item = Items::where('link', '=', $node['link'])
                    ->where('business_id', '=', 4)
                    ->get()
                    ->toArray();
                if (!$_item) {
                    Items::Create($node);
                    $msg = 'el Item <a href="' . $node['link'] . '" >' . $node['title'] . '</a> fue guardado entre los Items<br>';
                } else {
                    $item                 = Items::find($_item[0]['id']);
                    $item->business_id    = 20;
                    $item->category_id    = $node['category_id'];
                    $item->subcategory_id = $node['subcategory_id'];
                    $item->price_now      = $node['price_now'];
                    $item->price_now      = $node['price_now'];
                    $item->price_old      = $node['price_old'];
                    $item->price_off      = $node['price_off'];
                    $item->update();
                    $msg = 'el Item <a href="' . $node['link'] . '" >' . $node['title'] . '</a> fue actualizado entre los Items<br>';
                }
                echo $msg;
            }
        }
        echo '<hr>';
    }

    // arete dame precios

    public function arete_dame_precios()
    {
        $link = 'https://arete.com.py/pantene-acond-liso-extremo-200-ml-p32415';
        $ch   = curl_init();
        // echo $link;
        curl_setopt($ch, CURLOPT_URL, $link);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($ch);
        $crawler = new Crawler($response);
        $price = $crawler->filter('p.price span')->each(function ($n) {
            $r = explode(' ', $n->text());
            $r = str_ireplace('.', '', $r[1]);
            return $r;
        });

        dd($price);
        return $price;
    }

    // Salenma
    function salenma_buscar_items_ajax()
    {
        $q   = $_GET['q'];
        $url = 'https://www.salemmaonline.com.py/buscar?q=' . $q;
        // echo "<a href='" . $url . "'>" . $url . '</a><br>';
        $con = curl_init();

        curl_setopt($con, CURLOPT_URL, $url);
        curl_setopt($con, CURLOPT_RETURNTRANSFER, true);

        $res = curl_exec($con);
        curl_close($con);

        $crawler = new Crawler($res);

        $items = $crawler->filter('div.divproduct')->each(function ($p) {
            try {
                $price = $p->filter('h6.pprice')->text('0');

                $price = explode(' ', $price);

                $price = str_replace('.', '', $price[1]);
                $off   = $p->filter('label.limit-desc-t')->text('0');
                return [
                    'image'     => $p->filter('img.imgprodts')->attr('src'),
                    'brand'     => $p->filter('h6.ptitle')->text(),
                    'title'     => $p->filter('h6.psubtitle')->text(),
                    'price_now' => (int) $price,
                    'price_off' => (int) $off,
                    'link'      => $p->filter('a.apsubtitle')->attr('href')
                ];
            } catch (InvalidArgumentException $e1) {
            }
        });
        $data = [];
        $i    = 0;
        foreach ($items as $n) {
            $c = 1;
            $s = 1;
            if (isset($_GET['c']) && !empty($_GET['c'])) {
                $c = $_GET['c'];
            }
            if (isset($_GET['s']) && !empty($_GET['s'])) {
                $s = $_GET['s'];
            }
            $data[$i]['business_id'] = 21;

            $data[$i]['category_id']    = $c;
            $data[$i]['subcategory_id'] = $s;
            $data[$i]['title']          = $n['title'];
            $data[$i]['sku']            = $this->salemma_dame_sku($n['link']);
            $data[$i]['link']           = $n['link'];
            $data[$i]['image']          = $n['image'];
            $data[$i]['price_now']      = $n['price_now'];
            $data[$i]['brand_id']       = $this->dame_marca_id_x_nombre($n['brand']);
            if ($n['price_off'] > 0) {
                $data[$i]['price_old'] = $this->dame_precio_desc($n['price_now'], $n['price_off']);
                $data[$i]['price_off'] = $n['price_off'];
            } else {
                $data[$i]['price_old'] = $n['price_now'];
                $data[$i]['price_off'] = 0;
            }
            $i++;
        }
        $this->salemma_guardar_item_array($data);
    }

    // salemma traer datos codigo de barra precio desc marca
    public function salemma_dame_sku($url)
    {
        $con = curl_init();

        curl_setopt($con, CURLOPT_URL, $url);
        curl_setopt($con, CURLOPT_RETURNTRANSFER, true);

        $res = curl_exec($con);
        curl_close($con);

        $crawler = new Crawler($res);
        $sku     = $crawler->filter('p.pricedetails-off')->eq(0)->text();
        $sku     = explode(':', $sku);
        return trim($sku[1]);
    }

    public function salemma_dame_sku_demo()
    {
        $con = curl_init();
        $url = 'https://www.salemmaonline.com.py/producto/jab-tocador-blanco-x-135g';
        curl_setopt($con, CURLOPT_URL, $url);
        curl_setopt($con, CURLOPT_RETURNTRANSFER, true);

        $res = curl_exec($con);
        curl_close($con);

        $crawler = new Crawler($res);
        $sku     = $crawler->filter('p.pricedetails-off')->eq(0)->text();
        $sku     = explode(':', $sku);
        return trim($sku[1]);
    }

    // Salemma guaradr item arra
    public function salemma_guardar_item_array($data)
    {
        $msg = '';

        if (!is_array($data)) {
            die('Debe proporcionar un Array');
        } else {
            echo 'Salemma Online:  ' . count($data) . ' items encontrados<hr>';
            foreach ($data as $node) {
                $_link = Sitemaps::where('link', '=', $node['link'])
                    ->where('business_id', '=', 21)
                    ->get()
                    ->toArray();
                if (!$_link) {
                    $link              = new Sitemaps();
                    $link->link        = $node['link'];
                    $link->business_id = 21;
                    $link->save();
                    $msg = 'el Link <a href="' . $node['link'] . '" >' . $node['title'] . '</a> fue guardao entre los Sitemaps<br>';
                }

                $_item = Items::where('link', '=', $node['link'])
                    ->where('business_id', '=', 21)
                    ->get()
                    ->toArray();
                if (!$_item) {
                    Items::Create($node);
                    $msg = 'el Item <a href="' . $node['link'] . '" >' . $node['title'] . '</a> fue guardado entre los Items<br>';
                } else {
                    $item                 = Items::find($_item[0]['id']);
                    $item->business_id    = 21;
                    $item->category_id    = $node['category_id'];
                    $item->subcategory_id = $node['subcategory_id'];
                    $item->price_now      = $node['price_now'];
                    $item->price_now      = $node['price_now'];
                    $item->price_old      = $node['price_old'];
                    $item->price_off      = $node['price_off'];
                    $item->update();
                    $msg = 'el Item <a href="' . $node['link'] . '" >' . $node['title'] . '</a> fue actualizado entre los Items<br>';
                }
                echo $msg;
            }
        }
        echo '<hr>';
    }

    // buscador global
    public function web_buscador_global()
    {
        set_time_limit(600000);
        $q = '';
        $c = 1;
        $s = 1;
        if (!isset($_GET['q']) || empty($_GET['q'])) {
            die('debe proporcionar un terminao de busqueda');
        } else {
            $q = urldecode($_GET['q']);
        }
        if (isset($_GET['c']) && !empty($_GET['c'])) {
            $c = $_GET['c'];
        }
        if (isset($_GET['s']) && !empty($_GET['s'])) {
            $s = $_GET['s'];
        }
        $url = [
            'http://localhost/ahorrala/public/superseis/buscar/items?q=' . $q . '&c=' . $c . '&s=' . $s,
            'http://localhost/ahorrala/public/stock/buscar/items?q=' . $q . '&c=' . $c . '&s=' . $s,
            'http://localhost/ahorrala/public/casarica/buscar/items?q=' . $q . '&c=' . $c . '&s=' . $s,
            'http://localhost/ahorrala/public/biggie/buscar/items?q=' . $q . '&c=' . $c . '&s=' . $s,
            'http://localhost/ahorrala/public/salemma/buscar/items?q=' . $q . '&c=' . $c . '&s=' . $s,
            'http://localhost/ahorrala/public/arete/buscar/items?q=' . $q . '&c=' . $c . '&s=' . $s,
            'http://localhost/ahorrala/public/farmatotal/buscar/items?q=' . $q . '&c=' . $c . '&s=' . $s,
            'http://localhost/ahorrala/public/oliva/buscar/items?q=' . $q . '&c=' . $c . '&s=' . $s,
            'http://localhost/ahorrala/public/farmacenter/buscar/items?q=' . $q . '&c=' . $c . '&s=' . $s,
            'http://localhost/ahorrala/public/catedral/buscar/items?q=' . $q . '&c=' . $c . '&s=' . $s,
            'http://localhost/ahorrala/public/puntofarma/buscar/items?q=' . $q . '&c=' . $c . '&s=' . $s,
        ];
        echo '<b>Ahorrala.com - Buscador Global </b> <br>';
        echo "Buscando '" . $q . "' en " . count($url) . ' negocios..  <hr>';
        foreach ($url as $link) {
            echo '<a href="' . $link . '">' . $link . ' </a><br>';

            $con = curl_init();

            curl_setopt($con, CURLOPT_URL, $link);
            curl_setopt($con, CURLOPT_RETURNTRANSFER, true);

            $res = curl_exec($con);
            // dd($res);
            curl_close($con);
            echo $res;
        }
    }



    public function global_dame_precios($link){
        $url = "";




    }




    //buscador global automatico

    public function web_global_buscador_array(){
        $data=[];
        $data[3]=['dove','rexona','sedal', 'rexona','clear','axe','8x4','colgate','kolinos','closeup','pantene','sedal','shampoo', 'acondicionador','anticaspa','antitranspirante','toalla humeda','gel intimo','jabon','nosotras','kotex','algabo','intimo','prestobarba','after shave','afeitar'];
        //$data[4]=['antoniodove','rexona','sedal', 'rexona','clear','axe','8x4','colgate','kolinos','closeup','pantene','sedal','shampoo', 'acondicionador','anticaspa','antitranspirante','toalla humeda','gel intimo','jabon','nosotras','kotex','algabo','intimo','prestobarba','after shave','afeitar'];

//dd($data);

        $link = "http://localhost/ahorrala/public/global/buscador";
            foreach ($data as $key => $val) {
                // code...
                //echo $key."<br>";
;                if(is_array($val)){

                    foreach ($val as $n) {
                        $link.="?q=".$n."&c=".$key;
                        echo $link;
                    $ch = curl_init();
                      curl_setopt($ch, CURLOPT_URL, $link);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

            $res = curl_exec($ch);
            // dd($res);
            curl_close($ch);
            echo $res;       // code...
                    
                    }   
                    

                }



            }
        dd($data); 

    } 

    //playstore buscador
   
    public function playstore_buscador(){

        $query = $_GET['q'];
        $query = urlencode($query);
        //scraping mtodos malditos tags de google play store
        $list ='div[class="ULeU3b"]';
        $img = 'img.T75of';
        $descriptionDetalle = 'div.bARER';
        $valoracion = 'span.w2kbF';
        $appname = 'span.DdYX5';
        $link = '.Si6A0c';
        $apporg = '.wMUdtb';
        $download  = 'div.ClM7O';
        $options['app_name']=$appname;
        $options['app_image']=$img;
        $options['app_org']=$apporg;
        $options['app_link']=$link;
        $options['app_rate']=$valoracion;
        $options['app_download']=$download;
        $options['app_description']=$descriptionDetalle;
        $client = new Client();
        $crawler = $client->request('GET', 'https://play.google.com/store/search?q='.$query.'&c=apps&hl=es');
        $data=[];
        $i=0;
        $l=-1;
            //recorremos los resultados de la busqiedad
         $crawler->filter($list)->each(function ($node) use (&$l,&$i, &$data, &$options){
           // dd($node->text());
//print_r($options);

            if($i>1){
             
                //obtenemos el link de los resultados de busqueda
                $node->filter($options['app_link'])->each(function ($n) use(&$l,&$data) 
                {
                    $res=$n->attr('href');
                    $data[$l]['app_link']= 'https://play.google.com'.$res;

                });
                 //obtenemos el link de los resultados de busqueda
                 $node->filter($options['app_name'])->each(function ($n) use(&$l,&$data) {

                    $data[$l]['app_name']= $n->text();

                });
                 //obtenemos el nomnre la orgacion que nhace la app o nombre del apquete en adnroid
                $node->filter($options['app_org'])->each(function ($n) use(&$l,&$data) {

                    $data[$l]['app_org']= $n->text();

                });
                //obtenemos la calificacion
                $node->filter($options['app_rate'])->each(function ($n) use(&$l,&$data) {
                    //dd($n->text('0'));
                    $data[$l]['app_rate']= $n->text('0');

                });
                //ontenemos la imag
                $node->filter($options['app_image'])->each(function ($n) use(&$l,&$data) {

                    $data[$l]['app_image']= $n->attr('src');

                });
                $l++;
             }
            $i++;
           /* $node->filter($list)->each(function ($node) use (&$i, $data){

            });*/
        });
         ///ahora a obtener la descripcion y rate y downloads de estas app
        $j=0;

        foreach($data as $d){
           // dd($d['app_link']);
            //filtra a cada uno de la lista
        $crawler2 = $client->request('GET', $d['app_link']."&hl=es");

        $k=0;
        $crawler2->filter($options['app_description'])->each(function ($node) use (&$j, &$data, &$options){
          // dd($node->text());
           //echo $node->text();





            $data[$j]['app_description']= $node->text();




//$data[$j]['app_downlod']=$node->text();
        });
       $appdownload = $crawler2->filter($options['app_download'])->each(function ($node) use (&$j, &$data, &$options){
            //dd($node->text());
             //echo $node->text();





              return $node->text('0');




  //$data[$j]['app_downlod']=$node->text();
          });
      // dd(sizeof($appdownload));
       if(sizeof($appdownload)>2){

         $data[$j]['app_download']=$appdownload[1];
//dd('hace esto '.$appdownload[1]);
       }else{
         $data[$j]['app_download']=$appdownload[0];
      //   dd($j.' o hace esto '.$appdownload[0]);
       }


        $j++;
        }
       // return $data;
      // dd($data);
        return view('backend.search_result',['data'=>$data]);
    }


    public function drogueriaalamedasur_guardar_links(){

      
        $url = 'http://localhost/catedral/otro.xml';
        
            $con = curl_init();
        curl_setopt($con, CURLOPT_URL, $url);
        curl_setopt($con, CURLOPT_RETURNTRANSFER, true);
        $res = curl_exec($con);
        curl_close($con);
      //  dd($res);
        $crawler = new Crawler($res);
        
        $links = $crawler->filter('loc')->each(function ($node) {
            return $node->text();
        });
        $i = 1;
      //dd($links);
        echo 'Drogueria Alameda Sur: ' . count($links) . ' links encontrados..<hr>';
        foreach ($links as $value) {
            if (empty($value)) {
                continue;
            } else {
                $url              = new Sitemaps();
                $url->business_id = 22;
                $url->link        = $value;
                $url->save();
                echo 'Link <a href="' . $value . '">' . $value . '</a><br>';
               
            }

            $i++;
        }
        echo '<hr>';
    


  }

  //guardar items
    public function drogueriaalamedasur_guardar_items(){
        $links = Sitemaps::where('business_id','=',22)->get()->toArray();
       // dd($links);
        foreach($links as $node){
                
             echo $this->drogueriaalamedasur_guardar_item($node['link']);
        }
    }

//guardar item droguera alamada sur

    public function drogueriaalamedasur_guardar_item($url){

      
       // $url = $link;
      //  $url = "https://drogueriaalamedasur.co/tienda/cuidado-personal/cuidado-capilar/tratamiento-dove-x-1tabletas/";
        $con = curl_init();
        curl_setopt($con, CURLOPT_URL, $url);
        curl_setopt($con, CURLOPT_RETURNTRANSFER, true);
        $res = curl_exec($con);
        curl_close($con);
        
        $crawler = new Crawler($res);
        
        $sku = $crawler->filter('span.sku')->text('0');
        $price = $crawler->filter('p.price')->text();
        $price = explode("$",$price);
        $title = $crawler->filter('h1.product_title')->text();
        $price = $price[1];
     
        $price = str_replace(",","",$price);
        $price = (int) $price; 
        $priceOld =  (int) $price;
        $priceOff = 0; 
        $image = $crawler->filter('figure img')->attr('src');
       
        $_item = Items::where('business_id','=',22)
                      ->where('link','=',$url)
                       ->where('country_id','=',5)
                      ->get()
                      ->toArray();
        if($_item){
            $item = Items::find($_item[0]['id']);
            $item->price_now= $price;
            $item->price_old =$priceOld;
            $item ->price_off=$priceOff;
            echo "Item <a href='".$url."'>".$title."</a> actualizado con exito entre los items";
        }else{
            $item = new Items();
            $item->price_now= $price;
            $item->price_old =$priceOld;
            $item ->price_off=$priceOff;
            $item->title = $title;
            $item->image = $image;
            $item->business_id=22;
            $item->country_id=5;
            $item->save();
            echo "Item <a href='".$url."'>".$title."</a> creado con exito entre los items";
        }

        echo '<hr>';
    


  }


    public function exist_url($link){

        $ret = false;
        $con = curl_init();
        curl_setopt($con, CURLOPT_URL, $link);
        curl_setopt($con, CURLOPT_RETURNTRANSFER, true );
        curl_setopt($con, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($con, CURLOPT_SSL_VERIFYHOST, 0);
        curl_exec($con);
        $info = curl_getinfo($con);
        curl_close($con);
        if($info['http_code']==200){
            $ret = true;
        }
        return $ret ;

       
       

    }


    public function dame_categoria_id_x_nombre(){


    }

}
