<?php

namespace App\Http\Controllers;

use App\Models\Items;
use App\Models\Products;
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;

class ProductsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function catedral_guardar_items()
    {
        //
        //
        // Capturamos el tiempo de inicio

        set_time_limit(5000000);
        $tiempoInicio = microtime(true);
        $links = Items::where('business_id', '=', 4)->skip(1193)->limit(218)->get();
        // dd($links);
        $i = 1;
        $j=1;
        $items = array();
        $client = new Client(HttpClient::create(['timeout' => 180]));

        $test = [];
        $msg = '';
        $_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']);
                    // 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();

                        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);
                            $test['sku'] = $codigo_barras;
                            $price_old = $crawler->filter('h5.precio-antes')->text();
                            if (!isset($price_old) || empty($price_old)) {
                                continue;
                            }
                            $price_old = explode(' ', $price_old);

                            $price_old = $price_old[1];
                            $price_old = str_replace('.', '', $price_old);
                            $test['old'] = str_replace('.', '', $price_old);

                            // PRECIO ACTUAL
                            $price_now = $crawler->filter('h5.precio-ahora')->text();

                            if (!isset($price_now) || empty($price_now)) {
                                continue;
                            }
                            $price_now = explode(' ', $price_now);

                            $price_now = $price_now[1];
                            $price_now = str_replace('.', '', $price_now);
                            $test['now'] = $price_now;

                            // DESC
                            $price_off = $crawler->filter('h5.precio-desc')->text();
                            $price_off = str_replace('% OFF', '', $price_off);
                            $test['off'] = $price_off;
                            // dd($test);

                            // 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 = Products::where('business_id', '=', 4)
                                ->where('sku', '=', $codigo_barras)
                                ->get();
                            if (count($_item) == 0) {
                                $item = new Products();
                                $item->business_id = 4;
                                $item->title = $titulo;
                                $item->sku = $codigo_barras;
                                $item->image = $imagen;
                                $item->link = $link['link'];
                                $item->price_now = $price_now;
                                $item->price_old = $price_old;
                                $item->price_off = $price_off;
                                $item->save();
                                $_msg = 'creado ';
                            } else {
                                // dd($_item[0]['id']);
                                $item = Products::find($_item[0]['id']);
                                $item->title = $titulo;
                                $item->image = $imagen;
                                $item->price_now = $price_now;
                                $item->price_old = $price_old;
                                $item->price_off = $price_off;
                                $item->updated_at = now();
                                $item->link = $link['link'];
                                $item->update();
                                $_msg = 'actualizado ';
                            }
                        }
                    }
                } catch (Exception $e) {
                    continue;
                } catch (InvalidArgumentException $e1) {
                    continue;
                }
            }
            $items[] = $item;
            $msg.= 'orden: ' . $j . ' - sku:  ' . $codigo_barras . ' - link: <a target="_blank" href="' . $link['link'] . '">' . $titulo . '</a> --> ' . $_msg . ' OK <br> ';

            $j++;
            $i++;
        }
        $tiempoFin = microtime(true);
        // Calculamos la resta
        $tiempoEjecucion = $tiempoFin - $tiempoInicio;

        echo 'Tiempo de ejecución: ' . date('i \minutos y s \seguntos',$tiempoEjecucion) . ' segundos <br>';
        echo 'Total Productos: ' . $i  . '<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;
                            }
                            // dd($imagen);

                            $item = new Items();
                            $item->business_id = 4;
                            $item->title = $titulo;
                            $item->sku = $codigo_barras;
                            $item->image = $imagen;
                            $item->link = $link['link'];
                            $item->price = $price;
                            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++;
            return $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)
            ->skip(642)
            ->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);
    }
}
