<?php

use App\Article;
use App\Artnim;
use App\Author;
use App\Authornimaia;
use App\Clientegm;
use App\Clientegmdest;
use App\Gm_product;
use App\Http\Controllers\TestPaoController;
use App\Newproduct;
use App\Order;
use App\Orderdetail;
use App\Setting;
use App\Statusproduct;
use App\Stock;
use App\WP_post;
use Carbon\Carbon;
use Illuminate\Support\Facades\Route;
use Codexshaper\WooCommerce\Facades\WooCommerce;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
use Illuminate\Support\Facades\DB;

use Codexshaper\WooCommerce\Facades\Product;
use Codexshaper\WooCommerce\Facades\Attribute;
use Codexshaper\WooCommerce\Facades\Category;
use Codexshaper\WooCommerce\Facades\Customer;
use Codexshaper\WooCommerce\Facades\Order as FacadesOrder;
use Codexshaper\WooCommerce\Facades\Term;
use Codexshaper\WooCommerce\Facades\Variation;
use Codexshaper\WooCommerce\Facades\Webhook;
use Codexshaper\WooCommerce\Models\Product as ModelsProduct;
use Illuminate\Http\Request;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;

Route::get('/', function () {
    return view('welcome');
});

Route::get('/getsku/{sku}', function ($sku) {
    $product = Product::where('sku', $sku)->first();
    /*
$data = [
    'regular_price' => '11.00'
];

$product = Variation::update($product['parent_id'], $product['id'], $data);
*/
    dd($product);
    /*
if($product->count() > 0) {
    echo "trovato";

} else {
    echo "non trovato";
}*/
});

Route::get('/updatesku', function () {
    $productsku = Product::where('sku', '15')->first();
    $autori[] = "Pino Pallo";
    $autori[] = "Sempronio";
    $data = [

        'name' => 'Libro 3',
        'type' => 'simple',
        'regular_price' => '10.00',
        'description' => 'Simple product full description.',
        'short_description' => 'Simple product short description.',


        'attributes' => [

            [
                'id' => 1,
                'visible' => true,

                'options' =>
                $autori


            ]
        ],


        'meta_data' => [
            [
                'key' => 'pagine',
                'value' => '60'
            ]
        ]

    ];

    $product = Product::update($productsku['id'], $data);
});

Route::get('/getid/{id}', function ($id) {



    $product = Product::find($id);

    /*
    $attributes = $product['meta_data'];
    foreach ($attributes as  $key => $value){
        if($value->key == 'isbn'){
            dd($value->value);
        }
    }*/
    //if($product['description'] == '')
    //echo 'vuota';
    dd($product);
    //dd(count($product['images']));
    //$found_key = array_search('Versione', array_column($product['attributes'], 'name'));
    //dd($product['attributes'][$found_key]->option);
    //dd($product['attributes'][6]->option);
    //$found_key = array_search('edizione', array_column($product['meta_data'], 'key'));
    //dd($product['meta_data'][$found_key]->value);

});

Route::get('/getattr', function () {
    $attribute_id = 1;
    $attribute = Attribute::find($attribute_id);
    dd($attribute);
});
Route::get('/getautori', function () {
    $attribute_id = 1;
    $page = 1;
    $terms = Term::all($attribute_id);
    dd($terms);

    $all_terms = new Collection();
    do {

        $terms = Term::all($attribute_id, $options = ['per_page' => 100, 'page' => $page]);

        //$filtered = $products->where('type');

        $all_terms = $all_terms->merge($terms);
        $page++;
    } while ($terms->count() > 0);
    $autore = $all_terms->where('name', 'Alano Shoemaker');
    if ($autore->count() > 0) {
        dd($autore);
    } else {
        echo "nulla";
    }
});
Route::get('/getterms', function () {
    $attribute_id = 1;
    $page = 1;
    $terms = Term::all($attribute_id, $options = ['search' => 'Pinco Pallo Pollo']);
    dd($terms);

    $all_terms = new Collection();
    do {

        $terms = Term::all($attribute_id, $options = ['per_page' => 100, 'page' => $page]);

        //$filtered = $products->where('type');

        $all_terms = $all_terms->merge($terms);
        $page++;
    } while ($terms->count() > 0);
    $autore = $all_terms->where('name', 'Alano Shoemaker');
    if ($autore->count() > 0) {
        dd($autore);
    } else {
        echo "nulla";
    }
});
Route::get('/getterm', function () {
    $attribute_id = 1;
    $terms = Term::all($attribute_id, $options = ['search' => 'Pinco Pallo']);
    //$terms = Term::where('name','=','Pinco Pallo Pollo')->first();
    //dd($terms);
    foreach ($terms as $term) {
        echo $term->id . "<br>";
    }
});



Route::get('/articolo/{id}', function ($id) {

    $articles = Article::join(DB::raw('(SELECT IdArticolo, MAX(DataOra) AS data FROM T_WEB_Articoli GROUP BY IdArticolo) b'), function ($join) {
        $join->on('T_WEB_Articoli.IdArticolo', '=', 'b.IdArticolo')
            ->on('T_WEB_Articoli.DataOra', '=', 'b.data');
    })->where('T_WEB_Articoli.IdArticolo', $id)->get();
    //$articolo = Article::find($id);
    //$article = Article::where('IdArticolo',)->whereDate('DataOra',$articolo->data)->first();
    dd($articles);
    //dd($articles[0]->authors);


});

Route::get('/articoli/{id}', function ($id) {

    $articles = Article::where('IdArticolo', $id)
        ->leftJoin(DB::raw('(SELECT e.IdStatoProdotto, e.Descrizione as DescrizioneStatoProdotto FROM T_WEB_StatiProdotto e JOIN (SELECT IdStatoProdotto, MAX(DataOra) as data1 from T_WEB_StatiProdotto GROUP BY IdStatoProdotto) c ON e.IdStatoProdotto = c.IdStatoProdotto AND e.DataOra = c.data1 ) f'), function ($join) {
            $join->on('T_WEB_Articoli.IdStatoProdotto', '=', 'f.IdStatoProdotto');
        })
        ->leftJoin(DB::raw('(SELECT g.IdArgomento, g.Descrizione as DescrizioneArgomentoProdotto FROM T_WEB_Argomenti g JOIN (SELECT IdArgomento, MAX(DataOra) as data1 from T_WEB_Argomenti GROUP BY IdArgomento) h ON g.IdArgomento = h.IdArgomento AND g.DataOra = h.data1 ) i'), function ($join) {
            $join->on('T_WEB_Articoli.ListaArgomenti', '=', 'i.IdArgomento');
        })

        ->orderBy('dataOra', 'desc')
        ->get();
    //$articolo = Article::find($id);
    //$article = Article::where('IdArticolo',)->whereDate('DataOra',$articolo->data)->first();
    //dd($articles);
    //dd($articolo->authors);
    echo "IdArticolo | Titolo | ISBN | Prezzo | Argomento | Data<br>";
    foreach ($articles as $article) {
        echo $article->IdArticolo . " | " . $article->Titolo . " | " . $article->Ean13 . " | " . $article->PrezzoIvato . " | " . $article->DescrizioneArgomentoProdotto . " | " . $article->DescrizioneStatoProdotto . " | " . $article->DataOra . "<br>";
    }
});

Route::get('/stock', function () {
    $stock = new Stock();
    $qta = $stock->qtadisponibile(9781);
    dd($qta);
});




Route::get('/nimaia', function () {
    set_time_limit(0);
    ini_set("memory_limit", "512M");
    //ob_implicit_flush(true);
    $page = 1;

    $all_products = new Collection();
    do {

        $products = Product::all($options = ['per_page' => 100, 'page' => $page]);


        $all_products = $all_products->merge($products);
        $page++;
    } while ($products->count() > 0);
    ob_end_flush();
    ob_implicit_flush(true);
    echo "Totale prodotti padri: " . $all_products->count() . "<br>";

    foreach ($all_products as $key => $product) {
        echo $key . " - Sto processando " . $product->name . "<br>";
        $variations = Variation::all($product->id);
        foreach ($variations as $variation) {
            $artnimaia = Artnim::where('id_gm', $variation->sku)->first();
            if ($artnimaia && count($product->images) == 0) {
                //echo $product->id .' '. $variation->sku.'<br>';
                $data = [];
                $letterainiziale = strtolower(substr($artnimaia->titolo, 0, 1));
                $data['description'] = $artnimaia->descrizione;
                $data['meta_data'] = [['key' => 'prima_edizione', 'value' => $artnimaia->prima_edizione]];
                if ($artnimaia->img != '') {
                    $file = env('WOOCOMMERCE_STORE_URL') . 'wp-content/uploads/web/' . $letterainiziale . '/' . $artnimaia->img;
                    $file_headers = @get_headers($file);
                    if ($file_headers[0] == 'HTTP/1.1 404 Not Found' || $file_headers[0] == 'HTTP/1.1 301 Moved Permanently') {
                        $img = false;
                    } else {
                        $img = true;
                        $data['images'] = [
                            [
                                'src' => env('WOOCOMMERCE_STORE_URL') . 'wp-content/uploads/web/' . $letterainiziale . '/' . $artnimaia->img
                            ]
                        ];
                    }
                }

                Product::update($product->id, $data);

                break;
            }
        }
    }
});


Route::get('/wooproducts', function () {
    set_time_limit(0);
    ini_set("memory_limit", "512M");
    //ob_implicit_flush(true);
    $page = 1;
    $key = 0;
    $all_products = new Collection();
    ob_end_flush();
    ob_implicit_flush(true);
    do {

        $products = Product::all($options = ['per_page' => 100, 'page' => $page, 'orderby' => 'title', 'order' => 'asc']);

        foreach ($products as $product) {
            echo ++$key . " | " . $product->name . " | "  . $product->id;
            $variations = Variation::all($product->id);
            foreach ($variations as $variation) {

                $id = array_search('formato', array_column($variation->meta_data, 'key'));
                if ($id >= 0)
                    echo ' | ' . $variation->meta_data[$id]->value . ' | ' . $variation->id .  ' | ' . $variation->sku;
            }
            echo "<br>";
        }

        //$all_products = $all_products->merge($products);
        $page++;
    } while ($products->count() > 0);
});

Route::get('/collane', function () {

    $subQuery = DB::table('T_WEB_Collane')->select('IdCollana', DB::raw('max(DataOra) as data'))
        ->groupBy('IdCollana');

    $collane = DB::table(DB::raw('(' . $subQuery->toSql() . ') as c1'))
        ->select('*')
        ->join('T_WEB_Collane as c2', function ($join) {
            $join->on('c1.IdCollana', '=', 'c2.IdCollana')->On('c1.data', '=', 'DataOra');
        })
        ->whereNotNull('descrizione')
        ->mergeBindings($subQuery)
        ->get();

    dd($collane);
});

Route::get('/statoprodotto', function () {

    $subQuery = DB::table('T_WEB_StatiProdotto')->select('IdStatoProdotto', DB::raw('max(DataOra) as data'))
        ->groupBy('IdStatoProdotto');

    $collane = DB::table(DB::raw('(' . $subQuery->toSql() . ') as c1'))
        ->select('*')
        ->join('T_WEB_StatiProdotto as c2', function ($join) {
            $join->on('c1.IdStatoProdotto', '=', 'c2.IdStatoProdotto')->On('c1.data', '=', 'DataOra');
        })
        //->whereNotNull('descrizione')
        ->mergeBindings($subQuery)
        ->orderBy('Descrizione')
        ->get();
    foreach ($collane as $collana) {
        echo $collana->Descrizione . "<br>";
    }
    //dd($collane);

});

Route::get('/statoprodotto1', function () {
    //non va
    $collane = DB::table('T_WEB_StatiProdotto')->select(
        DB::raw('(SELECT * FROM T_WEB_StatiProdotto e JOIN (SELECT IdStatoProdotto, MAX(DataOra) as data1 from T_WEB_StatiProdotto GROUP BY IdStatoProdotto) c ON e.IdStatoProdotto = c.IdStatoProdotto AND e.DataOra = c.data1 ) f')
    )
        //->orderBy('T_WEB_StatiProdotto.Descrizione')
        ->get();
    dd($collane);
    foreach ($collane as $collana) {
        echo $collana->Descrizione . "<br>";
    }
});


Route::get('/disponibile', function () {

    $collane = DB::table('T_WEB_Disponibile')->select('*')
        ->where('Codice', 9154)->orderBy('DataOra', 'desc')
        ->take(10)
        ->get();
    dd($collane);
});





Route::get('/test1', function () {
    $products = Product::where('name', 'Vaccini Sì o No')->get();
    //$products = Product::where('name','LIKE','%Vaccini%')->get();
    dd($products);
    $data = [
        'meta_data' => [
            [
                'key' => 'edizione',
                'value' => 'Edizione plus'
            ]
        ]
    ];
    Product::update(13, $data);
});

Route::get('/categorie', function () {

    $subQuery = DB::table('T_WEB_Argomenti')->select('IdArgomento', DB::raw('max(DataOra) as data'))
        ->groupBy('IdArgomento');

    $categorie = DB::table(DB::raw('(' . $subQuery->toSql() . ') as c1'))
        ->select('*')
        ->join('T_WEB_Argomenti as c2', function ($join) {
            $join->on('c1.IdArgomento', '=', 'c2.IdArgomento')->On('c1.data', '=', 'DataOra');
        })
        //->whereNotNull('descrizione')
        ->mergeBindings($subQuery)
        ->get();
    //dd($categorie);
    foreach ($categorie as $categoria) {


        $data = [
            'name' => $categoria->Descrizione,

        ];

        $category = Category::where('name', $categoria->Descrizione);
        //$category = Category::all();
        //dd($category->count());
        if ($category->count() > 0) {
            $cat = $category->first();
            $category = Category::update($cat['id'], $data);
        } else {
            $category = Category::create($data);
        }
    }
});

Route::get('/artlibronuovo', function () {
    set_time_limit(0);
    $articles = Article::join(DB::raw('(SELECT IdArticolo, MAX(DataOra) AS data FROM T_WEB_Articoli GROUP BY IdArticolo) b'), function ($join) {
        $join->on('T_WEB_Articoli.IdArticolo', '=', 'b.IdArticolo')
            ->on('T_WEB_Articoli.DataOra', '=', 'b.data');
    })

        ->leftJoin(DB::raw('(SELECT e.IdStatoProdotto, e.Descrizione as DescrizioneStatoProdotto FROM T_WEB_StatiProdotto e JOIN (SELECT IdStatoProdotto, MAX(DataOra) as data1 from T_WEB_StatiProdotto GROUP BY IdStatoProdotto) c ON e.IdStatoProdotto = c.IdStatoProdotto AND e.DataOra = c.data1 ) f'), function ($join) {
            $join->on('T_WEB_Articoli.IdStatoProdotto', '=', 'f.IdStatoProdotto');
        })
        ->leftJoin(DB::raw('(SELECT g.IdTipologia, g.Descrizione as DescrizioneTipologia FROM T_WEB_Tipologie g JOIN (SELECT IdTipologia, MAX(DataOra) as data1 from T_WEB_Tipologie GROUP BY IdTipologia) h ON g.IdTipologia = h.IdTipologia AND g.DataOra = h.data1 ) i'), function ($join) {
            $join->on('T_WEB_Articoli.IdTipologia', '=', 'i.IdTipologia');
        })
        ->leftJoin(DB::raw('(SELECT l.IdTipoFormato, l.Descrizione as DescrizioneFormato FROM T_WEB_TipiFormato l JOIN (SELECT IdTipoFormato, MAX(DataOra) as data1 from T_WEB_TipiFormato GROUP BY IdTipoFormato) m ON l.IdTipoFormato = m.IdTipoFormato AND l.DataOra = m.data1 ) n'), function ($join) {
            $join->on('T_WEB_Articoli.IdTipoFormato', '=', 'n.IdTipoFormato');
        })
        ->leftJoin(DB::raw('(SELECT o.Codice, o.QtaDisponibile FROM T_WEB_Disponibile o JOIN (SELECT Codice, MAX(DataOra) as data1 from T_WEB_Disponibile GROUP BY Codice) p ON o.Codice = p.Codice AND o.DataOra = p.data1 ) q'), function ($join) {
            $join->on('T_WEB_Articoli.IdArticolo', '=', 'q.Codice');
        })

        //->groupBy('T_WEB_Articoli.IdArticolo')
        ->where('DescrizioneStatoProdotto', 'In commercio')
        //->where(function($query){
        //    $query->where('DescrizioneStatoProdotto','Usato')
        //->orWhere('DescrizioneStatoProdotto','In Commercio')
        //->orWhere('DescrizioneStatoProdotto','Remainder');
        //})
        //->where(DB::raw('CONVERT(INT, QtaDisponibile)'),'>',0)
        //->where('DescrizioneFormato','brossura')
        ->where('DescrizioneTipologia', 'Rivista')
        /*->where(function($query) {
        $query->where('b.data','>', '2022-01-01');
             //->orwhere('f.DataOra', '>', '2022-01-01');
            //  ->orwhere('h.data1', '>', '2022/01/01')
            //  ->orwhere('m.data1', '>', '2022/01/01')
            //  ->orwhere('p.data1', '>', '2022/01/01');
    })*/
        ->orderBy('Titolo')

        //->take(10)
        //->orderBy('ListaAutori')
        ->get();
    /*
    ->chunk(100, function ($articles) {
        foreach($articles as $article){
            echo $article->Id.' '. $article->IdArticolo. ' '. $article->Titolo .' '. $article->DescrizioneStatoProdotto. ' ' . $article->DescrizioneFormato .'<br>';
        }

    });
    */
    //dd($articles);
    ob_end_flush();
    ob_implicit_flush(true);
    foreach ($articles as $article) {
        echo $article->IdArticolo . "<br>";
        $productsku = Product::where('sku', $article->IdArticolo)->first();
        if ($productsku->count() == 0) {
            $category = Category::where('name', $article->argomento);
            if ($category->count() > 0) {
                $categoria = $category->first();
                $categoriaid = $categoria['id'];
            } else {
                $categoriaid = 0;
            }



            $data = [

                'name' => $article->Titolo,
                'type' => 'variable',
                'short_description' =>  $article->Sottotitolo,
                'categories' => [
                    ['id' => $categoriaid]

                ],


                //'description' => 'Simple product full description.',
                //'short_description' => 'Simple product short description.',


                'attributes' => [

                    [
                        //'id' => 1,
                        'id' => 6,
                        'position' => 0,
                        'visible' => true,
                        'variation' => true,
                        'options' => [
                            'Nuovo',
                            'Usato',
                            'PDF',
                            'Epub',
                            'Mobi',
                        ]
                    ],

                    [
                        //'id' => 5,
                        'id' => 7,
                        'visible' => true,

                        'options' =>
                        $article->authors


                    ],
                    [
                        //'id' => 2,
                        'id' => 8,
                        'visible' => true,

                        'options' => [
                            $article->editore

                        ]
                    ],
                    [
                        //'id' => 7,
                        'id' => 9,
                        'visible' => true,

                        'options' => [
                            $article->DescrizioneTipologia

                        ]
                    ]
                ],

                'default_attributes' => [
                    [
                        //'id' => 1,
                        'id' => 6,
                        'option' => 'Nuovo'
                    ]
                ],


                'meta_data' => [
                    [
                        'key' => 'pagine',
                        'value' =>  $article->Pagine
                    ],
                    [
                        'key' => 'edizione',
                        'value' =>  $article->Edizione
                    ],
                    [
                        'key' => 'ristampa',
                        'value' =>  $article->Ristampa
                    ],
                    [
                        'key' => 'misure',
                        'value' =>  $article->Misure
                    ],
                    [
                        'key' => 'isbn',
                        'value' =>  $article->Ean13
                    ],
                    [
                        'key' => 'formato',
                        'value' =>  $article->DescrizioneFormato
                    ],
                ]

            ];
            if ($productsku->count() == 0) {
                $product = Product::create($data);

                $idprodotto = $product['id'];
            } else {
                $idprodotto = $productsku['parent_id'];
                Product::update($idprodotto, $data);
            }


            $data1 = [

                'regular_price' => $article->PrezzoIvato,
                'sku' => $article->IdArticolo,
                'sale_price' => $article->PrezzoIvatoScontatoCampagna,
                'date_on_sale_from' => $article->DataInizioCampagna,
                'date_on_sale_to' => $article->DataFineCampagna,
                'manage_stock' => true,
                'stock_quantity' => $article->stock,

                'attributes' => [
                    [
                        //'id' => 1,
                        'id' => 6,
                        'option' => 'Nuovo'
                    ]

                ],
                'meta_data' => [
                    [
                        'key' => 'ISBN',
                        'value' => $article->Ean13
                    ],
                    [
                        'key' => 'misure',
                        'value' => $article->Misure
                    ],
                    [
                        'key' => 'formato',
                        'value' => $article->DescrizioneFormato
                    ],
                    [
                        'key' => 'pagine',
                        'value' => $article->Pagine
                    ],
                    [
                        'key' => 'edizione',
                        'value' => $article->Edizione
                    ],

                ]
            ];
            if ($productsku->count() > 0) {
                $variation = Variation::update($idprodotto, $productsku['id'], $data1);
            } else {
                $variation = Variation::create($idprodotto, $data1);
            }
        }
    }
    echo "Finito";
});


Route::get('/artlibrousato', function () {
    set_time_limit(0);
    $articles = Article::join(DB::raw('(SELECT IdArticolo, MAX(DataOra) AS data FROM T_WEB_Articoli GROUP BY IdArticolo) b'), function ($join) {
        $join->on('T_WEB_Articoli.IdArticolo', '=', 'b.IdArticolo')
            ->on('T_WEB_Articoli.DataOra', '=', 'b.data');
    })

        ->leftJoin(DB::raw('(SELECT e.IdStatoProdotto, e.Descrizione as DescrizioneStatoProdotto FROM T_WEB_StatiProdotto e JOIN (SELECT IdStatoProdotto, MAX(DataOra) as data1 from T_WEB_StatiProdotto GROUP BY IdStatoProdotto) c ON e.IdStatoProdotto = c.IdStatoProdotto AND e.DataOra = c.data1 ) f'), function ($join) {
            $join->on('T_WEB_Articoli.IdStatoProdotto', '=', 'f.IdStatoProdotto');
        })
        ->leftJoin(DB::raw('(SELECT g.IdTipologia, g.Descrizione as DescrizioneTipologia FROM T_WEB_Tipologie g JOIN (SELECT IdTipologia, MAX(DataOra) as data1 from T_WEB_Tipologie GROUP BY IdTipologia) h ON g.IdTipologia = h.IdTipologia AND g.DataOra = h.data1 ) i'), function ($join) {
            $join->on('T_WEB_Articoli.IdTipologia', '=', 'i.IdTipologia');
        })
        ->leftJoin(DB::raw('(SELECT l.IdTipoFormato, l.Descrizione as DescrizioneFormato FROM T_WEB_TipiFormato l JOIN (SELECT IdTipoFormato, MAX(DataOra) as data1 from T_WEB_TipiFormato GROUP BY IdTipoFormato) m ON l.IdTipoFormato = m.IdTipoFormato AND l.DataOra = m.data1 ) n'), function ($join) {
            $join->on('T_WEB_Articoli.IdTipoFormato', '=', 'n.IdTipoFormato');
        })
        ->leftJoin(DB::raw('(SELECT o.Codice, o.QtaDisponibile FROM T_WEB_Disponibile o JOIN (SELECT Codice, MAX(DataOra) as data1 from T_WEB_Disponibile GROUP BY Codice) p ON o.Codice = p.Codice AND o.DataOra = p.data1 ) q'), function ($join) {
            $join->on('T_WEB_Articoli.IdArticolo', '=', 'q.Codice');
        })

        //->groupBy('T_WEB_Articoli.IdArticolo')
        ->where('DescrizioneStatoProdotto', 'usato')
        //->where(function($query){
        //    $query->where('DescrizioneStatoProdotto','Usato')
        //->orWhere('DescrizioneStatoProdotto','In Commercio')
        //->orWhere('DescrizioneStatoProdotto','Remainder');
        //})
        ->where(DB::raw('CONVERT(INT, QtaDisponibile)'), '>', 0)
        ->where('DescrizioneFormato', 'brossura')
        ->where('DescrizioneTipologia', 'Libri')
        ->orderBy('Titolo')

        //->take(5)
        //->orderBy('ListaAutori')
        ->get();
    /*
        ->chunk(100, function ($articles) {
            foreach($articles as $article){
                echo $article->Id.' '. $article->IdArticolo. ' '. $article->Titolo .' '. $article->DescrizioneStatoProdotto. ' ' . $article->DescrizioneFormato .'<br>';
            }

        });
        */
    //dd($articles);
    //ob_implicit_flush(true);
    foreach ($articles as $article) {
        $titolo = rtrim(str_ireplace('USATO', '', $article->Titolo));
        $prodotti = Product::where('name', $titolo)->get();
        //$sku = Product::where('sku',6563)->first();

        $id = 0;
        if ($prodotti->count() > 0) {
            foreach ($prodotti as $prodotto) {

                if ($prodotto->name === $titolo) {
                    $id = $prodotto->id;
                    break;
                }
            }
        }
        //$product = Product::where('name','1 2 3 Animal Yoga')->first();
        if ($id  > 0) {
            //$sku = Product::where('sku',$article->IdArticolo)->first();
            $product = Product::find($id);
            $attributes = $product['meta_data'];

            $isbnproduct = '';
            foreach ($attributes as  $key => $value) {
                if ($value->key == 'isbn') {
                    $isbnproduct = $value->value;
                    break;
                }
            }
            $variations = Variation::all($id);
            $trovatosku = false;
            foreach ($variations as $variation) {

                if ($variation->sku == $article->IdProdotto) {
                    $trovatosku = true;
                    break;
                }
            }
            if (!$trovatosku) {
                if (substr($isbnproduct, 5) == substr($article->Ean13, 5)) {
                    $data1 = [

                        'regular_price' => $article->PrezzoIvato,
                        'sku' => $article->IdArticolo,
                        'sale_price' => $article->PrezzoIvatoScontatoCampagna,
                        'date_on_sale_from' => $article->DataInizioCampagna,
                        'date_on_sale_to' => $article->DataFineCampagna,
                        'manage_stock' => true,
                        'stock_quantity' => $article->stock,

                        'attributes' => [
                            [
                                'name' => 'Versione Libro',
                                'option' => 'Usato'
                            ]

                        ],
                        'meta_data' => [
                            [
                                'key' => 'ISBN',
                                'value' => $article->Ean13
                            ]
                        ]
                    ];
                    Variation::create($id, $data1);
                }
            }

            //echo $isbnproduct . ' '. $article->Ean13 .'<br>';
            /*
                    if(substr($isbnproduct,5) == substr($article->Ean13,5))
                    {
                        echo $product['id']. ' '.$product['name'].' '.$isbnproduct. ' '.$article->Ean13.' '. $titolo . ' ' .$article->IdArticolo. '<br>' ;
                        /*
                        $data1 = [

                            'regular_price' => $article->PrezzoIvato,
                            'sku' => $article->IdArticolo,
                            'sale_price' => $article->PrezzoIvatoScontatoCampagna,
                            'date_on_sale_from' => $article->DataInizioCampagna,
                            'date_on_sale_to' => $article->DataFineCampagna,
                            'manage_stock' => true,
                            'stock_quantity' => $article->stock,

                            'attributes' => [
                                [
                                    'name' => 'Versione Libro',
                                    'option' => 'Usato'
                                ]

                            ],
                            'meta_data' => [
                                [
                                    'key' => 'ISBN',
                                    'value' => $article->Ean13
                                ]
                            ]
                        ];
                        Variation::create($product['id'],$data1);
                        */
            // }


            //}

        }
        /*
            $productsku = Product::where('sku',$article->IdArticolo)->first();
            if($productsku->count() == 0){
            $category = Category::where('name',$article->argomento);
            if($category->count() > 0 ) {
                $categoria = $category->first();
                $categoriaid =$categoria['id'];
            } else {
                $categoriaid = 0;
            }



                $data = [

                'name' => $article->Titolo,
                'type' => 'variable',

                'categories' => [
                    [ 'id' => $categoriaid ]

                ],


                //'description' => 'Simple product full description.',
                //'short_description' => 'Simple product short description.',


                'attributes' => [

                    [
                        'name' => 'Versione Libro',
                        'position' => 0,
                        'visible' => true,
                        'variation' => true,
                        'options' => [
                            'Nuovo',
                            'Usato'
                        ]
                     ],

                    [
                        'id' => 5,
                        'visible' => true,

                        'options' =>
                            $article->authors


                        ],
                    [
                        'id' => 2,
                        'visible' => true,

                        'options' => [
                            $article->editore

                        ]
                        ],
                    [
                        'name' => 'Tipologia',
                        'visible' => true,

                        'options' => [
                            $article->DescrizioneTipologia

                        ]
                    ]
                ],

                'default_attributes' => [
                    [
                        'name' => 'Versione Libro',
                        'option' => 'Nuovo'
                    ]
                    ],


                'meta_data' => [
                    [
                        'key' => 'pagine',
                        'value' =>  $article->Pagine
                    ],
                    [
                        'key' => 'edizione',
                        'value' =>  $article->Edizione
                    ],
                    [
                        'key' => 'ristampa',
                        'value' =>  $article->Ristampa
                    ],
                    [
                        'key' => 'misure',
                        'value' =>  $article->Misure
                    ],
                    [
                        'key' => 'isbn',
                        'value' =>  $article->Ean13
                    ],
                    [
                        'key' => 'formato',
                        'value' =>  $article->DescrizioneFormato
                    ],
                ]

            ];
            if($productsku->count() == 0){
            $product = Product::create($data);

            $idprodotto= $product['id'];

            } else {
                $idprodotto = $productsku['parent_id'];
                Product::update($idprodotto,$data);
            }


            $data1 = [

                'regular_price' => $article->PrezzoIvato,
                'sku' => $article->IdArticolo,
                'sale_price' => $article->PrezzoIvatoScontatoCampagna,
                'date_on_sale_from' => $article->DataInizioCampagna,
                'date_on_sale_to' => $article->DataFineCampagna,
                'manage_stock' => true,
                'stock_quantity' => $article->stock,

                'attributes' => [
                    [
                        'name' => 'Versione Libro',
                        'option' => 'Nuovo'
                    ]

                ],
                'meta_data' => [
                    [
                        'key' => 'ISBN',
                        'value' => $article->Ean13
                    ]
                ]
            ];
            if($productsku->count() > 0){
                  $variation = Variation::update($idprodotto,$productsku['id'], $data1);
            } else {
                $variation = Variation::create($idprodotto, $data1);

            }
        }
        */
    }
    echo "Finito";
});
Route::get(
    '/test2',
    function () {

        $product = Product::where('name', 'LiKE', '100 baby ricette -')->get();

        if ($product->count() > 0) {
            dd($product);
            $sku = Product::where('sku', 3514)->get();

            dd($sku->count());
        }
    }
);
Route::get('/test3', function () {

    $page = 1;

    $all_products = new Collection();
    do {

        $products = Product::all($options = ['per_page' => 100, 'page' => $page]);


        $all_products = $all_products->merge($products);
        $page++;
    } while ($products->count() > 0);
    foreach ($all_products as $product) {
        dd($product->attributes);
    }
    dd($all_products);
});

Route::get('/test4', function () {
    dd(date('d-m-Y H:i:s'));
    $product = Product::find(24006);
    /*
    $variations = Variation::all($product['id']);
    foreach ($variations as  $variation) {
        $old_variantion_attributes[$variation->id] = $variation->attributes[0]->option;

    }

*/
    dd($product['attributes']);

    $old_attributes = $product['attributes'];
    foreach ($old_attributes as $old_attribute) {
        echo $old_attribute->id . " " . $old_attribute->name . " ";
        print_r($old_attribute->options) . "<br>";
    }


    /*

   $data = [
    'attributes' => [
        [
        'id' => 4,
        'position' => 0,
                'visible' => true,
                'variation' => true,
                'options' => ['Nuovo','Usato']
        ],
        [
            'id' => 1,

            'visible' => $old_attributes[1]->visible,

            'options' => $old_attributes[1]->options




    ]

        ],
         'default_attributes' => [
                               [
                    'id' => 4,
                    'option' => 'Nuovo'
                ]
            ]
   ];

   Product::update($product['id'],$data);

   foreach ($variations as  $variation) {

    $data1 = [
            'attributes' => [
                [
                    'id' => 4,
                    'option' => $old_variantion_attributes[$variation->id]
                ]
         ]
        ];
        Variation::update($product['id'], $variation->id,$data1);

    }

   //Product::update(81,$data);
   //$product = Product::find(3004);
   //$variations =Variation::find(3008,3009);
   //dd($variations);

*/
});


Route::get('/test5', function () {
    set_time_limit(0);
    $authors = Authornimaia::where('id_sito', 1)->get();
    $attribute_id = 7;
    ob_implicit_flush(true);
    foreach ($authors as $author) {
        $search_author = $author->nome . ' ' . $author->cognome;

        $terms = Term::all($attribute_id, $options = ['search' => $search_author]);
        if ($terms->count() > 0) {
            $data = [
                'description' => $author->biografia
            ];

            Term::update($attribute_id, $terms[0]->id, $data);
            echo $terms[0]->id . "<br>";
        }
    }
});
Route::get('/artlibroebook', function () {
    set_time_limit(0);
    ob_implicit_flush(true);
    $articles = Article::join(DB::raw('(SELECT IdArticolo, MAX(DataOra) AS data FROM T_WEB_Articoli GROUP BY IdArticolo) b'), function ($join) {
        $join->on('T_WEB_Articoli.IdArticolo', '=', 'b.IdArticolo')
            ->on('T_WEB_Articoli.DataOra', '=', 'b.data');
    })

        ->leftJoin(DB::raw('(SELECT e.IdStatoProdotto, e.Descrizione as DescrizioneStatoProdotto FROM T_WEB_StatiProdotto e JOIN (SELECT IdStatoProdotto, MAX(DataOra) as data1 from T_WEB_StatiProdotto GROUP BY IdStatoProdotto) c ON e.IdStatoProdotto = c.IdStatoProdotto AND e.DataOra = c.data1 ) f'), function ($join) {
            $join->on('T_WEB_Articoli.IdStatoProdotto', '=', 'f.IdStatoProdotto');
        })
        ->leftJoin(DB::raw('(SELECT g.IdTipologia, g.Descrizione as DescrizioneTipologia FROM T_WEB_Tipologie g JOIN (SELECT IdTipologia, MAX(DataOra) as data1 from T_WEB_Tipologie GROUP BY IdTipologia) h ON g.IdTipologia = h.IdTipologia AND g.DataOra = h.data1 ) i'), function ($join) {
            $join->on('T_WEB_Articoli.IdTipologia', '=', 'i.IdTipologia');
        })
        ->leftJoin(DB::raw('(SELECT l.IdTipoFormato, l.Descrizione as DescrizioneFormato FROM T_WEB_TipiFormato l JOIN (SELECT IdTipoFormato, MAX(DataOra) as data1 from T_WEB_TipiFormato GROUP BY IdTipoFormato) m ON l.IdTipoFormato = m.IdTipoFormato AND l.DataOra = m.data1 ) n'), function ($join) {
            $join->on('T_WEB_Articoli.IdTipoFormato', '=', 'n.IdTipoFormato');
        })
        /*
    ->leftJoin(DB::raw('(SELECT o.Codice, o.QtaDisponibile FROM T_WEB_Disponibile o JOIN (SELECT Codice, MAX(DataOra) as data1 from T_WEB_Disponibile GROUP BY Codice) p ON o.Codice = p.Codice AND o.DataOra = p.data1 ) q'), function($join) {
        $join->on('T_WEB_Articoli.IdArticolo', '=', 'q.Codice');
    })
    */

        //->groupBy('T_WEB_Articoli.IdArticolo')
        ->where('DescrizioneStatoProdotto', 'In commercio')
        //->where(function($query){
        //    $query->where('DescrizioneStatoProdotto','Usato')
        //->orWhere('DescrizioneStatoProdotto','In Commercio')
        //->orWhere('DescrizioneStatoProdotto','Remainder');
        //})
        //->where(DB::raw('CONVERT(INT, QtaDisponibile)'),'>',0)
        //->where('DescrizioneFormato','Epub')
        ->where('DescrizioneTipologia', 'E-book')
        ->orderBy('Titolo')

        //->take(5)
        //->orderBy('ListaAutori')
        ->get();
    /*
    ->chunk(100, function ($articles) {
        foreach($articles as $article){
            echo $article->Id.' '. $article->IdArticolo. ' '. $article->Titolo .' '. $article->DescrizioneStatoProdotto. ' ' . $article->DescrizioneFormato .'<br>';
        }

    });
    */
    //dd($articles);
    ob_end_flush();
    ob_implicit_flush(true);
    echo "Trovati " . $articles->count() . "<br>";
    foreach ($articles as $key => $article) {
        echo $key . " - Sto proccessando " . $article->Titolo . "<br>";
        $titolo = null;
        $formato = null;
        $prodotti = null;

        if ($article->DescrizioneFormato === 'Epub') {


            $titolo = rtrim(str_ireplace('EPUB', '', $article->Titolo));

            $formato = 'Epub';
        } elseif ($article->DescrizioneFormato === 'Pdf') {
            $titolo = rtrim(str_ireplace('PDF', '', $article->Titolo));

            $formato = 'PDF';
        } elseif ($article->DescrizioneFormato === 'Mobi') {
            $titolo = rtrim(str_ireplace('MOBI', '', $article->Titolo));


            $formato = 'Mobi';
        } else {
            continue;
        }

        $titolo = rtrim($titolo);
        $titolo = rtrim(str_ireplace('EBOOK', '', $titolo));
        $titolo = rtrim($titolo);
        $titolo = rtrim(str_ireplace('_', '', $titolo));
        $titolo = rtrim($titolo);
        $titolo = rtrim($titolo, '-');
        $titolo = rtrim($titolo);
        $titolo = rtrim($titolo, '_');
        $titolo = rtrim($titolo);
        echo $titolo . "<br>";
        $prodotti = new ModelsProduct();
        $prodotti = $prodotti->where('name', $titolo)->get();

        /*
        echo $article->Id.' '. $article->IdArticolo. ' '. $article->Ean13 . ' '. $article->Titolo .' '. implode(",",$article->authors) .' ' . $article->DescrizioneStatoProdotto. ' ' . $article->DescrizioneFormato . ' ' .$article->QtaDisponibile . '<br>';
        */
        $id = 0;
        if (!is_null($prodotti) && $prodotti->count() > 0) {
            foreach ($prodotti as $prodotto) {
                echo $prodotto->name . "<br>";
                echo $titolo . "<br>";
                if (strtolower($prodotto->name) === strtolower($titolo)) {
                    $id = $prodotto->id;
                }
            }
        }

        if ($id  > 0) {
            //$sku = Product::where('sku',$article->IdArticolo)->first();
            echo "Trovato " . $titolo . "<br>";
            $product = Product::find($id);
            $old_attributes = $product['attributes'];
            $attributes = [];
            foreach ($old_attributes as $old_attribute) {
                if ($old_attribute->id <> 6) {

                    $attributes[] = [
                        'id' => $old_attribute->id,
                        'variation' => $old_attribute->variation,
                        'visible' => $old_attribute->visible,
                        'options' => $old_attribute->options
                    ];
                }
            }

            $attributes[] =  [
                //'id' => 1,
                'id' => 6,
                'position' => 0,
                'visible' => true,
                'variation' => true,
                'options' => [
                    'Nuovo',
                    'Usato',
                    'PDF',
                    'Epub',
                    'Mobi',
                ]
            ];
            //dd($attributes);

            $data = [

                'attributes' => $attributes


            ];
            Product::update($id, $data);


            $variations = Variation::all($id);
            $trovatosku = false;
            foreach ($variations as $variation) {

                if ($variation->sku == $article->IdProdotto) {
                    $trovatosku = true;
                    break;
                }
            }
            if (!$trovatosku) {
                echo "&nbsp;&nbsp;&nbsp;&nbsp;Aggiunto " . $article->Titolo . "<br>";
                $data1 = [

                    'regular_price' => $article->PrezzoIvato,
                    'sku' => $article->IdArticolo,
                    'sale_price' => $article->PrezzoIvatoScontatoCampagna,
                    'date_on_sale_from' => $article->DataInizioCampagna,
                    'date_on_sale_to' => $article->DataFineCampagna,
                    //'manage_stock' => true,
                    //'stock_quantity' => $article->stock,

                    'attributes' => [
                        [
                            'id' => 6,
                            'option' => $formato
                        ]

                    ],
                    'meta_data' => [
                        [
                            'key' => 'ISBN',
                            'value' => $article->Ean13
                        ],
                        [
                            'key' => 'misure',
                            'value' => $article->Misure
                        ],
                        [
                            'key' => 'formato',
                            'value' => $article->DescrizioneFormato
                        ],
                        [
                            'key' => 'pagine',
                            'value' => $article->Pagine
                        ],
                        [
                            'key' => 'edizione',
                            'value' => $article->Edizione
                        ],
                    ]
                ];
                Variation::create($id, $data1);
            }
        } else {


            $productsku = Product::where('sku', $article->IdArticolo)->first();
            if ($productsku->count() == 0) {
                //$sku = Product::where('sku',$article->IdArticolo)->first();
                echo "Nuovo " . $titolo . "<br>";
                $category = Category::where('name', $article->argomento);
                if ($category->count() > 0) {
                    $categoria = $category->first();
                    $categoriaid = $categoria['id'];
                } else {
                    $categoriaid = 0;
                }



                $data = [

                    'name' => $titolo,
                    'type' => 'variable',
                    'short_description' =>  $article->Sottotitolo,
                    'categories' => [
                        ['id' => $categoriaid]

                    ],

                    'attributes' => [

                        [
                            //'id' => 1,
                            'id' => 6,
                            'position' => 0,
                            'visible' => true,
                            'variation' => true,
                            'options' => [
                                'Nuovo',
                                'Usato',
                                'PDF',
                                'Epub',
                                'Mobi',
                            ]
                        ],

                        [
                            //'id' => 5,
                            'id' => 7,
                            'visible' => true,

                            'options' =>
                            $article->authors


                        ],
                        [
                            //'id' => 2,
                            'id' => 8,
                            'visible' => true,

                            'options' => [
                                $article->editore

                            ]
                        ],
                        [
                            //'id' => 7,
                            'id' => 9,
                            'visible' => true,

                            'options' => [
                                $article->DescrizioneTipologia

                            ]
                        ]
                    ],

                    'default_attributes' => [
                        [
                            //'id' => 1,
                            'id' => 6,
                            'option' => 'Nuovo'
                        ]
                    ],


                    'meta_data' => [
                        [
                            'key' => 'pagine',
                            'value' =>  $article->Pagine
                        ],
                        [
                            'key' => 'edizione',
                            'value' =>  $article->Edizione
                        ],
                        [
                            'key' => 'ristampa',
                            'value' =>  $article->Ristampa
                        ],
                        [
                            'key' => 'misure',
                            'value' =>  $article->Misure
                        ],
                        [
                            'key' => 'isbn',
                            'value' =>  $article->Ean13
                        ],
                        [
                            'key' => 'formato',
                            'value' =>  $formato
                        ],
                    ]

                ];
                if ($productsku->count() == 0) {
                    $product = Product::create($data);

                    $idprodotto = $product['id'];
                } else {
                    $idprodotto = $productsku['parent_id'];
                    Product::update($idprodotto, $data);
                }

                echo "&nbsp;&nbsp;&nbsp;&nbsp;Aggiunto " . $article->Titolo . "<br>";
                $data1 = [

                    'regular_price' => $article->PrezzoIvato,
                    'sku' => $article->IdArticolo,
                    'sale_price' => $article->PrezzoIvatoScontatoCampagna,
                    'date_on_sale_from' => $article->DataInizioCampagna,
                    'date_on_sale_to' => $article->DataFineCampagna,
                    //'manage_stock' => true,
                    //'stock_quantity' => $article->stock,

                    'attributes' => [
                        [
                            //'id' => 1,
                            'id' => 6,
                            'option' => $formato
                        ]

                    ],
                    'meta_data' => [
                        [
                            'key' => 'ISBN',
                            'value' => $article->Ean13
                        ],
                        [
                            'key' => 'misure',
                            'value' => $article->Misure
                        ],
                        [
                            'key' => 'formato',
                            'value' => $formato
                        ],
                        [
                            'key' => 'pagine',
                            'value' => $article->Pagine
                        ],
                        [
                            'key' => 'edizione',
                            'value' => $article->Edizione
                        ],

                    ]
                ];
                if ($productsku->count() > 0) {
                    $variation = Variation::update($idprodotto, $productsku['id'], $data1);
                } else {
                    $variation = Variation::create($idprodotto, $data1);
                }
            }
        }
    }
    echo "Finito";
});

Route::get('/changeversion', function () {
    set_time_limit(0);
    $page = 1;
    $all_products = new Collection();
    do {

        $products = Product::all($options = ['per_page' => 100, 'page' => $page]);


        $all_products = $all_products->merge($products);
        $page++;
    } while ($products->count() > 0);

    foreach ($all_products as $product) {
        if ($product->id > 670) {
            $old_attributes = $product->attributes;
            $variations = Variation::all($product->id);
            foreach ($variations as  $variation) {
                $old_variantion_attributes[$variation->id] = $variation->attributes[0]->option;
            }

            $data = [
                'attributes' => [
                    [
                        'id' => 1,
                        'position' => 0,
                        'visible' => true,
                        'variation' => true,
                        'options' => ['Nuovo', 'Usato']
                    ],

                    [
                        'id' => 5,
                        'visible' => true,

                        'options' =>
                        $old_attributes[1]->options


                    ],
                    [
                        'id' => 2,
                        'visible' => true,

                        'options' =>
                        $old_attributes[2]->options


                    ],
                    [
                        'id' => 7,
                        'visible' => true,

                        'options' =>
                        $old_attributes[3]->options


                    ]

                ],
                'default_attributes' => [
                    [
                        'id' => 1,
                        'option' => 'Nuovo'
                    ]
                ]
            ];
            $product = Product::update($product->id, $data);

            //$variations = Variation::all($product['id']);
            foreach ($variations as $variation) {

                $data1 = [
                    'attributes' => [
                        [
                            'id' => 1,
                            'option' => $old_variantion_attributes[$variation->id]
                        ]
                    ]
                ];
                $variationup = Variation::update($product['id'], $variation->id, $data1);
            }
        }
    }

    echo "Finito";
});


Route::post('/ordercreate', function (Request $request) {

    //dd($webhook);

    Log::debug($request->all());

    /*
  $changedest = false;
  if (($request->shipping['address_1'] != null && $request->shipping['address_1'] != '' &&   $request->shipping['address_1']  != $request->billing['address_1']) || ($request->shipping['first_name']!= null && $request->shipping['first_name'] != '' && $request->shipping['first_name'] != $request->billing['first_name'])  ){
    $changedest= true;
  }
  $order = new Order();
  $order->IdInternet = $request->id;
  $order->CodClienteInternet = $request->customer_id;
  $order->Enabled = 1;
  $order->DataOra = $request->date_created;
  $order->Note = $request->customer_note;
  $order->Totale = $request->total;
  if ($changedest)
  {
      $order->CodDestInternet = $request->customer_id;
  }
  $order->save();

  $prodotti = $request->line_items;
  foreach ($prodotti as $prodotto){
    $orderdetail = new Orderdetail();
    $orderdetail->IdInternet = $request->id;
    $orderdetail->CodArticoloGM = $prodotto['sku'];
    $orderdetail->Qta = $prodotto['quantity'];
    $orderdetail->PrezzoLordo = $prodotto['total'];
    $orderdetail->Enabled = 1;
    $orderdetail->DataOra = $request->date_created;
    $orderdetail->save();

  }

  $customer = Customer::find($request->customer_id);
  $cliente = new Clientegm();
  $cliente->CodClienteInternet = $customer['id'];
  $cliente->Nominativo = $customer['last_name'] . " " .$customer['first_name'];
  $cliente->Indirizzo = $customer['billing']->address_1 . " ". $customer['billing']->address_2;
  $cliente->Citta = $customer['billing']->city;
  $cliente->Cap = $customer['billing']->postcode;
  $cliente->Provincia = $customer['billing']->state;
  $cliente->Telefono = $customer['billing']->phone;
  $cliente->Email = $customer['billing']->email;
  $metas = $customer['meta_data'];
  foreach($metas as $meta)
  {

      if ($meta->key == 'cod_fiscale')
      {
          $cliente->CodiceFiscale = $meta->value;
      }
      elseif ($meta->key == 'vat')
      {
        $cliente->PIVA = $meta->value;
      }
  }
  $cliente->IdInternet = $request->id;
  $cliente->save();

  if($changedest){
      $clientedest = new Clientegmdest();
      $clientedest->CodDestInternet = $request->customer_id;
      $clientedest->Nominativo = $request->shipping['last_name'] . " " .$request->shipping['first_name'];
      $clientedest->Indirizzo = $request->shipping['address_1'] . " ". $request->shipping['address_2'];
      $clientedest->Citta = $request->shipping['city'];
      $clientedest->Cap = $request->shipping['postcode'];
      $clientedest->Provincia = $request->shipping['state'];
      $clientedest->Telefono = $request->shipping['phone'];
      $clientedest->IdInternet = $request->id;
      $clientedest->save();
  }







  Log::info('Inserito ordine');


*/
});
Route::get('/ordercreate/{id}', function ($id) {

    dd(Webhook::find($id));
});
Route::get('/cliente/{id}', function ($id) {

    dd(Customer::find($id));
});

Route::get('sistema', function () {
    set_time_limit(0);
    //ob_implicit_flush(true);
    $page = 1;

    $all_products = new Collection();
    do {

        $products = Product::all($options = ['per_page' => 100, 'page' => $page]);

        $filtered = $products->whereBetween('id', [23856, 24304]);

        $all_products = $all_products->merge($filtered);
        $page++;
    } while ($products->count() > 0);

    foreach ($all_products as $product) {
        $variations = Variation::all($product->id);
        foreach ($variations as $variation) {


            $article = Article::join(DB::raw('(SELECT IdArticolo, MAX(DataOra) AS data FROM T_WEB_Articoli GROUP BY IdArticolo) b'), function ($join) {
                $join->on('T_WEB_Articoli.IdArticolo', '=', 'b.IdArticolo')
                    ->on('T_WEB_Articoli.DataOra', '=', 'b.data');
            })
                /*
            ->leftJoin(DB::raw('(SELECT e.IdStatoProdotto, e.Descrizione as DescrizioneStatoProdotto FROM T_WEB_StatiProdotto e JOIN (SELECT IdStatoProdotto, MAX(DataOra) as data1 from T_WEB_StatiProdotto GROUP BY IdStatoProdotto) c ON e.IdStatoProdotto = c.IdStatoProdotto AND e.DataOra = c.data1 ) f'), function($join) {
                $join->on('T_WEB_Articoli.IdStatoProdotto', '=', 'f.IdStatoProdotto');
            })
            ->leftJoin(DB::raw('(SELECT g.IdTipologia, g.Descrizione as DescrizioneTipologia FROM T_WEB_Tipologie g JOIN (SELECT IdTipologia, MAX(DataOra) as data1 from T_WEB_Tipologie GROUP BY IdTipologia) h ON g.IdTipologia = h.IdTipologia AND g.DataOra = h.data1 ) i'), function($join) {
                $join->on('T_WEB_Articoli.IdTipologia', '=', 'i.IdTipologia');
            })
            ->leftJoin(DB::raw('(SELECT l.IdTipoFormato, l.Descrizione as DescrizioneFormato FROM T_WEB_TipiFormato l JOIN (SELECT IdTipoFormato, MAX(DataOra) as data1 from T_WEB_TipiFormato GROUP BY IdTipoFormato) m ON l.IdTipoFormato = m.IdTipoFormato AND l.DataOra = m.data1 ) n'), function($join) {
                $join->on('T_WEB_Articoli.IdTipoFormato', '=', 'n.IdTipoFormato');
            })
            ->leftJoin(DB::raw('(SELECT o.Codice, o.QtaDisponibile FROM T_WEB_Disponibile o JOIN (SELECT Codice, MAX(DataOra) as data1 from T_WEB_Disponibile GROUP BY Codice) p ON o.Codice = p.Codice AND o.DataOra = p.data1 ) q'), function($join) {
                $join->on('T_WEB_Articoli.IdArticolo', '=', 'q.Codice');
            })
            */
                ->leftJoin(DB::raw('(SELECT r.IdMarchioEditoriale, r.Descrizione as CasaEditrice FROM T_WEB_MarchiEditoriali r JOIN (SELECT IdMarchioEditoriale, MAX(DataOra) as data1 from T_WEB_MarchiEditoriali GROUP BY IdMarchioEditoriale) s ON r.IdMarchioEditoriale = s.IdMarchioEditoriale AND r.DataOra = s.data1 ) t'), function ($join) {
                    $join->on('T_WEB_Articoli.IdMarchioEditoriale', '=', 't.IdMarchioEditoriale');
                })
                ->where('T_WEB_Articoli.IdArticolo', $variation->sku)->first();

            $data = [
                'meta_data' => [
                    [
                        'key' => 'casa_editrice',
                        'value' =>  $article->CasaEditrice
                    ]
                ]
            ];
            Product::update($product->id, $data);
            break;
        }
    }
});

Route::get('/sistema_autori', function () {
    set_time_limit(0);

    $page = 1;

    $all_products = new Collection();
    do {

        $products = Product::all($options = ['per_page' => 100, 'page' => $page]);

        //$filtered = $products->where('type');

        $all_products = $all_products->merge($products);
        $page++;
    } while ($products->count() > 0);
    ob_implicit_flush(true);
    foreach ($all_products as $product) {
        $variations = Variation::all($product->id);
        foreach ($variations as $variation) {
            $article = Article::join(DB::raw('(SELECT IdArticolo, MAX(DataOra) AS data FROM T_WEB_Articoli GROUP BY IdArticolo) b'), function ($join) {
                $join->on('T_WEB_Articoli.IdArticolo', '=', 'b.IdArticolo')
                    ->on('T_WEB_Articoli.DataOra', '=', 'b.data');
            })
                ->where('T_WEB_Articoli.IdArticolo', $variation->sku)
                ->where('T_WEB_Articoli.ListaAutori', 'LIKE', '%,%')
                ->first();
            if ($article) {
                $old_attributes = $product->attributes;
                $attributes = [];
                foreach ($old_attributes as $old_attribute) {
                    if ($old_attribute->id <> 7) {

                        $attributes[] = [
                            'id' => $old_attribute->id,
                            'variation' => $old_attribute->variation,
                            'visible' => $old_attribute->visible,
                            'options' => $old_attribute->options
                        ];
                    }
                }

                $attributes[] = [
                    'id' => 7,
                    'variation' => false,
                    'visible' => true,
                    'options' => $article->authors
                ];


                $data = [

                    'attributes' => $attributes


                ];
                Product::update($product->id, $data);
                echo "Modificato: " . $product->id . "</br>";
                break;
            }
        }
    }
});


Route::get('/autori_test', function () {


    $article = Article::join(DB::raw('(SELECT IdArticolo, MAX(DataOra) AS data FROM T_WEB_Articoli GROUP BY IdArticolo) b'), function ($join) {
        $join->on('T_WEB_Articoli.IdArticolo', '=', 'b.IdArticolo')
            ->on('T_WEB_Articoli.DataOra', '=', 'b.data');
    })
        ->where('T_WEB_Articoli.IdArticolo', 13840)
        ->where('T_WEB_Articoli.ListaAutori', 'LIKE', '%,%')
        ->first();
    if ($article) {
        $product = Product::find(24006);
        $old_attributes = $product['attributes'];
        $attributes = [];
        foreach ($old_attributes as $old_attribute) {
            if ($old_attribute->id <> 7) {

                $attributes[] = [
                    'id' => $old_attribute->id,
                    'variation' => $old_attribute->variation,
                    'visible' => $old_attribute->visible,
                    'options' => $old_attribute->options
                ];
            }
        }

        $attributes[] = [
            'id' => 7,
            'variation' => false,
            'visible' => true,
            'options' => $article->authors
        ];
        //dd($attributes);

        $data = [

            'attributes' => $attributes


        ];
        Product::update(24006, $data);
    }
});

Route::get('/test6', function () {
    $orders = Order::all();
    dd($orders);
});

Route::get('/test7/{name}', function ($name) {
    $articles = Article::join(DB::raw('(SELECT IdArticolo, MAX(DataOra) AS data FROM T_WEB_Articoli WHERE Titolo LIKE \'%' . $name . '%\' GROUP BY IdArticolo) b'), function ($join) {
        $join->on('T_WEB_Articoli.IdArticolo', '=', 'b.IdArticolo')
            ->on('T_WEB_Articoli.DataOra', '=', 'b.data');
    })
        ->leftJoin(DB::raw('(SELECT e.IdStatoProdotto, e.Descrizione as DescrizioneStatoProdotto FROM T_WEB_StatiProdotto e JOIN (SELECT IdStatoProdotto, MAX(DataOra) as data1 from T_WEB_StatiProdotto GROUP BY IdStatoProdotto) c ON e.IdStatoProdotto = c.IdStatoProdotto AND e.DataOra = c.data1 ) f'), function ($join) {
            $join->on('T_WEB_Articoli.IdStatoProdotto', '=', 'f.IdStatoProdotto');
        })
        ->leftJoin(DB::raw('(SELECT g.IdTipologia, g.Descrizione as DescrizioneTipologia FROM T_WEB_Tipologie g JOIN (SELECT IdTipologia, MAX(DataOra) as data1 from T_WEB_Tipologie GROUP BY IdTipologia) h ON g.IdTipologia = h.IdTipologia AND g.DataOra = h.data1 ) i'), function ($join) {
            $join->on('T_WEB_Articoli.IdTipologia', '=', 'i.IdTipologia');
        })
        ->leftJoin(DB::raw('(SELECT l.IdTipoFormato, l.Descrizione as DescrizioneFormato FROM T_WEB_TipiFormato l JOIN (SELECT IdTipoFormato, MAX(DataOra) as data1 from T_WEB_TipiFormato GROUP BY IdTipoFormato) m ON l.IdTipoFormato = m.IdTipoFormato AND l.DataOra = m.data1 ) n'), function ($join) {
            $join->on('T_WEB_Articoli.IdTipoFormato', '=', 'n.IdTipoFormato');
        })
        ->leftJoin(DB::raw('(SELECT o.Codice, o.QtaDisponibile FROM T_WEB_Disponibile o JOIN (SELECT Codice, MAX(DataOra) as data1 from T_WEB_Disponibile GROUP BY Codice) p ON o.Codice = p.Codice AND o.DataOra = p.data1 ) q'), function ($join) {
            $join->on('T_WEB_Articoli.IdArticolo', '=', 'q.Codice');
        })
        ->get();
    //$articolo = Article::find($id);
    //$article = Article::where('IdArticolo',)->whereDate('DataOra',$articolo->data)->first();
    //dd($articles);
    //dd($articles[0]);
    ob_implicit_flush(true);
    //dd($articles);
    foreach ($articles as $article) {
        echo $article->IdArticolo . " | " . $article->Titolo . " | " . $article->Ean13 . "|" . $article->DescrizioneStatoProdotto . " | " . $article->DescrizioneTipologia . " | " .  $article->DescrizioneFormato . " | " . $article->QtaDisponibile . " | " . $article->data . "<br>";
    }
});
Route::get('/test8/{tipologia}', function ($name) {
    $articles = Article::join(DB::raw('(SELECT IdArticolo, MAX(DataOra) AS data FROM T_WEB_Articoli  GROUP BY IdArticolo) b'), function ($join) {
        $join->on('T_WEB_Articoli.IdArticolo', '=', 'b.IdArticolo')
            ->on('T_WEB_Articoli.DataOra', '=', 'b.data');
    })
        ->leftJoin(DB::raw('(SELECT e.IdStatoProdotto, e.Descrizione as DescrizioneStatoProdotto FROM T_WEB_StatiProdotto e JOIN (SELECT IdStatoProdotto, MAX(DataOra) as data1 from T_WEB_StatiProdotto GROUP BY IdStatoProdotto) c ON e.IdStatoProdotto = c.IdStatoProdotto AND e.DataOra = c.data1 ) f'), function ($join) {
            $join->on('T_WEB_Articoli.IdStatoProdotto', '=', 'f.IdStatoProdotto');
        })
        ->leftJoin(DB::raw('(SELECT g.IdTipologia, g.Descrizione as DescrizioneTipologia FROM T_WEB_Tipologie g JOIN (SELECT IdTipologia, MAX(DataOra) as data1 from T_WEB_Tipologie GROUP BY IdTipologia) h ON g.IdTipologia = h.IdTipologia AND g.DataOra = h.data1 ) i'), function ($join) {
            $join->on('T_WEB_Articoli.IdTipologia', '=', 'i.IdTipologia');
        })
        ->leftJoin(DB::raw('(SELECT l.IdTipoFormato, l.Descrizione as DescrizioneFormato FROM T_WEB_TipiFormato l JOIN (SELECT IdTipoFormato, MAX(DataOra) as data1 from T_WEB_TipiFormato GROUP BY IdTipoFormato) m ON l.IdTipoFormato = m.IdTipoFormato AND l.DataOra = m.data1 ) n'), function ($join) {
            $join->on('T_WEB_Articoli.IdTipoFormato', '=', 'n.IdTipoFormato');
        })
        /*
    ->leftJoin(DB::raw('(SELECT o.Codice, o.QtaDisponibile FROM T_WEB_Disponibile o JOIN (SELECT Codice, MAX(DataOra) as data1 from T_WEB_Disponibile GROUP BY Codice) p ON o.Codice = p.Codice AND o.DataOra = p.data1 ) q'), function($join) {
        $join->on('T_WEB_Articoli.IdArticolo', '=', 'q.Codice');
    })
    */
        ->where('DescrizioneTipologia', 'LIKE', 'Video Streaming')
        ->get();
    //$articolo = Article::find($id);
    //$article = Article::where('IdArticolo',)->whereDate('DataOra',$articolo->data)->first();
    //dd($articles);
    //dd($articles[0]);
    ob_implicit_flush(true);
    //dd($articles);
    foreach ($articles as $article) {
        echo $article->IdArticolo . " | " . $article->Titolo . " | " . $article->DescrizioneStatoProdotto . " | " . $article->DescrizioneTipologia . " | " .  $article->DescrizioneFormato . " | " . $article->QtaDisponibile . " | " . $article->data . "<br>";
    }
});
Route::get('statoProdotto', function () {
    $subQuery = DB::table('T_WEB_StatiProdotto')->select('IdStatoProdotto', DB::raw('max(DataOra) as data'))
        ->groupBy('IdStatoProdotto');
    $stati = DB::table(DB::raw('(' . $subQuery->toSql() . ') as c1'))
        ->select('*')
        ->join('T_WEB_StatiProdotto as c2', function ($join) {
            $join->on('c1.IdStatoProdotto', '=', 'c2.IdStatoProdotto')->On('c1.data', '=', 'DataOra');
        })
        //->whereNotNull('descrizione')
        ->mergeBindings($subQuery)
        ->orderBy('c1.IdStatoProdotto')
        ->get();
    echo "IdStatoProdotto | Descrizione<br>";
    foreach ($stati as $stato) {
        echo $stato->IdStatoProdotto . " " . $stato->Descrizione . "<br>";
    }
});
Route::get('cliente/{id}', function ($id) {
    $customer = Customer::find($id);
    dd($customer);
});

Route::get('cliente1/{id}', function ($id) {
    $customer = Customer::find($id);
    dd($customer['billing']->first_name);
    $metas = $customer['meta_data'];

    foreach ($metas as $meta) {

        if ($meta->key == 'cod_fiscale') {
            dd($meta->value);
        }
    }
});


Route::get('ordinestato/{id}', function ($id) {
    $ordini = Order::where('IdInternet', $id)->get();
    dd($ordini);
});


Route::get('/commercio', function () {
    set_time_limit(0);
    //$articles = Article::select(DB::raw('count(*) as Totale, DescrizioneFormato'))->join(DB::raw('(SELECT IdArticolo, MAX(DataOra) AS data FROM T_WEB_Articoli GROUP BY IdArticolo) b'), function($join)
    $articles = Article::select(DB::raw('T_WEB_Articoli.IdArticolo, count(*) as Totale'))->join(DB::raw('(SELECT IdArticolo, MAX(DataOra) AS data FROM T_WEB_Articoli GROUP BY IdArticolo) b'), function ($join) {
        $join->on('T_WEB_Articoli.IdArticolo', '=', 'b.IdArticolo')
            ->on('T_WEB_Articoli.DataOra', '=', 'b.data');
    })

        ->leftJoin(DB::raw('(SELECT e.IdStatoProdotto, e.Descrizione as DescrizioneStatoProdotto FROM T_WEB_StatiProdotto e JOIN (SELECT IdStatoProdotto, MAX(DataOra) as data1 from T_WEB_StatiProdotto GROUP BY IdStatoProdotto) c ON e.IdStatoProdotto = c.IdStatoProdotto AND e.DataOra = c.data1 ) f'), function ($join) {
            $join->on('T_WEB_Articoli.IdStatoProdotto', '=', 'f.IdStatoProdotto');
        })
        ->leftJoin(DB::raw('(SELECT g.IdTipologia, g.Descrizione as DescrizioneTipologia FROM T_WEB_Tipologie g JOIN (SELECT IdTipologia, MAX(DataOra) as data1 from T_WEB_Tipologie GROUP BY IdTipologia) h ON g.IdTipologia = h.IdTipologia AND g.DataOra = h.data1 ) i'), function ($join) {
            $join->on('T_WEB_Articoli.IdTipologia', '=', 'i.IdTipologia');
        })
        ->leftJoin(DB::raw('(SELECT l.IdTipoFormato, l.Descrizione as DescrizioneFormato FROM T_WEB_TipiFormato l JOIN (SELECT IdTipoFormato, MAX(DataOra) as data1 from T_WEB_TipiFormato GROUP BY IdTipoFormato) m ON l.IdTipoFormato = m.IdTipoFormato AND l.DataOra = m.data1 ) n'), function ($join) {
            $join->on('T_WEB_Articoli.IdTipoFormato', '=', 'n.IdTipoFormato');
        })
        ->where('DescrizioneStatoProdotto', 'In commercio')
        ->where('DescrizioneTipologia', 'Libri')
        //->where('DescrizioneFormato','Rilegato')
        ->groupBy('T_WEB_Articoli.IdArticolo')
        //->orderBy('T_WEB_Articoli.Titolo')
        ->get();
    /*
    foreach($articles as $article)
    {
        if($article->DescrizioneFormato != '')
         echo $article->DescrizioneFormato . ' : ' .$article->Totale . '<br>';
    }*/
    foreach ($articles as $article) {
        if ($article->Totale > 1)
            echo $article->IdArticolo . ' : ' . $article->Totale . '<br>';
    }
});

Route::get('variazione/{id1}/{id2}', function ($id1, $id2) {
    $variation = Variation::find($id1, $id2)->toArray();
    dd($variation);
});

Route::get('/tipologia', function () {
    $subQuery = DB::table('T_WEB_Tipologie')->select('IdTipologia', DB::raw('max(DataOra) as data'))
        ->groupBy('IdTipologia');

    $tipologie = DB::table(DB::raw('(' . $subQuery->toSql() . ') as c1'))
        ->select('*')
        ->join('T_WEB_Tipologie as c2', function ($join) {
            $join->on('c1.IdTipologia', '=', 'c2.IdTipologia')->On('c1.data', '=', 'DataOra');
        })
        //->whereNotNull('descrizione')
        ->mergeBindings($subQuery)
        ->orderBy('Descrizione')
        ->get();
    foreach ($tipologie as $tipologia) {
        echo $tipologia->Descrizione . "<br>";
    }
});

Route::get('/formato', function () {
    $subQuery = DB::table('T_WEB_TipiFormato')->select('IdTipoFormato', DB::raw('max(DataOra) as data'))
        ->groupBy('IdTipoFormato');

    $tipologie = DB::table(DB::raw('(' . $subQuery->toSql() . ') as c1'))
        ->select('*')
        ->join('T_WEB_TipiFormato as c2', function ($join) {
            $join->on('c1.IdTipoFormato', '=', 'c2.IdTipoFormato')->On('c1.data', '=', 'DataOra');
        })
        //->whereNotNull('descrizione')
        ->mergeBindings($subQuery)
        ->orderBy('Descrizione')
        ->get();
    foreach ($tipologie as $tipologia) {
        echo $tipologia->Descrizione . "<br>";
    }
});



Route::get('/sistema_campi', function () {
    set_time_limit(0);

    $page = 1;

    $all_products = new Collection();
    do {

        $products = Product::all($options = ['per_page' => 100, 'page' => $page]);

        //$filtered = $products->where('type');

        $all_products = $all_products->merge($products);
        $page++;
    } while ($products->count() > 0);
    ob_end_flush();
    ob_implicit_flush(true);
    echo "Totale prodotti padri: " . $all_products->count() . "<br>";
    foreach ($all_products as $key => $product) {
        echo $key . " - Sto processando " . $product->name . "<br>";
        $metadatas_old = $product->meta_data;
        $variations = Variation::all($product->id);
        foreach ($variations as $variation) {

            $metadata = [];
            foreach ($metadatas_old as  $key => $value) {
                if ($value->key == 'pagine') {
                    $metadata[] = [
                        'key' => 'pagine',
                        'value' => $value->value

                    ];
                }
                if ($value->key == 'misure') {
                    $metadata[] = [
                        'key' => 'misure',
                        'value' => $value->value

                    ];
                }
                if ($value->key == 'formato') {
                    $metadata[] = [
                        'key' => 'formato',
                        'value' => $value->value

                    ];
                }
                if ($value->key == 'edizione') {
                    $metadata[] = [
                        'key' => 'edizione',
                        'value' => $value->value

                    ];
                }
            }
            $data1 = [
                'meta_data' => $metadata
            ];

            $variation = Variation::update($product->id, $variation->id, $data1);
        }
    }
    echo "finito";
});

Route::get('/test8', function () {
    $product = Product::find(24006);
    $attributes = $product['attributes'];
    foreach ($attributes as $key => $attribute) {
        echo $attribute->name . "<br>";
    }
});


Route::get('/artlibro1', function () {
    set_time_limit(0);
    $articles = Article::join(DB::raw('(SELECT IdArticolo, MAX(DataOra) AS data FROM T_WEB_Articoli GROUP BY IdArticolo) b'), function ($join) {
        $join->on('T_WEB_Articoli.IdArticolo', '=', 'b.IdArticolo')
            ->on('T_WEB_Articoli.DataOra', '=', 'b.data');
    })

        ->leftJoin(DB::raw('(SELECT e.IdStatoProdotto, e.Descrizione as DescrizioneStatoProdotto FROM T_WEB_StatiProdotto e JOIN (SELECT IdStatoProdotto, MAX(DataOra) as data1 from T_WEB_StatiProdotto GROUP BY IdStatoProdotto) c ON e.IdStatoProdotto = c.IdStatoProdotto AND e.DataOra = c.data1 ) f'), function ($join) {
            $join->on('T_WEB_Articoli.IdStatoProdotto', '=', 'f.IdStatoProdotto');
        })
        ->leftJoin(DB::raw('(SELECT g.IdTipologia, g.Descrizione as DescrizioneTipologia FROM T_WEB_Tipologie g JOIN (SELECT IdTipologia, MAX(DataOra) as data1 from T_WEB_Tipologie GROUP BY IdTipologia) h ON g.IdTipologia = h.IdTipologia AND g.DataOra = h.data1 ) i'), function ($join) {
            $join->on('T_WEB_Articoli.IdTipologia', '=', 'i.IdTipologia');
        })

        ->leftJoin(DB::raw('(SELECT l.IdTipoFormato, l.Descrizione as DescrizioneFormato FROM T_WEB_TipiFormato l JOIN (SELECT IdTipoFormato, MAX(DataOra) as data1 from T_WEB_TipiFormato GROUP BY IdTipoFormato) m ON l.IdTipoFormato = m.IdTipoFormato AND l.DataOra = m.data1 ) n'), function ($join) {
            $join->on('T_WEB_Articoli.IdTipoFormato', '=', 'n.IdTipoFormato');
        })

        /*
    ->leftJoin(DB::raw('(SELECT o.Codice, o.QtaDisponibile FROM T_WEB_Disponibile o JOIN (SELECT Codice, MAX(DataOra) as data1 from T_WEB_Disponibile GROUP BY Codice) p ON o.Codice = p.Codice AND o.DataOra = p.data1 ) q'), function($join) {
        $join->on('T_WEB_Articoli.IdArticolo', '=', 'q.Codice');
    })
    */
        //->groupBy('T_WEB_Articoli.IdArticolo')
        ->where('DescrizioneStatoProdotto', 'In commercio')
        //->where(function($query){
        //    $query->where('DescrizioneStatoProdotto','Usato')
        //->orWhere('DescrizioneStatoProdotto','In Commercio')
        //->orWhere('DescrizioneStatoProdotto','Remainder');
        //})
        //->where(DB::raw('CONVERT(INT, QtaDisponibile)'),'>',0)
        //->where('DescrizioneFormato','brossura')
        ->where('DescrizioneTipologia', 'Dvd')
        ->orderBy('Titolo')
        ->orderBy('DescrizioneTipologia')

        //->take(5)
        //->orderBy('ListaAutori')
        ->get();
    /*
    ->chunk(100, function ($articles) {
        foreach($articles as $article){
            echo $article->Id.' '. $article->IdArticolo. ' '. $article->Titolo .' '. $article->DescrizioneStatoProdotto. ' ' . $article->DescrizioneFormato .'<br>';
        }

    });
    */
    //dd($articles);
    ob_end_flush();
    ob_implicit_flush(true);
    echo "Trovati " . $articles->count() . "<br>";
    foreach ($articles as $key => $article) {
        $titolo = null;
        //$formato = null;
        $prodotti = null;
        echo $key . ' | ' . $article->Titolo . ' | ' . implode(" ", $article->authors) . $article->DescrizioneFormato . ' |' . $article->DescrizioneTipologia . "<br>";
        $titolo = rtrim($article->Titolo);
        $titolo = rtrim(str_ireplace('DVD', '', $titolo));
        $titolo = rtrim($titolo);
        $titolo = rtrim(str_ireplace('_', '', $titolo));
        $titolo = rtrim($titolo);
        $titolo = rtrim($titolo, '-');
        $titolo = rtrim($titolo);
        $titolo = rtrim($titolo, '_');
        $titolo = rtrim($titolo);
        echo $titolo . '<br>';
        $prodotti = new ModelsProduct();
        $prodotti = $prodotti->where('name', $titolo)->get();
        if (!is_null($prodotti) && $prodotti->count() > 0) {

            foreach ($prodotti as $prodotto) {

                if (strtolower($prodotto->name) === strtolower($titolo)) {
                    echo "Trovato titolo" . "<br>";
                    //$found_key = array_search('Autore libro', array_column($prodotto->attributes, 'name'));
                    //dd($prodotto->attributes[$found_key]->options);

                }
            }
            echo "---------------------------------------------------------------------" . "<br>";
        }
    }
});

Route::get('/artlibro2', function () {
    set_time_limit(0);
    $articles = Article::join(DB::raw('(SELECT IdArticolo, MAX(DataOra) AS data FROM T_WEB_Articoli GROUP BY IdArticolo) b'), function ($join) {
        $join->on('T_WEB_Articoli.IdArticolo', '=', 'b.IdArticolo')
            ->on('T_WEB_Articoli.DataOra', '=', 'b.data');
    })

        ->leftJoin(DB::raw('(SELECT e.IdStatoProdotto, e.Descrizione as DescrizioneStatoProdotto FROM T_WEB_StatiProdotto e JOIN (SELECT IdStatoProdotto, MAX(DataOra) as data1 from T_WEB_StatiProdotto GROUP BY IdStatoProdotto) c ON e.IdStatoProdotto = c.IdStatoProdotto AND e.DataOra = c.data1 ) f'), function ($join) {
            $join->on('T_WEB_Articoli.IdStatoProdotto', '=', 'f.IdStatoProdotto');
        })
        ->leftJoin(DB::raw('(SELECT g.IdTipologia, g.Descrizione as DescrizioneTipologia FROM T_WEB_Tipologie g JOIN (SELECT IdTipologia, MAX(DataOra) as data1 from T_WEB_Tipologie GROUP BY IdTipologia) h ON g.IdTipologia = h.IdTipologia AND g.DataOra = h.data1 ) i'), function ($join) {
            $join->on('T_WEB_Articoli.IdTipologia', '=', 'i.IdTipologia');
        })

        ->leftJoin(DB::raw('(SELECT l.IdTipoFormato, l.Descrizione as DescrizioneFormato FROM T_WEB_TipiFormato l JOIN (SELECT IdTipoFormato, MAX(DataOra) as data1 from T_WEB_TipiFormato GROUP BY IdTipoFormato) m ON l.IdTipoFormato = m.IdTipoFormato AND l.DataOra = m.data1 ) n'), function ($join) {
            $join->on('T_WEB_Articoli.IdTipoFormato', '=', 'n.IdTipoFormato');
        })

        /*
    ->leftJoin(DB::raw('(SELECT o.Codice, o.QtaDisponibile FROM T_WEB_Disponibile o JOIN (SELECT Codice, MAX(DataOra) as data1 from T_WEB_Disponibile GROUP BY Codice) p ON o.Codice = p.Codice AND o.DataOra = p.data1 ) q'), function($join) {
        $join->on('T_WEB_Articoli.IdArticolo', '=', 'q.Codice');
    })
    */
        //->groupBy('T_WEB_Articoli.IdArticolo')
        ->where('DescrizioneStatoProdotto', 'In commercio')
        //->where(function($query){
        //    $query->where('DescrizioneStatoProdotto','Usato')
        //->orWhere('DescrizioneStatoProdotto','In Commercio')
        //->orWhere('DescrizioneStatoProdotto','Remainder');
        //})
        //->where(DB::raw('CONVERT(INT, QtaDisponibile)'),'>',0)
        //->where('DescrizioneFormato','brossura')
        ->where('DescrizioneTipologia', 'E-Book')
        ->orderBy('Titolo')
        ->orderBy('DescrizioneTipologia')

        //->take(5)
        //->orderBy('ListaAutori')
        ->get();
    /*
    ->chunk(100, function ($articles) {
        foreach($articles as $article){
            echo $article->Id.' '. $article->IdArticolo. ' '. $article->Titolo .' '. $article->DescrizioneStatoProdotto. ' ' . $article->DescrizioneFormato .'<br>';
        }

    });
    */
    //dd($articles);
    ob_implicit_flush(true);
    foreach ($articles as $key => $article) {
        $titolo = null;
        $formato = null;
        $prodotti = null;
        if ($article->DescrizioneFormato === 'Epub') {


            $titolo = rtrim(str_ireplace('EPUB', '', $article->Titolo));
        } elseif ($article->DescrizioneFormato === 'Pdf') {
            $titolo = rtrim(str_ireplace('PDF', '', $article->Titolo));
        } elseif ($article->DescrizioneFormato === 'Mobi') {
            $titolo = rtrim(str_ireplace('MOBI', '', $article->Titolo));
        } else {
            continue;
        }
        $titolo = rtrim($titolo);
        $titolo = rtrim(str_ireplace('EBOOK', '', $titolo));
        $titolo = rtrim($titolo);
        $titolo = rtrim(str_ireplace('_', '', $titolo));
        $titolo = rtrim($titolo);
        $titolo = rtrim($titolo, '-');
        $titolo = rtrim($titolo);
        $titolo = rtrim($titolo, '_');
        $titolo = rtrim($titolo);


        echo $key . ' | ' . $article->Titolo . ' | ' . $titolo . ' | ' . $article->DescrizioneFormato . "<br>";
    }
});
Route::get('/infophp', function () {
    phpinfo();
});

Route::get('/testnimaia', function () {
    $file = env('WOOCOMMERCE_STORE_URL') . 'wp-content/uploads/web/y/yogasana.jpg';
    $file_headers = @get_headers($file);
    //dd($file_headers);
    if ($file_headers[0] == 'HTTP/1.1 404 Not Found' || $file_headers[0] == 'HTTP/1.1 301 Moved Permanently') {
        echo "not found";
    } else {

        echo  "found";
    }
});

Route::get('/move/{id1}/{id2}', function ($id1, $id2) {
    $variazione = Variation::find(85, $id1)->toArray();

    dd($variazione);
    Variation::create($id2, $variazione);
});

Route::get('/test9/{name}', function ($name) {
    $products = Product::where('name', $name)->get();
    dd($products);
});


Route::post('/updatecreate', function (Request $request) {

    //dd($webhook);


    if (($request->status == 'on-hold'  && $request->payment_method == 'bacs') || ($request->status == 'processing' && $request->payment_method == 'wc_gateway_gestpay') || ($request->status == 'processing' && $request->payment_method == 'paypal')) {
        $changedest = false;
        if (($request->shipping['address_1'] != null && $request->shipping['address_1'] != '' &&   $request->shipping['address_1']  != $request->billing['address_1']) || ($request->shipping['first_name'] != null && $request->shipping['first_name'] != '' && $request->shipping['first_name'] != $request->billing['first_name'])) {
            $changedest = true;
        }
        //$orderold =
        $order = new Order();
        $order->IdInternet = $request->id;
        $order->CodClienteInternet = $request->customer_id;
        $order->Enabled = 1;
        $order->DataOra = $request->date_created;
        $order->Note = $request->customer_note;
        $order->Totale = $request->total;
        if ($request->payment_method == 'wc_gateway_gestpay') {
            $order->CodPagamentoGM = 'CARTASELLA';
        }
        if ($request->payment_method == 'paypal') {
            $order->CodPagamentoGM = '472';
        }
        if ($request->payment_method == 'bacs') {
            $order->CodPagamentoGM = 'BONIFPOSTALE';
            $order->FlagSospeso = 1;
        }
        $order->Spedizioniere = 'GLS';
        $order->ImportoSpedizione = $request->shipping_total;

        if ($changedest) {
            $order->CodDestInternet = $request->customer_id;
        }
        $order->save();

        $prodotti = $request->line_items;
        foreach ($prodotti as $prodotto) {
            $orderdetail = new Orderdetail();
            $orderdetail->IdInternet = $request->id;
            $orderdetail->CodArticoloGM = $prodotto['sku'];
            $orderdetail->Qta = $prodotto['quantity'];
            $orderdetail->PrezzoLordo = $prodotto['total'];
            $orderdetail->Enabled = 1;
            $orderdetail->DataOra = $request->date_created;
            $orderdetail->save();
        }

        $customer = Customer::find($request->customer_id);
        $cliente = new Clientegm();
        $cliente->CodClienteInternet = $customer['id'];
        $cliente->Nominativo = $customer['last_name'] . " " . $customer['first_name'];
        $cliente->Indirizzo = $customer['billing']->address_1 . " " . $customer['billing']->address_2;
        $cliente->Citta = $customer['billing']->city;
        $cliente->Cap = $customer['billing']->postcode;
        $cliente->Provincia = $customer['billing']->state;
        $cliente->Telefono = $customer['billing']->phone;
        $cliente->Email = $customer['billing']->email;
        $cliente->IdNazione = 227;
        $metas = $customer['meta_data'];
        foreach ($metas as $meta) {

            if ($meta->key == 'cod_fiscale') {
                $cliente->CodiceFiscale = $meta->value;
            } elseif ($meta->key == 'vat') {
                $cliente->PIVA = $meta->value;
            }
        }
        $cliente->IdInternet = $request->id;
        $cliente->save();

        if ($changedest) {
            $clientedest = new Clientegmdest();
            $clientedest->CodDestInternet = $request->customer_id;
            $clientedest->Nominativo = $request->shipping['last_name'] . " " . $request->shipping['first_name'];
            $clientedest->Indirizzo = $request->shipping['address_1'] . " " . $request->shipping['address_2'];
            $clientedest->Citta = $request->shipping['city'];
            $clientedest->Cap = $request->shipping['postcode'];
            $clientedest->Provincia = $request->shipping['state'];
            $clientedest->Telefono = $request->shipping['phone'];
            $cliente->IdNazione = 227;
            $clientedest->IdInternet = $request->id;
            $clientedest->save();
        }
        Log::debug($request->all());
        Log::info('Inserito ordine');
    } //end if status








});


Route::get('/artlibroondemand', function () {
    set_time_limit(0);
    ob_implicit_flush(true);
    $articles = Article::join(DB::raw('(SELECT IdArticolo, MAX(DataOra) AS data FROM T_WEB_Articoli GROUP BY IdArticolo) b'), function ($join) {
        $join->on('T_WEB_Articoli.IdArticolo', '=', 'b.IdArticolo')
            ->on('T_WEB_Articoli.DataOra', '=', 'b.data');
    })

        ->leftJoin(DB::raw('(SELECT e.IdStatoProdotto, e.Descrizione as DescrizioneStatoProdotto FROM T_WEB_StatiProdotto e JOIN (SELECT IdStatoProdotto, MAX(DataOra) as data1 from T_WEB_StatiProdotto GROUP BY IdStatoProdotto) c ON e.IdStatoProdotto = c.IdStatoProdotto AND e.DataOra = c.data1 ) f'), function ($join) {
            $join->on('T_WEB_Articoli.IdStatoProdotto', '=', 'f.IdStatoProdotto');
        })
        ->leftJoin(DB::raw('(SELECT g.IdTipologia, g.Descrizione as DescrizioneTipologia FROM T_WEB_Tipologie g JOIN (SELECT IdTipologia, MAX(DataOra) as data1 from T_WEB_Tipologie GROUP BY IdTipologia) h ON g.IdTipologia = h.IdTipologia AND g.DataOra = h.data1 ) i'), function ($join) {
            $join->on('T_WEB_Articoli.IdTipologia', '=', 'i.IdTipologia');
        })
        ->leftJoin(DB::raw('(SELECT l.IdTipoFormato, l.Descrizione as DescrizioneFormato FROM T_WEB_TipiFormato l JOIN (SELECT IdTipoFormato, MAX(DataOra) as data1 from T_WEB_TipiFormato GROUP BY IdTipoFormato) m ON l.IdTipoFormato = m.IdTipoFormato AND l.DataOra = m.data1 ) n'), function ($join) {
            $join->on('T_WEB_Articoli.IdTipoFormato', '=', 'n.IdTipoFormato');
        })
        /*
    ->leftJoin(DB::raw('(SELECT o.Codice, o.QtaDisponibile FROM T_WEB_Disponibile o JOIN (SELECT Codice, MAX(DataOra) as data1 from T_WEB_Disponibile GROUP BY Codice) p ON o.Codice = p.Codice AND o.DataOra = p.data1 ) q'), function($join) {
        $join->on('T_WEB_Articoli.IdArticolo', '=', 'q.Codice');
    })
    */

        //->groupBy('T_WEB_Articoli.IdArticolo')
        ->where('DescrizioneStatoProdotto', 'In commercio')
        //->where(function($query){
        //    $query->where('DescrizioneStatoProdotto','Usato')
        //->orWhere('DescrizioneStatoProdotto','In Commercio')
        //->orWhere('DescrizioneStatoProdotto','Remainder');
        //})
        //->where(DB::raw('CONVERT(INT, QtaDisponibile)'),'>',0)
        //->where('DescrizioneFormato','Epub')
        ->where('DescrizioneTipologia', 'Video On Demand')
        ->orderBy('Titolo')

        //->take(5)
        //->orderBy('ListaAutori')
        ->get();
    /*
    ->chunk(100, function ($articles) {
        foreach($articles as $article){
            echo $article->Id.' '. $article->IdArticolo. ' '. $article->Titolo .' '. $article->DescrizioneStatoProdotto. ' ' . $article->DescrizioneFormato .'<br>';
        }

    });
    */
    //dd($articles);
    ob_end_flush();
    ob_implicit_flush(true);
    echo "Trovati " . $articles->count() . "<br>";
    foreach ($articles as $key => $article) {
        echo $key . " - Sto proccessando " . $article->Titolo . "<br>";
        $titolo = null;
        $formato = null;
        $prodotti = null;

        if ($article->DescrizioneFormato === 'Streaming') {


            $titolo = rtrim($article->Titolo, 'STR');
            $titolo = rtrim(str_ireplace('streaming', '', $titolo));
            $formato = 'Streaming';
        } elseif ($article->DescrizioneFormato === 'Download') {
            $titolo = rtrim($article->Titolo, 'VOD');
            $titolo = rtrim(str_ireplace('download', '', $titolo));
            $formato = 'Download';
        } else {
            continue;
        }


        $titolo = rtrim($titolo);

        $titolo = rtrim(str_ireplace('_', '', $titolo));
        $titolo = rtrim($titolo);
        $titolo = rtrim($titolo, '-');
        $titolo = rtrim($titolo);
        $titolo = rtrim($titolo, '_');
        $titolo = rtrim($titolo);
        echo "Titolo sistemato: " . $titolo . "<br>";
        $prodotti = new ModelsProduct();
        $prodotti = $prodotti->where('name', $titolo)->get();

        /*
        echo $article->Id.' '. $article->IdArticolo. ' '. $article->Ean13 . ' '. $article->Titolo .' '. implode(",",$article->authors) .' ' . $article->DescrizioneStatoProdotto. ' ' . $article->DescrizioneFormato . ' ' .$article->QtaDisponibile . '<br>';
        */
        $id = 0;
        if (!is_null($prodotti) && $prodotti->count() > 0) {
            echo "Cerco titoli" . "<br>";
            foreach ($prodotti as $prodotto) {
                echo "WOO: " .  $prodotto->name . "<br>";
                echo "Cerco : " . $titolo . "<br>";
                if (strtolower($prodotto->name) === strtolower($titolo)) {
                    echo "Trovato titolo uguale" . "<br>";
                    $found_key = array_search('Autore libro', array_column($prodotto->attributes, 'name'));
                    echo implode(",", $prodotto->attributes[$found_key]->options) . '|' . implode(",", $article->authors) . "<br>";
                    print_r(array_diff($prodotto->attributes[$found_key]->options, $article->authors));
                    echo "<br>";
                    print_r(array_diff($article->authors, $prodotto->attributes[$found_key]->options));
                    echo "<br>";
                    if (array_diff($prodotto->attributes[$found_key]->options, $article->authors) === array_diff($article->authors, $prodotto->attributes[$found_key]->options)) {

                        $id = $prodotto->id;
                        echo "id = " . $id . "<br>";
                    }
                }
            }
        }

        if ($id  > 0) {
            //$sku = Product::where('sku',$article->IdArticolo)->first();
            echo "Trovato " . $titolo . "<br>";
            $product = Product::find($id);
            $old_attributes = $product['attributes'];
            $attributes = [];
            foreach ($old_attributes as $old_attribute) {
                if ($old_attribute->id <> 6) {

                    $attributes[] = [
                        'id' => $old_attribute->id,
                        'variation' => $old_attribute->variation,
                        'visible' => $old_attribute->visible,
                        'options' => $old_attribute->options
                    ];
                }
            }

            $attributes[] =  [
                //'id' => 1,
                'id' => 6,
                'position' => 0,
                'visible' => true,
                'variation' => true,
                'options' => [
                    'Nuovo',
                    'Usato',
                    'PDF',
                    'Epub',
                    'Mobi',
                    'DVD',
                    'Streaming',
                    'Download'
                ]
            ];
            //dd($attributes);

            $data = [

                'attributes' => $attributes


            ];
            Product::update($id, $data);


            $variations = Variation::all($id);
            $trovatosku = false;
            foreach ($variations as $variation) {

                if ($variation->sku == $article->IdProdotto) {
                    $trovatosku = true;
                    break;
                }
            }
            if (!$trovatosku) {
                echo "&nbsp;&nbsp;&nbsp;&nbsp;Aggiunto " . $article->Titolo . "<br>";
                $data1 = [

                    'regular_price' => $article->PrezzoIvato,
                    'sku' => $article->IdArticolo,
                    'sale_price' => $article->PrezzoIvatoScontatoCampagna,
                    'date_on_sale_from' => $article->DataInizioCampagna,
                    'date_on_sale_to' => $article->DataFineCampagna,
                    //'manage_stock' => true,
                    //'stock_quantity' => $article->stock,

                    'attributes' => [
                        [
                            'id' => 6,
                            'option' => $formato
                        ]

                    ],
                    'meta_data' => [
                        [
                            'key' => 'ISBN',
                            'value' => $article->Ean13
                        ],
                        [
                            'key' => 'misure',
                            'value' => $article->Misure
                        ],
                        [
                            'key' => 'formato',
                            'value' => $article->DescrizioneFormato
                        ],
                        [
                            'key' => 'pagine',
                            'value' => $article->Pagine
                        ],
                        [
                            'key' => 'edizione',
                            'value' => $article->Edizione
                        ],
                    ]
                ];
                Variation::create($id, $data1);
                $newproduct = new Newproduct();
                $newproduct->id_article = $article->IdArticolo;
                $newproduct->save();
            }
        } else {


            $productsku = Product::where('sku', $article->IdArticolo)->first();
            if ($productsku->count() == 0) {
                //$sku = Product::where('sku',$article->IdArticolo)->first();
                echo "Nuovo " . $titolo . "<br>";
                $category = Category::where('name', $article->argomento);
                if ($category->count() > 0) {
                    $categoria = $category->first();
                    $categoriaid = $categoria['id'];
                } else {
                    $categoriaid = 0;
                }



                $data = [

                    'name' => $titolo,
                    'type' => 'variable',
                    'short_description' =>  $article->Sottotitolo,
                    'categories' => [
                        ['id' => $categoriaid]

                    ],

                    'attributes' => [

                        [
                            //'id' => 1,
                            'id' => 6,
                            'position' => 0,
                            'visible' => true,
                            'variation' => true,
                            'options' => [
                                'Nuovo',
                                'Usato',
                                'PDF',
                                'Epub',
                                'Mobi',
                                'DVD',
                                'Streaming',
                                'Download'
                            ]
                        ],

                        [
                            //'id' => 5,
                            'id' => 7,
                            'visible' => true,

                            'options' =>
                            $article->authors


                        ],
                        [
                            //'id' => 2,
                            'id' => 8,
                            'visible' => true,

                            'options' => [
                                $article->editore

                            ]
                        ],
                        [
                            //'id' => 7,
                            'id' => 9,
                            'visible' => true,

                            'options' => [
                                $article->DescrizioneTipologia

                            ]
                        ]
                    ],

                    'default_attributes' => [
                        [
                            //'id' => 1,
                            'id' => 6,
                            'option' => 'Nuovo'
                        ]
                    ],


                    'meta_data' => [
                        [
                            'key' => 'pagine',
                            'value' =>  $article->Pagine
                        ],
                        [
                            'key' => 'edizione',
                            'value' =>  $article->Edizione
                        ],
                        [
                            'key' => 'ristampa',
                            'value' =>  $article->Ristampa
                        ],
                        [
                            'key' => 'misure',
                            'value' =>  $article->Misure
                        ],
                        [
                            'key' => 'isbn',
                            'value' =>  $article->Ean13
                        ],
                        [
                            'key' => 'formato',
                            'value' => $article->DescrizioneFormato
                        ],
                    ]

                ];
                if ($productsku->count() == 0) {
                    $product = Product::create($data);

                    $idprodotto = $product['id'];
                } else {
                    $idprodotto = $productsku['parent_id'];
                    Product::update($idprodotto, $data);
                }

                echo "&nbsp;&nbsp;&nbsp;&nbsp;Aggiunto " . $article->Titolo . "<br>";
                $data1 = [

                    'regular_price' => $article->PrezzoIvato,
                    'sku' => $article->IdArticolo,
                    'sale_price' => $article->PrezzoIvatoScontatoCampagna,
                    'date_on_sale_from' => $article->DataInizioCampagna,
                    'date_on_sale_to' => $article->DataFineCampagna,
                    //'manage_stock' => true,
                    //'stock_quantity' => $article->stock,

                    'attributes' => [
                        [
                            //'id' => 1,
                            'id' => 6,
                            'option' => $formato
                        ]

                    ],
                    'meta_data' => [
                        [
                            'key' => 'ISBN',
                            'value' => $article->Ean13
                        ],
                        [
                            'key' => 'misure',
                            'value' => $article->Misure
                        ],
                        [
                            'key' => 'formato',
                            'value' => $article->DescrizioneFormato
                        ],
                        [
                            'key' => 'pagine',
                            'value' => $article->Pagine
                        ],
                        [
                            'key' => 'edizione',
                            'value' => $article->Edizione
                        ],

                    ]
                ];
                if ($productsku->count() > 0) {
                    $variation = Variation::update($idprodotto, $productsku['id'], $data1);
                } else {
                    $variation = Variation::create($idprodotto, $data1);
                    $newproduct = new Newproduct();
                    $newproduct->id_article = $article->IdArticolo;
                    $newproduct->save();
                }
            }
        }
    }
    echo "Finito";
});

Route::get('/changeversion', function () {
    set_time_limit(0);
    $page = 1;
    $all_products = new Collection();
    do {

        $products = Product::all($options = ['per_page' => 100, 'page' => $page]);


        $all_products = $all_products->merge($products);
        $page++;
    } while ($products->count() > 0);

    foreach ($all_products as $product) {
        if ($product->id > 670) {
            $old_attributes = $product->attributes;
            $variations = Variation::all($product->id);
            foreach ($variations as  $variation) {
                $old_variantion_attributes[$variation->id] = $variation->attributes[0]->option;
            }

            $data = [
                'attributes' => [
                    [
                        'id' => 1,
                        'position' => 0,
                        'visible' => true,
                        'variation' => true,
                        'options' => ['Nuovo', 'Usato']
                    ],

                    [
                        'id' => 5,
                        'visible' => true,

                        'options' =>
                        $old_attributes[1]->options


                    ],
                    [
                        'id' => 2,
                        'visible' => true,

                        'options' =>
                        $old_attributes[2]->options


                    ],
                    [
                        'id' => 7,
                        'visible' => true,

                        'options' =>
                        $old_attributes[3]->options


                    ]

                ],
                'default_attributes' => [
                    [
                        'id' => 1,
                        'option' => 'Nuovo'
                    ]
                ]
            ];
            $product = Product::update($product->id, $data);

            //$variations = Variation::all($product['id']);
            foreach ($variations as $variation) {

                $data1 = [
                    'attributes' => [
                        [
                            'id' => 1,
                            'option' => $old_variantion_attributes[$variation->id]
                        ]
                    ]
                ];
                $variationup = Variation::update($product['id'], $variation->id, $data1);
            }
        }
    }

    echo "Finito";
});

Route::get('/artlibrodvd', function () {
    set_time_limit(0);
    ob_implicit_flush(true);
    $articles = Article::join(DB::raw('(SELECT IdArticolo, MAX(DataOra) AS data FROM T_WEB_Articoli GROUP BY IdArticolo) b'), function ($join) {
        $join->on('T_WEB_Articoli.IdArticolo', '=', 'b.IdArticolo')
            ->on('T_WEB_Articoli.DataOra', '=', 'b.data');
    })

        ->leftJoin(DB::raw('(SELECT e.IdStatoProdotto, e.Descrizione as DescrizioneStatoProdotto FROM T_WEB_StatiProdotto e JOIN (SELECT IdStatoProdotto, MAX(DataOra) as data1 from T_WEB_StatiProdotto GROUP BY IdStatoProdotto) c ON e.IdStatoProdotto = c.IdStatoProdotto AND e.DataOra = c.data1 ) f'), function ($join) {
            $join->on('T_WEB_Articoli.IdStatoProdotto', '=', 'f.IdStatoProdotto');
        })
        ->leftJoin(DB::raw('(SELECT g.IdTipologia, g.Descrizione as DescrizioneTipologia FROM T_WEB_Tipologie g JOIN (SELECT IdTipologia, MAX(DataOra) as data1 from T_WEB_Tipologie GROUP BY IdTipologia) h ON g.IdTipologia = h.IdTipologia AND g.DataOra = h.data1 ) i'), function ($join) {
            $join->on('T_WEB_Articoli.IdTipologia', '=', 'i.IdTipologia');
        })
        ->leftJoin(DB::raw('(SELECT l.IdTipoFormato, l.Descrizione as DescrizioneFormato FROM T_WEB_TipiFormato l JOIN (SELECT IdTipoFormato, MAX(DataOra) as data1 from T_WEB_TipiFormato GROUP BY IdTipoFormato) m ON l.IdTipoFormato = m.IdTipoFormato AND l.DataOra = m.data1 ) n'), function ($join) {
            $join->on('T_WEB_Articoli.IdTipoFormato', '=', 'n.IdTipoFormato');
        })
        ->leftJoin(DB::raw('(SELECT o.Codice, o.QtaDisponibile FROM T_WEB_Disponibile o JOIN (SELECT Codice, MAX(DataOra) as data1 from T_WEB_Disponibile GROUP BY Codice) p ON o.Codice = p.Codice AND o.DataOra = p.data1 ) q'), function ($join) {
            $join->on('T_WEB_Articoli.IdArticolo', '=', 'q.Codice');
        })


        //->groupBy('T_WEB_Articoli.IdArticolo')
        ->where('DescrizioneStatoProdotto', 'In commercio')
        //->where(function($query){
        //    $query->where('DescrizioneStatoProdotto','Usato')
        //->orWhere('DescrizioneStatoProdotto','In Commercio')
        //->orWhere('DescrizioneStatoProdotto','Remainder');
        //})
        //->where(DB::raw('CONVERT(INT, QtaDisponibile)'),'>',0)
        //->where('DescrizioneFormato','Epub')
        ->where('DescrizioneTipologia', 'Dvd')
        ->orderBy('Titolo')

        //->take(5)
        //->orderBy('ListaAutori')
        ->get();
    /*
    ->chunk(100, function ($articles) {
        foreach($articles as $article){
            echo $article->Id.' '. $article->IdArticolo. ' '. $article->Titolo .' '. $article->DescrizioneStatoProdotto. ' ' . $article->DescrizioneFormato .'<br>';
        }

    });
    */
    //dd($articles);
    ob_end_flush();
    ob_implicit_flush(true);
    echo "Trovati " . $articles->count() . "<br>";
    foreach ($articles as $key => $article) {
        echo $key . " - Sto proccessando " . $article->Titolo . "<br>";
        $titolo = null;
        $formato = null;
        $prodotti = null;
        /*
        if($article->DescrizioneFormato === 'Epub'){


            $titolo = rtrim(str_ireplace('EPUB','',$article->Titolo));

            $formato = 'Epub';

        }
        elseif($article->DescrizioneFormato === 'Pdf'){
            $titolo = rtrim(str_ireplace('PDF','',$article->Titolo));

            $formato = 'PDF';

        }
        elseif($article->DescrizioneFormato === 'Mobi'){
            $titolo = rtrim(str_ireplace('MOBI','',$article->Titolo));


            $formato = 'Mobi';

        } else {
            continue;
        }
        */

        $titolo =  $article->Titolo;

        $titolo = rtrim($titolo);
        $titolo = rtrim(str_ireplace('DVD', '', $titolo));
        $titolo = rtrim($titolo);
        $titolo = rtrim(str_ireplace('_', '', $titolo));
        $titolo = rtrim($titolo);
        $titolo = rtrim($titolo, '-');
        $titolo = rtrim($titolo);
        $titolo = rtrim($titolo, '_');
        $titolo = rtrim($titolo);
        echo $titolo . "<br>";
        $prodotti = new ModelsProduct();
        $prodotti = $prodotti->where('name', $titolo)->get();

        /*
        echo $article->Id.' '. $article->IdArticolo. ' '. $article->Ean13 . ' '. $article->Titolo .' '. implode(",",$article->authors) .' ' . $article->DescrizioneStatoProdotto. ' ' . $article->DescrizioneFormato . ' ' .$article->QtaDisponibile . '<br>';
        */
        $id = 0;
        if (!is_null($prodotti) && $prodotti->count() > 0) {
            foreach ($prodotti as $prodotto) {
                echo $prodotto->name . "<br>";
                echo $titolo . "<br>";
                if (strtolower($prodotto->name) === strtolower($titolo)) {
                    $found_key = array_search('Autore libro', array_column($prodotto->attributes, 'name'));
                    if (array_diff($prodotto->attributes[$found_key]->options, $article->authors) === array_diff($article->authors, $prodotto->attributes[$found_key]->options))
                        $id = $prodotto->id;
                }
            }
        }

        if ($id  > 0) {
            //$sku = Product::where('sku',$article->IdArticolo)->first();
            echo "Trovato " . $titolo . "<br>";
            $product = Product::find($id);
            $old_attributes = $product['attributes'];
            $attributes = [];
            foreach ($old_attributes as $old_attribute) {
                if ($old_attribute->id <> 6) {

                    $attributes[] = [
                        'id' => $old_attribute->id,
                        'variation' => $old_attribute->variation,
                        'visible' => $old_attribute->visible,
                        'options' => $old_attribute->options
                    ];
                }
            }

            $attributes[] =  [
                //'id' => 1,
                'id' => 6,
                'position' => 0,
                'visible' => true,
                'variation' => true,
                'options' => [
                    'Nuovo',
                    'Usato',
                    'PDF',
                    'Epub',
                    'Mobi',
                    'DVD',
                    'Streaming',
                    'Download'
                ]
            ];
            //dd($attributes);

            $data = [

                'attributes' => $attributes


            ];
            Product::update($id, $data);


            $variations = Variation::all($id);
            $trovatosku = false;
            foreach ($variations as $variation) {

                if ($variation->sku == $article->IdProdotto) {
                    $trovatosku = true;
                    break;
                }
            }
            if (!$trovatosku) {
                echo "&nbsp;&nbsp;&nbsp;&nbsp;Aggiunto " . $article->Titolo . "<br>";
                $data1 = [

                    'regular_price' => $article->PrezzoIvato,
                    'sku' => $article->IdArticolo,
                    'sale_price' => $article->PrezzoIvatoScontatoCampagna,
                    'date_on_sale_from' => $article->DataInizioCampagna,
                    'date_on_sale_to' => $article->DataFineCampagna,
                    'manage_stock' => true,
                    'stock_quantity' => $article->stock,

                    'attributes' => [
                        [
                            'id' => 6,
                            'option' => 'DVD'
                        ]

                    ],
                    'meta_data' => [
                        [
                            'key' => 'ISBN',
                            'value' => $article->Ean13
                        ],
                        [
                            'key' => 'misure',
                            'value' => $article->Misure
                        ],
                        [
                            'key' => 'formato',
                            'value' => $article->DescrizioneFormato
                        ],
                        [
                            'key' => 'pagine',
                            'value' => $article->Pagine
                        ],
                        [
                            'key' => 'edizione',
                            'value' => $article->Edizione
                        ],
                    ]
                ];
                Variation::create($id, $data1);
                $newproduct = new Newproduct();
                $newproduct->id_article = $article->IdArticolo;
                $newproduct->save();
            }
        } else {


            $productsku = Product::where('sku', $article->IdArticolo)->first();
            if ($productsku->count() == 0) {
                //$sku = Product::where('sku',$article->IdArticolo)->first();
                echo "Nuovo " . $titolo . "<br>";
                $category = Category::where('name', $article->argomento);
                if ($category->count() > 0) {
                    $categoria = $category->first();
                    $categoriaid = $categoria['id'];
                } else {
                    $categoriaid = 0;
                }



                $data = [

                    'name' => $titolo,
                    'type' => 'variable',
                    'short_description' =>  $article->Sottotitolo,
                    'categories' => [
                        ['id' => $categoriaid]

                    ],

                    'attributes' => [

                        [
                            //'id' => 1,
                            'id' => 6,
                            'position' => 0,
                            'visible' => true,
                            'variation' => true,
                            'options' => [
                                'Nuovo',
                                'Usato',
                                'PDF',
                                'Epub',
                                'Mobi',
                                'DVD',
                                'Streaming',
                                'Download'
                            ]
                        ],

                        [
                            //'id' => 5,
                            'id' => 7,
                            'visible' => true,

                            'options' =>
                            $article->authors


                        ],
                        [
                            //'id' => 2,
                            'id' => 8,
                            'visible' => true,

                            'options' => [
                                $article->editore

                            ]
                        ],
                        [
                            //'id' => 7,
                            'id' => 9,
                            'visible' => true,

                            'options' => [
                                $article->DescrizioneTipologia

                            ]
                        ]
                    ],

                    'default_attributes' => [
                        [
                            //'id' => 1,
                            'id' => 6,
                            'option' => 'Nuovo'
                        ]
                    ],


                    'meta_data' => [
                        [
                            'key' => 'pagine',
                            'value' =>  $article->Pagine
                        ],
                        [
                            'key' => 'edizione',
                            'value' =>  $article->Edizione
                        ],
                        [
                            'key' => 'ristampa',
                            'value' =>  $article->Ristampa
                        ],
                        [
                            'key' => 'misure',
                            'value' =>  $article->Misure
                        ],
                        [
                            'key' => 'isbn',
                            'value' =>  $article->Ean13
                        ],
                        [
                            'key' => 'formato',
                            'value' => $article->DescrizioneFormato
                        ],
                    ]

                ];
                if ($productsku->count() == 0) {
                    $product = Product::create($data);

                    $idprodotto = $product['id'];
                } else {
                    $idprodotto = $productsku['parent_id'];
                    Product::update($idprodotto, $data);
                }

                echo "&nbsp;&nbsp;&nbsp;&nbsp;Aggiunto " . $article->Titolo . "<br>";
                $data1 = [

                    'regular_price' => $article->PrezzoIvato,
                    'sku' => $article->IdArticolo,
                    'sale_price' => $article->PrezzoIvatoScontatoCampagna,
                    'date_on_sale_from' => $article->DataInizioCampagna,
                    'date_on_sale_to' => $article->DataFineCampagna,
                    'manage_stock' => true,
                    'stock_quantity' => $article->stock,

                    'attributes' => [
                        [
                            //'id' => 1,
                            'id' => 6,
                            'option' => 'DVD'
                        ]

                    ],
                    'meta_data' => [
                        [
                            'key' => 'ISBN',
                            'value' => $article->Ean13
                        ],
                        [
                            'key' => 'misure',
                            'value' => $article->Misure
                        ],
                        [
                            'key' => 'formato',
                            'value' => $article->DescrizioneFormato
                        ],
                        [
                            'key' => 'pagine',
                            'value' => $article->Pagine
                        ],
                        [
                            'key' => 'edizione',
                            'value' => $article->Edizione
                        ],

                    ]
                ];
                if ($productsku->count() > 0) {
                    $variation = Variation::update($idprodotto, $productsku['id'], $data1);
                } else {
                    $variation = Variation::create($idprodotto, $data1);
                    $newproduct = new Newproduct();
                    $newproduct->id_article = $article->IdArticolo;
                    $newproduct->save();
                }
            }
        }
    }
    echo "Finito";
});

Route::get('/changeversion', function () {
    set_time_limit(0);
    $page = 1;
    $all_products = new Collection();
    do {

        $products = Product::all($options = ['per_page' => 100, 'page' => $page]);


        $all_products = $all_products->merge($products);
        $page++;
    } while ($products->count() > 0);

    foreach ($all_products as $product) {
        if ($product->id > 670) {
            $old_attributes = $product->attributes;
            $variations = Variation::all($product->id);
            foreach ($variations as  $variation) {
                $old_variantion_attributes[$variation->id] = $variation->attributes[0]->option;
            }

            $data = [
                'attributes' => [
                    [
                        'id' => 1,
                        'position' => 0,
                        'visible' => true,
                        'variation' => true,
                        'options' => ['Nuovo', 'Usato']
                    ],

                    [
                        'id' => 5,
                        'visible' => true,

                        'options' =>
                        $old_attributes[1]->options


                    ],
                    [
                        'id' => 2,
                        'visible' => true,

                        'options' =>
                        $old_attributes[2]->options


                    ],
                    [
                        'id' => 7,
                        'visible' => true,

                        'options' =>
                        $old_attributes[3]->options


                    ]

                ],
                'default_attributes' => [
                    [
                        'id' => 1,
                        'option' => 'Nuovo'
                    ]
                ]
            ];
            $product = Product::update($product->id, $data);

            //$variations = Variation::all($product['id']);
            foreach ($variations as $variation) {

                $data1 = [
                    'attributes' => [
                        [
                            'id' => 1,
                            'option' => $old_variantion_attributes[$variation->id]
                        ]
                    ]
                ];
                $variationup = Variation::update($product['id'], $variation->id, $data1);
            }
        }
    }

    echo "Finito";
});


Route::get('/artondemand', function () {
    set_time_limit(0);
    ob_implicit_flush(true);
    $articles = Article::join(DB::raw('(SELECT IdArticolo, MAX(DataOra) AS data FROM T_WEB_Articoli GROUP BY IdArticolo) b'), function ($join) {
        $join->on('T_WEB_Articoli.IdArticolo', '=', 'b.IdArticolo')
            ->on('T_WEB_Articoli.DataOra', '=', 'b.data');
    })

        ->leftJoin(DB::raw('(SELECT e.IdStatoProdotto, e.Descrizione as DescrizioneStatoProdotto FROM T_WEB_StatiProdotto e JOIN (SELECT IdStatoProdotto, MAX(DataOra) as data1 from T_WEB_StatiProdotto GROUP BY IdStatoProdotto) c ON e.IdStatoProdotto = c.IdStatoProdotto AND e.DataOra = c.data1 ) f'), function ($join) {
            $join->on('T_WEB_Articoli.IdStatoProdotto', '=', 'f.IdStatoProdotto');
        })
        ->leftJoin(DB::raw('(SELECT g.IdTipologia, g.Descrizione as DescrizioneTipologia FROM T_WEB_Tipologie g JOIN (SELECT IdTipologia, MAX(DataOra) as data1 from T_WEB_Tipologie GROUP BY IdTipologia) h ON g.IdTipologia = h.IdTipologia AND g.DataOra = h.data1 ) i'), function ($join) {
            $join->on('T_WEB_Articoli.IdTipologia', '=', 'i.IdTipologia');
        })
        ->leftJoin(DB::raw('(SELECT l.IdTipoFormato, l.Descrizione as DescrizioneFormato FROM T_WEB_TipiFormato l JOIN (SELECT IdTipoFormato, MAX(DataOra) as data1 from T_WEB_TipiFormato GROUP BY IdTipoFormato) m ON l.IdTipoFormato = m.IdTipoFormato AND l.DataOra = m.data1 ) n'), function ($join) {
            $join->on('T_WEB_Articoli.IdTipoFormato', '=', 'n.IdTipoFormato');
        })
        /*
    ->leftJoin(DB::raw('(SELECT o.Codice, o.QtaDisponibile FROM T_WEB_Disponibile o JOIN (SELECT Codice, MAX(DataOra) as data1 from T_WEB_Disponibile GROUP BY Codice) p ON o.Codice = p.Codice AND o.DataOra = p.data1 ) q'), function($join) {
        $join->on('T_WEB_Articoli.IdArticolo', '=', 'q.Codice');
    })
    */

        //->groupBy('T_WEB_Articoli.IdArticolo')
        ->where('DescrizioneStatoProdotto', 'In commercio')
        //->where(function($query){
        //    $query->where('DescrizioneStatoProdotto','Usato')
        //->orWhere('DescrizioneStatoProdotto','In Commercio')
        //->orWhere('DescrizioneStatoProdotto','Remainder');
        //})
        //->where(DB::raw('CONVERT(INT, QtaDisponibile)'),'>',0)
        //->where('DescrizioneFormato','Epub')
        ->where('DescrizioneTipologia', 'Video On Demand')
        ->orderBy('Titolo')

        //->take(5)
        //->orderBy('ListaAutori')
        ->get();
    /*
    ->chunk(100, function ($articles) {
        foreach($articles as $article){
            echo $article->Id.' '. $article->IdArticolo. ' '. $article->Titolo .' '. $article->DescrizioneStatoProdotto. ' ' . $article->DescrizioneFormato .'<br>';
        }

    });
    */
    //dd($articles);
    ob_end_flush();
    ob_implicit_flush(true);
    echo "Trovati " . $articles->count() . "<br>";
    foreach ($articles as $key => $article) {
        echo $key . " - Sto proccessando " . $article->Titolo . "<br>";
        $titolo = null;
        $formato = null;
        $prodotti = null;

        if ($article->DescrizioneFormato === 'Streaming') {


            $titolo = rtrim(str_ireplace('STR', '', $article->Titolo));

            $formato = 'Streaming';
        } elseif ($article->DescrizioneFormato === 'Download') {
            $titolo = rtrim(str_ireplace('VOD', '', $article->Titolo));

            $formato = 'Download';
        } else {
            continue;
        }


        $titolo = rtrim($titolo);

        $titolo = rtrim(str_ireplace('_', '', $titolo));
        $titolo = rtrim($titolo);
        $titolo = rtrim($titolo, '-');
        $titolo = rtrim($titolo);
        $titolo = rtrim($titolo, '_');
        $titolo = rtrim($titolo);
        echo $titolo . "<br>";
        $prodotti = new ModelsProduct();
        $prodotti = $prodotti->where('name', $titolo)->get();

        /*
        echo $article->Id.' '. $article->IdArticolo. ' '. $article->Ean13 . ' '. $article->Titolo .' '. implode(",",$article->authors) .' ' . $article->DescrizioneStatoProdotto. ' ' . $article->DescrizioneFormato . ' ' .$article->QtaDisponibile . '<br>';
        */
        $id = 0;
        if (!is_null($prodotti) && $prodotti->count() > 0) {
            foreach ($prodotti as $prodotto) {
                echo $prodotto->name . "<br>";
                echo $titolo . "<br>";
                if (strtolower($prodotto->name) === strtolower($titolo)) {
                    echo "Trovato titolo uguale" . "<br>";
                    $found_key = array_search('Autore libro', array_column($prodotto->attributes, 'name'));
                    echo implode(",", $prodotto->attributes[$found_key]->options) . '|' . implode(",", $article->authors) . "<br>";

                    if (array_diff($prodotto->attributes[$found_key]->options, $article->authors) === array_diff($article->authors, $prodotto->attributes[$found_key]->options))
                        $id = $prodotto->id;
                }
            }
        }

        if ($id  > 0) {
            //$sku = Product::where('sku',$article->IdArticolo)->first();
            echo "Trovato " . $titolo . "<br>";
        } else {


            $productsku = Product::where('sku', $article->IdArticolo)->first();
            if ($productsku->count() == 0) {
                //$sku = Product::where('sku',$article->IdArticolo)->first();
                echo "Nuovo " . $titolo . "<br>";


                echo "&nbsp;&nbsp;&nbsp;&nbsp;Aggiunto " . $article->Titolo . "<br>";
            }
        }
    }
    echo "Finito";
});

Route::get('/changeversion', function () {
    set_time_limit(0);
    $page = 1;
    $all_products = new Collection();
    do {

        $products = Product::all($options = ['per_page' => 100, 'page' => $page]);


        $all_products = $all_products->merge($products);
        $page++;
    } while ($products->count() > 0);

    foreach ($all_products as $product) {
        if ($product->id > 670) {
            $old_attributes = $product->attributes;
            $variations = Variation::all($product->id);
            foreach ($variations as  $variation) {
                $old_variantion_attributes[$variation->id] = $variation->attributes[0]->option;
            }

            $data = [
                'attributes' => [
                    [
                        'id' => 1,
                        'position' => 0,
                        'visible' => true,
                        'variation' => true,
                        'options' => ['Nuovo', 'Usato']
                    ],

                    [
                        'id' => 5,
                        'visible' => true,

                        'options' =>
                        $old_attributes[1]->options


                    ],
                    [
                        'id' => 2,
                        'visible' => true,

                        'options' =>
                        $old_attributes[2]->options


                    ],
                    [
                        'id' => 7,
                        'visible' => true,

                        'options' =>
                        $old_attributes[3]->options


                    ]

                ],
                'default_attributes' => [
                    [
                        'id' => 1,
                        'option' => 'Nuovo'
                    ]
                ]
            ];
            $product = Product::update($product->id, $data);

            //$variations = Variation::all($product['id']);
            foreach ($variations as $variation) {

                $data1 = [
                    'attributes' => [
                        [
                            'id' => 1,
                            'option' => $old_variantion_attributes[$variation->id]
                        ]
                    ]
                ];
                $variationup = Variation::update($product['id'], $variation->id, $data1);
            }
        }
    }

    echo "Finito";
});

Route::get('/appoggio', function () {
    set_time_limit(0);
    ini_set("memory_limit", "512M");
    $page = 1;
    $key = 0;
    $all_products = new Collection();
    ob_end_flush();
    ob_implicit_flush(true);
    do {

        $products = Product::all($options = ['per_page' => 100, 'page' => $page, 'orderby' => 'title', 'order' => 'asc']);

        foreach ($products as $product) {
            echo ++$key . " | " . $product->name . " | "  . $product->id;
            $variations = Variation::all($product->id);
            foreach ($variations as $variation) {
                if (!Gm_product::where('id_gm', $variation->sku)->exists()) {
                    $gmproduct = new Gm_product();
                    $gmproduct->id_gm = $variation->sku;
                    $gmproduct->wc_id = $variation->id;
                    $gmproduct->wc_parentid = $product->id;
                    $gmproduct->save();
                }
            }
            echo "<br>";
        }

        //$all_products = $all_products->merge($products);
        $page++;
    } while ($products->count() > 0);
    //} while ($page == 1);
});



Route::get('/updateproducts', function () {
    set_time_limit(0);
    ini_set("memory_limit", "512M");
    $ora_update = Carbon::now();
    $settingora = Setting::where('key', 'update_products')->first();
    $fromtime = str_replace('-', '', $settingora->value);

    $articles = Article::join(DB::raw('(SELECT IdArticolo, MAX(DataOra) AS data FROM T_WEB_Articoli GROUP BY IdArticolo) b'), function ($join) {
        $join->on('T_WEB_Articoli.IdArticolo', '=', 'b.IdArticolo')
            ->on('T_WEB_Articoli.DataOra', '=', 'b.data');
    })
        ->leftJoin(DB::raw('(SELECT e.IdStatoProdotto, e.Descrizione as DescrizioneStatoProdotto FROM T_WEB_StatiProdotto e JOIN (SELECT IdStatoProdotto, MAX(DataOra) as data1 from T_WEB_StatiProdotto GROUP BY IdStatoProdotto) c ON e.IdStatoProdotto = c.IdStatoProdotto AND e.DataOra = c.data1 ) f'), function ($join) {
            $join->on('T_WEB_Articoli.IdStatoProdotto', '=', 'f.IdStatoProdotto');
        })
        ->leftJoin(DB::raw('(SELECT g.IdTipologia, g.Descrizione as DescrizioneTipologia FROM T_WEB_Tipologie g JOIN (SELECT IdTipologia, MAX(DataOra) as data1 from T_WEB_Tipologie GROUP BY IdTipologia) h ON g.IdTipologia = h.IdTipologia AND g.DataOra = h.data1 ) i'), function ($join) {
            $join->on('T_WEB_Articoli.IdTipologia', '=', 'i.IdTipologia');
        })
        ->leftJoin(DB::raw('(SELECT l.IdTipoFormato, l.Descrizione as DescrizioneFormato FROM T_WEB_TipiFormato l JOIN (SELECT IdTipoFormato, MAX(DataOra) as data1 from T_WEB_TipiFormato GROUP BY IdTipoFormato) m ON l.IdTipoFormato = m.IdTipoFormato AND l.DataOra = m.data1 ) n'), function ($join) {
            $join->on('T_WEB_Articoli.IdTipoFormato', '=', 'n.IdTipoFormato');
        })
        /*
        ->leftJoin(DB::raw('(SELECT o.Codice, o.QtaDisponibile FROM T_WEB_Disponibile o JOIN (SELECT Codice, MAX(DataOra) as data1 from T_WEB_Disponibile GROUP BY Codice) p ON o.Codice = p.Codice AND o.DataOra = p.data1 ) q'), function($join) {
            $join->on('T_WEB_Articoli.IdArticolo', '=', 'q.Codice');
        })
        */

        //->where('T_WEB_Articoli.DataOra','>',$settingora->value)
        ->where('data', '>=', $fromtime)
        ->where(function ($query) {
            $query->where('DescrizioneStatoProdotto', 'In commercio')
                ->orWhere('DescrizioneStatoProdotto', 'Prossima uscita');
        })
        //->where('DescrizioneTipologia','Video Streaming')
        ->orderBy('Titolo')
        ->get();
    ob_end_flush();
    ob_implicit_flush(true);

    foreach ($articles as $article) {
        echo $article->IdArticolo . " - " . $article->Titolo . " - " . $article->DescrizioneTipologia . ' - ' . $article->DescrizioneFormato . ' - ' . $article->DescrizioneStatoProdotto . ' - ' . $article->data . " - " . $article->Id . "<br>";
    }
    /*

        \Log::channel('updateproducts')->notice('Inizio da '.$settingora->value."\n");
        $log = 'PRODOTTI INSERITI'."\n";
        $log1 = 'EVENTUALI PRODOTTI NON INSERITI'."\n";
        $log2 = 'PRODOTTI AGGIORNATI' . "\n";
        $log3 = 'PRODOTTI NON INSERITI PER PROBLEMI SERVER' . "\n";

        foreach($articles as $article )
        { try {
            $productsku = Product::where('sku' , $article->IdArticolo)->first();
            //if(Gm_product::where('id_gm',$article->IdArticolo)->doesntExist())
            if($productsku->count() == 0)
            {






                $titolo = null;
                $formato = null;
                $prodotti = null;
                $prodotti= new ModelsProduct();
                $titolo =  $article->Titolo;
                switch($article->DescrizioneTipologia){

                    case 'Libri':

                        $prodotti = $prodotti->where('name',$titolo)->get();
                        $id = 0;

                        if(!is_null($prodotti) && $prodotti->count() > 0){
                            foreach($prodotti as $prodotto){
                            if(strtolower($prodotto->name) === strtolower($titolo)){
                            $found_key = array_search('Autore libro', array_column($prodotto->attributes, 'name'));
                            if(array_diff($prodotto->attributes[$found_key]->options, $article->authors) === array_diff($article->authors, $prodotto->attributes[$found_key]->options ) )
                            {
                                $id = $prodotto->id;
                                $variations = Variation::all($prodotto->id);
                                foreach ($variations as  $variation) {
                                  $found_key_version = array_search('Versione', array_column($variation->attributes, 'name'));
                                    if($variation->attributes[$found_key_version]->option == 'Nuovo')
                                    {
                                        $id = 0;
                                    }


                                }
                            }

                            }
                          }

                        }
                        $data1 = [

                            'regular_price' => $article->PrezzoIvato,
                            'sku' => $article->IdArticolo,
                            'sale_price' => $article->PrezzoIvatoScontatoCampagna,
                            'date_on_sale_from' => $article->DataInizioCampagna,
                            'date_on_sale_to' => $article->DataFineCampagna,
                            'manage_stock' => true,
                            'stock_quantity' => $article->stock,
                            'purchasable' => false,

                            'attributes' => [
                                [
                                    //'id' => 1,
                                    'id' => 6,
                                    'option' => 'Nuovo'
                                ]

                            ],
                            'meta_data' => [
                                [
                                    'key' => 'ISBN',
                                    'value' => $article->Ean13
                                ],
                                [
                                    'key' => 'misure',
                                    'value' => $article->Misure
                                ],
                                [
                                    'key' => 'formato',
                                    'value' => $article->DescrizioneFormato
                                ],
                                [
                                    'key' => 'pagine',
                                    'value' => $article->Pagine
                                ],
                                [
                                    'key' => 'edizione',
                                    'value' => $article->Edizione
                                ],
                                [
                                    'key' => 'ristampa',
                                    'value' =>  $article->Ristampa
                                ],

                            ]
                        ];
                        if ($id == 0 ){
                            $versione = 'Nuova versione';
                            $category = Category::where('name',$article->argomento);
                            if($category->count() > 0 ) {
                                $categoria = $category->first();
                                $categoriaid =$categoria['id'];
                            } else {
                                $categoriaid = 0;
                            }
                            $data = [

                                'name' => $article->Titolo,
                                'type' => 'variable',
                                'short_description' =>  $article->Sottotitolo,
                                'categories' => [
                                    [ 'id' => $categoriaid ]

                                ],
                                'status' => 'draft',




                                //'description' => 'Simple product full description.',
                                //'short_description' => 'Simple product short description.',


                                'attributes' => [

                                    [
                                        //'id' => 1,
                                        'id' => 6,
                                        'position' => 0,
                                        'visible' => true,
                                        'variation' => true,
                                        'options' => [
                                            'Nuovo',
                                            'Usato',
                                            'PDF',
                                            'Epub',
                                            'Mobi',
                                            'DVD',
                                            'Streaming',
                                            'Download'
                                        ]
                                     ],

                                    [
                                        //'id' => 5,
                                        'id' => 7,
                                        'visible' => true,

                                        'options' =>
                                            $article->authors


                                        ],
                                    [
                                        //'id' => 2,
                                        'id' => 8,
                                        'visible' => true,

                                        'options' => [
                                            $article->editore

                                        ]
                                        ],
                                    [
                                        //'id' => 7,
                                        'id' => 9,
                                        'visible' => true,

                                        'options' => [
                                            $article->DescrizioneTipologia

                                        ]
                                    ]
                                ],

                                'default_attributes' => [
                                    [
                                        //'id' => 1,
                                        'id' => 6,
                                        'option' => 'Nuovo'
                                    ]
                                    ],




                            ];

                            $product = Product::create($data);

                            $idprodotto= $product['id'];


                            $variation = Variation::create($idprodotto, $data1);
                            //dd($variation);



                        }  else {
                            $versione = "Aggiunta versione";
                            $product = Product::find($id);
                            $old_attributes = $product['attributes'];
                            $attributes = [];
                            foreach($old_attributes as $old_attribute)
                            {
                                if($old_attribute->id <> 6)
                                {

                                    $attributes[] = [
                                                    'id' => $old_attribute->id,
                                                    'variation' => $old_attribute->variation,
                                                    'visible' => $old_attribute->visible,
                                                    'options' => $old_attribute->options
                                                    ];
                                }
                            }

                            $attributes[] =  [
                                //'id' => 1,
                                'id' => 6,
                                'position' => 0,
                                'visible' => true,
                                'variation' => true,
                                'options' => [
                                    'Nuovo',
                                    'Usato',
                                    'PDF',
                                    'Epub',
                                    'Mobi',
                                    'DVD',
                                    'Streaming',
                                    'Download'
                                ]
                                ];
                            //dd($attributes);

                            $data = [

                                    'attributes' => $attributes


                                ];
                           Product::update($id, $data);

                           $variation = Variation::create($id, $data1);
                        }
                         echo $article->Titolo . ' - ' . $article->DescrizioneTipologia . ' - ' .$article->DescrizioneFormato . ' - '. $versione . ' - ' . $variation['permalink']. '<br>';
                         $log .= $article->Titolo . ' - ' . $article->DescrizioneTipologia . ' - ' .$article->DescrizioneFormato . ' - '. $versione . ' - ' . $variation['permalink']. "\n";
                         break;

                    case 'E-book':

                        if($article->DescrizioneFormato === 'Epub'){


                            $titolo = rtrim(str_ireplace('EPUB','',$article->Titolo));

                            $formato = 'Epub';

                        }
                        elseif($article->DescrizioneFormato === 'Pdf'){
                            $titolo = rtrim(str_ireplace('PDF','',$article->Titolo));

                            $formato = 'PDF';

                        }
                        elseif($article->DescrizioneFormato === 'Mobi'){
                            $titolo = rtrim(str_ireplace('MOBI','',$article->Titolo));


                            $formato = 'Mobi';

                        } else {
                            $log1 .= $article->Titolo . ' - '. $article->DescrizioneTipologia . ' - ' .$article->DescrizioneFormato . "\n";
                            break;
                        }
                        $titolo = rtrim($titolo);
                        $titolo = rtrim(str_ireplace('EBOOK','',$titolo));
                        $titolo = rtrim($titolo);
                        $titolo = rtrim(str_ireplace('_','',$titolo));
                        $titolo = rtrim($titolo);
                        $titolo = rtrim($titolo,'-');
                        $titolo = rtrim($titolo);
                        $titolo = rtrim($titolo,'_');
                        $titolo = rtrim($titolo);

                        $prodotti = $prodotti->where('name',$titolo)->get();
                        $id = 0;

                        if(!is_null($prodotti) && $prodotti->count() > 0){
                            foreach($prodotti as $prodotto){
                            if(strtolower($prodotto->name) === strtolower($titolo)){
                            $found_key = array_search('Autore libro', array_column($prodotto->attributes, 'name'));
                            if(array_diff($prodotto->attributes[$found_key]->options, $article->authors) === array_diff($article->authors, $prodotto->attributes[$found_key]->options ) )
                            {
                                $id = $prodotto->id;
                                $variations = Variation::all($prodotto->id);
                                foreach ($variations as  $variation) {
                                    $found_key_version = array_search('Versione', array_column($variation->attributes, 'name'));
                                    if($variation->attributes[$found_key_version]->option == $formato)
                                    {
                                        $id = 0;
                                    }


                                }
                            }
                            }
                          }

                        }
                        $data1 = [

                            'regular_price' => $article->PrezzoIvato,
                            'sku' => $article->IdArticolo,
                            'sale_price' => $article->PrezzoIvatoScontatoCampagna,
                            'date_on_sale_from' => $article->DataInizioCampagna,
                            'date_on_sale_to' => $article->DataFineCampagna,
                            //'manage_stock' => true,
                            //'stock_quantity' => $article->stock,
                            'purchasable' => 'false',

                            'attributes' => [
                                [
                                    'id' => 6,
                                    'option' => $formato
                                ]

                            ],
                            'meta_data' => [
                                [
                                    'key' => 'ISBN',
                                    'value' => $article->Ean13
                                ],
                                [
                                    'key' => 'misure',
                                    'value' => $article->Misure
                                ],
                                [
                                    'key' => 'formato',
                                    'value' => $article->DescrizioneFormato
                                ],
                                [
                                    'key' => 'pagine',
                                    'value' => $article->Pagine
                                ],
                                [
                                    'key' => 'edizione',
                                    'value' => $article->Edizione
                                ],
                            ]
                        ];
                        if($id == 0){

                            $versione = 'Nuova versione';

                            $category = Category::where('name',$article->argomento);
                            if($category->count() > 0 ) {
                                $categoria = $category->first();
                                $categoriaid =$categoria['id'];
                            } else {
                                $categoriaid = 0;
                            }

                            $data = [

                                'name' => $titolo,
                                'type' => 'variable',
                                'short_description' =>  $article->Sottotitolo,
                                'categories' => [
                                    [ 'id' => $categoriaid ]

                                ],
                                'status' => 'draft',

                                'attributes' => [

                                    [
                                        //'id' => 1,
                                        'id' => 6,
                                        'position' => 0,
                                        'visible' => true,
                                        'variation' => true,
                                        'options' => [
                                            'Nuovo',
                                            'Usato',
                                            'PDF',
                                            'Epub',
                                            'Mobi',
                                            'DVD',
                                            'Streaming',
                                            'Download'
                                        ]
                                     ],

                                    [
                                        //'id' => 5,
                                        'id' => 7,
                                        'visible' => true,

                                        'options' =>
                                            $article->authors


                                        ],
                                    [
                                        //'id' => 2,
                                        'id' => 8,
                                        'visible' => true,

                                        'options' => [
                                            $article->editore

                                        ]
                                        ],
                                    [
                                        //'id' => 7,
                                        'id' => 9,
                                        'visible' => true,

                                        'options' => [
                                            $article->DescrizioneTipologia

                                        ]
                                    ]
                                ],

                                'default_attributes' => [
                                    [
                                        //'id' => 1,
                                        'id' => 6,
                                        'option' => 'Nuovo'
                                    ]
                                    ],




                            ];

                            $product = Product::create($data);

                            $idprodotto= $product['id'];


                            $variation = Variation::create($idprodotto, $data1);


                        }
                        else {
                            $versione = "Aggiunta versione";
                            $product = Product::find($id);
                            $old_attributes = $product['attributes'];
                            $attributes = [];
                            foreach($old_attributes as $old_attribute)
                            {
                                if($old_attribute->id <> 6)
                                {

                                    $attributes[] = [
                                                    'id' => $old_attribute->id,
                                                    'variation' => $old_attribute->variation,
                                                    'visible' => $old_attribute->visible,
                                                    'options' => $old_attribute->options
                                                    ];
                                }
                            }

                            $attributes[] =  [
                                //'id' => 1,
                                'id' => 6,
                                'position' => 0,
                                'visible' => true,
                                'variation' => true,
                                'options' => [
                                    'Nuovo',
                                    'Usato',
                                    'PDF',
                                    'Epub',
                                    'Mobi',
                                    'DVD',
                                    'Streaming',
                                    'Download'
                                ]
                                ];
                            //dd($attributes);

                            $data = [

                                    'attributes' => $attributes


                                ];
                           Product::update($id, $data);
                           $variation = Variation::create($id, $data1);
                        }
                        echo $article->Titolo . ' - ' . $article->DescrizioneTipologia . ' - ' .$article->DescrizioneFormato . ' - '. $versione .'<br>';
                        $log .= $article->Titolo . ' - ' . $article->DescrizioneTipologia . ' - ' .$article->DescrizioneFormato . ' - '. $versione . ' - ' . $variation['permalink']."\n";
                         break;

                    case 'Dvd':
                        $titolo = rtrim($article->Titolo);
                        $titolo = rtrim(str_ireplace('DVD','',$titolo));
                        $titolo = rtrim($titolo);
                        $titolo = rtrim(str_ireplace('_','',$titolo));
                        $titolo = rtrim($titolo);
                        $titolo = rtrim($titolo,'-');
                        $titolo = rtrim($titolo);
                        $titolo = rtrim($titolo,'_');
                        $titolo = rtrim($titolo);
                        $prodotti = $prodotti->where('name',$titolo)->get();
                        $id = 0;

                        if(!is_null($prodotti) && $prodotti->count() > 0){
                            foreach($prodotti as $prodotto){
                            if(strtolower($prodotto->name) === strtolower($titolo)){
                            $found_key = array_search('Autore libro', array_column($prodotto->attributes, 'name'));
                            if(array_diff($prodotto->attributes[$found_key]->options, $article->authors) === array_diff($article->authors, $prodotto->attributes[$found_key]->options ) )
                            {
                                $id = $prodotto->id;
                                $variations = Variation::all($prodotto->id);
                                foreach ($variations as  $variation) {
                                    $found_key_version = array_search('Versione', array_column($variation->attributes, 'name'));
                                    if($variation->attributes[$found_key_version]->option == 'DVD')
                                    {
                                        $id = 0;
                                    }


                                }
                            }
                            }
                          }

                        }

                        $data1 = [

                            'regular_price' => $article->PrezzoIvato,
                            'sku' => $article->IdArticolo,
                            'sale_price' => $article->PrezzoIvatoScontatoCampagna,
                            'date_on_sale_from' => $article->DataInizioCampagna,
                            'date_on_sale_to' => $article->DataFineCampagna,
                            'manage_stock' => true,
                            'stock_quantity' => $article->stock,
                            'purchasable' => false,

                            'attributes' => [
                                [
                                    'id' => 6,
                                    'option' => 'DVD'
                                ]

                            ],
                            'meta_data' => [
                                [
                                    'key' => 'ISBN',
                                    'value' => $article->Ean13
                                ],
                                [
                                    'key' => 'misure',
                                    'value' => $article->Misure
                                ],
                                [
                                    'key' => 'formato',
                                    'value' => $article->DescrizioneFormato
                                ],
                                [
                                    'key' => 'pagine',
                                    'value' => $article->Pagine
                                ],
                                [
                                    'key' => 'edizione',
                                    'value' => $article->Edizione
                                ],
                            ]
                        ];
                        if ($id == 0){
                            $versione = 'Nuova versione';
                            $category = Category::where('name',$article->argomento);
                            if($category->count() > 0 ) {
                                $categoria = $category->first();
                                $categoriaid =$categoria['id'];
                            } else {
                                $categoriaid = 0;
                            }
                            $data = [

                                'name' => $article->Titolo,
                                'type' => 'variable',
                                'short_description' =>  $article->Sottotitolo,
                                'categories' => [
                                    [ 'id' => $categoriaid ]

                                ],
                                'status' => 'draft',


                                //'description' => 'Simple product full description.',
                                //'short_description' => 'Simple product short description.',


                                'attributes' => [

                                    [
                                        //'id' => 1,
                                        'id' => 6,
                                        'position' => 0,
                                        'visible' => true,
                                        'variation' => true,
                                        'options' => [
                                            'Nuovo',
                                            'Usato',
                                            'PDF',
                                            'Epub',
                                            'Mobi',
                                            'DVD',
                                            'Streaming',
                                            'Download'
                                        ]
                                     ],

                                    [
                                        //'id' => 5,
                                        'id' => 7,
                                        'visible' => true,

                                        'options' =>
                                            $article->authors


                                        ],
                                    [
                                        //'id' => 2,
                                        'id' => 8,
                                        'visible' => true,

                                        'options' => [
                                            $article->editore

                                        ]
                                        ],
                                    [
                                        //'id' => 7,
                                        'id' => 9,
                                        'visible' => true,

                                        'options' => [
                                            $article->DescrizioneTipologia

                                        ]
                                    ]
                                ],

                                'default_attributes' => [
                                    [
                                        //'id' => 1,
                                        'id' => 6,
                                        'option' => 'Nuovo'
                                    ]
                                    ],




                            ];

                            $product = Product::create($data);

                            $idprodotto= $product['id'];


                            $variation = Variation::create($idprodotto, $data1);



                        }  else {
                            $versione = "Aggiunta versione";
                            $product = Product::find($id);
                            $old_attributes = $product['attributes'];
                            $attributes = [];
                            foreach($old_attributes as $old_attribute)
                            {
                                if($old_attribute->id <> 6)
                                {

                                    $attributes[] = [
                                                    'id' => $old_attribute->id,
                                                    'variation' => $old_attribute->variation,
                                                    'visible' => $old_attribute->visible,
                                                    'options' => $old_attribute->options
                                                    ];
                                }
                            }

                            $attributes[] =  [
                                //'id' => 1,
                                'id' => 6,
                                'position' => 0,
                                'visible' => true,
                                'variation' => true,
                                'options' => [
                                    'Nuovo',
                                    'Usato',
                                    'PDF',
                                    'Epub',
                                    'Mobi',
                                    'DVD',
                                    'Streaming',
                                    'Download'
                                ]
                                ];
                            //dd($attributes);

                            $data = [

                                    'attributes' => $attributes


                                ];
                           Product::update($id, $data);

                           $variation = Variation::create($id, $data1);
                        }
                         echo $article->Titolo . ' - ' . $article->DescrizioneTipologia . ' - ' .$article->DescrizioneFormato . ' - '. $versione . ' - ' . $variation['permalink'].'<br>';
                        $log .= $article->Titolo . ' - ' . $article->DescrizioneTipologia . ' - ' .$article->DescrizioneFormato . ' - '. $versione . ' - ' . $variation['permalink']."\n";

                         break;

                    case 'Video Streaming':
                    case 'Video On Demand':
                        if($article->DescrizioneFormato === 'Streaming'){


                            $titolo = rtrim($article->Titolo, 'STR');
                            $titolo = rtrim(str_ireplace('streaming','',$titolo));
                            $formato = 'Streaming';

                        }
                        elseif($article->DescrizioneFormato === 'Download'){
                            $titolo = rtrim($article->Titolo, 'VOD');
                            $titolo = rtrim(str_ireplace('download','',$titolo));
                            $formato = 'Download';

                        }
                        else {
                            $log1 .= $article->Titolo . ' - '. $article->DescrizioneTipologia . ' - ' .$article->DescrizioneFormato . "\n";
                            break;
                        }

                        $titolo = rtrim($titolo);

                        $titolo = rtrim(str_ireplace('_','',$titolo));
                        $titolo = rtrim($titolo);
                        $titolo = rtrim($titolo,'-');
                        $titolo = rtrim($titolo);
                        $titolo = rtrim($titolo,'_');
                        $titolo = rtrim($titolo);

                        $prodotti = $prodotti->where('name',$titolo)->get();
                        $id = 0;
                        if(!is_null($prodotti) && $prodotti->count() > 0){
                            foreach($prodotti as $prodotto){

                            if(strtolower($prodotto->name) === strtolower($titolo)){

                            $found_key = array_search('Autore libro', array_column($prodotto->attributes, 'name'));


                            if(array_diff($prodotto->attributes[$found_key]->options, $article->authors) === array_diff($article->authors, $prodotto->attributes[$found_key]->options ) )
                               {
                            $id = $prodotto->id;
                            $variations = Variation::all($prodotto->id);
                            foreach ($variations as  $variation) {
                                $found_key_version = array_search('Versione', array_column($variation->attributes, 'name'));
                                if($variation->attributes[$found_key_version]->option == $formato)
                                {
                                    $id = 0;
                                }


                            }
                               }
                            }
                          }

                        }

                        $data1 = [

                            'regular_price' => $article->PrezzoIvato,
                            'sku' => $article->IdArticolo,
                            'sale_price' => $article->PrezzoIvatoScontatoCampagna,
                            'date_on_sale_from' => $article->DataInizioCampagna,
                            'date_on_sale_to' => $article->DataFineCampagna,
                            //'manage_stock' => true,
                            //'stock_quantity' => $article->stock,
                            'purchasable' => false,

                            'attributes' => [
                                [
                                    'id' => 6,
                                    'option' => $formato
                                ]

                            ],
                            'meta_data' => [
                                [
                                    'key' => 'ISBN',
                                    'value' => $article->Ean13
                                ],
                                [
                                    'key' => 'misure',
                                    'value' => $article->Misure
                                ],
                                [
                                    'key' => 'formato',
                                    'value' => $article->DescrizioneFormato
                                ],
                                [
                                    'key' => 'pagine',
                                    'value' => $article->Pagine
                                ],
                                [
                                    'key' => 'edizione',
                                    'value' => $article->Edizione
                                ],
                            ]
                        ];
                        if($id == 0)
                        {
                            $versione = 'Nuova versione';
                            $category = Category::where('name',$article->argomento);
                            if($category->count() > 0 ) {
                                $categoria = $category->first();
                                $categoriaid =$categoria['id'];
                            } else {
                                $categoriaid = 0;
                            }

                            $data = [

                                'name' => $titolo,
                                'type' => 'variable',
                                'short_description' =>  $article->Sottotitolo,
                                'categories' => [
                                    [ 'id' => $categoriaid ]

                                ],
                                'status' => 'draft',

                                'attributes' => [

                                    [
                                        //'id' => 1,
                                        'id' => 6,
                                        'position' => 0,
                                        'visible' => true,
                                        'variation' => true,
                                        'options' => [
                                            'Nuovo',
                                            'Usato',
                                            'PDF',
                                            'Epub',
                                            'Mobi',
                                            'DVD',
                                            'Streaming',
                                            'Download'
                                        ]
                                     ],

                                    [
                                        //'id' => 5,
                                        'id' => 7,
                                        'visible' => true,

                                        'options' =>
                                            $article->authors


                                        ],
                                    [
                                        //'id' => 2,
                                        'id' => 8,
                                        'visible' => true,

                                        'options' => [
                                            $article->editore

                                        ]
                                        ],
                                    [
                                        //'id' => 7,
                                        'id' => 9,
                                        'visible' => true,

                                        'options' => [
                                            $article->DescrizioneTipologia

                                        ]
                                    ]
                                ],

                                'default_attributes' => [
                                    [
                                        //'id' => 1,
                                        'id' => 6,
                                        'option' => 'Nuovo'
                                    ]
                                    ],




                            ];

                            $product = Product::create($data);

                            $idprodotto= $product['id'];


                            $variation = Variation::create($idprodotto, $data1);


                        }
                        else {
                            $versione = "Aggiunta versione";
                            $product = Product::find($id);
                            $old_attributes = $product['attributes'];
                            $attributes = [];
                            foreach($old_attributes as $old_attribute)
                            {
                                if($old_attribute->id <> 6)
                                {

                                    $attributes[] = [
                                                    'id' => $old_attribute->id,
                                                    'variation' => $old_attribute->variation,
                                                    'visible' => $old_attribute->visible,
                                                    'options' => $old_attribute->options
                                                    ];
                                }
                            }

                            $attributes[] =  [
                                //'id' => 1,
                                'id' => 6,
                                'position' => 0,
                                'visible' => true,
                                'variation' => true,
                                'options' => [
                                    'Nuovo',
                                    'Usato',
                                    'PDF',
                                    'Epub',
                                    'Mobi',
                                    'DVD',
                                    'Streaming',
                                    'Download'
                                ]
                                ];
                            //dd($attributes);

                            $data = [

                                    'attributes' => $attributes


                                ];
                           Product::update($id, $data);
                           $variation = Variation::create($id, $data1);
                        }
                        echo $article->Titolo . ' - ' . $article->DescrizioneTipologia . ' - ' .$article->DescrizioneFormato . ' - '. $versione . ' - ' . $variation['permalink'].'<br>';
                        $log .= $article->Titolo . ' - ' . $article->DescrizioneTipologia . ' - ' .$article->DescrizioneFormato . ' - '. $versione . ' - ' . $variation['permalink']."\n";
                        break;




                }



            } else {

                $data1 = [

                    'regular_price' => $article->PrezzoIvato,
                    'sale_price' => $article->PrezzoIvatoScontatoCampagna,
                    'date_on_sale_from' => $article->DataInizioCampagna,
                    'date_on_sale_to' => $article->DataFineCampagna,
                    'stock_quantity' => $article->stock,

                ];
                $idprodotto = $productsku['parent_id'];
                if($idprodotto > 0){
                $variation = Variation::update($idprodotto,$productsku['id'], $data1);
                echo $article->Titolo . ' - ' . $article->DescrizioneTipologia . ' - ' .$article->DescrizioneFormato . ' - Articolo aggiornato - ' . $variation['permalink'].'<br>';

                $log2 .= $article->Titolo . ' - ' . $article->DescrizioneTipologia . ' - ' .$article->DescrizioneFormato . ' - Articolo aggiornato - ' . $variation['permalink']."\n";

                }



            }
         }  catch (\Exception $e) {
            $log3 .= $article->IdArticolo . ' - '. $article->Titolo ."\n" ;
        }
        }
        echo $log1;

        $settingora->value = $ora_update;
        $settingora->save();
        \Log::channel('updateproducts')->notice($log . $log2 . $log1 . $log3);
        Mail::raw($log . $log2 . $log1 . $log3, function ($message)  {
            $message->to("luca.pecos@gmail.com");
            //$message->bcc('luca@pecos.it');
            $message->subject("Inserimento nuovi prodotti");

         });
*/
    echo "FINITO!!!";
});

Route::get('/emailtest', function () {
    Mail::html('Prova email <b>2</b>', function ($message) {
        $message->to("luca.pecos@gmail.com");
        $message->subject("Prova email");
    });
});

Route::get('createlog', function () {



    \Log::channel('updateproducts')->notice('This is testing for updateproducts!' . "\n" . 'Ciao');
    \Log::channel('updateproducts')->info('This is testing for updateproducts! 2' . "\n" . 'Ciao');
    dd('done');
});


Route::get('/streamingdvd', function () {
    set_time_limit(0);
    ini_set("memory_limit", "512M");
    ob_end_flush();
    ob_implicit_flush(true);
    $page = 1;
    $i = 1;
    do {

        $products = Product::all($options = ['per_page' => 100, 'page' => $page, 'after' => '2022-08-09T00:00:00']);


        //$all_products = $all_products->merge($products);

        foreach ($products as $product) {
            echo $i++ . ' - ' . $product->id . "<br>";
            if ($product->description == '' && $product->type == 'variable') {
                $variations = Variation::all($product->id);
                foreach ($variations as $variation) {
                    $found_key_version = array_search('Versione', array_column($variation->attributes, 'name'));
                    switch ($variation->attributes[$found_key_version]->option) {
                        case 'Nuovo':
                        case 'Usato':
                        case 'PDF':
                        case 'Epub':
                        case 'Mobi':
                        case 'DVD':
                        case 'Streaming':
                        case 'Download':
                            $artnimaia = Artnim::where('id_gm', $variation->sku)->first();
                            if ($artnimaia) {
                                $data = [];
                                $letterainiziale = strtolower(substr($artnimaia->titolo, 0, 1));
                                $data['description'] = $artnimaia->descrizione;
                                $data['meta_data'] = [['key' => 'prima_edizione', 'value' => $artnimaia->prima_edizione]];
                                if ($artnimaia->img != '' && count($product->images) == 0) {
                                    $file = env('WOOCOMMERCE_STORE_URL') . 'wp-content/uploads/web/' . $letterainiziale . '/' . $artnimaia->img;
                                    $file_headers = @get_headers($file);
                                    if ($file_headers[0] == 'HTTP/1.1 404 Not Found' || $file_headers[0] == 'HTTP/1.1 301 Moved Permanently') {
                                        $img = false;
                                    } else {
                                        $img = true;
                                        $data['images'] = [
                                            [
                                                'src' => env('WOOCOMMERCE_STORE_URL') . 'wp-content/uploads/web/' . $letterainiziale . '/' . $artnimaia->img
                                            ]
                                        ];
                                    }
                                }
                                Product::update($product->id, $data);
                                echo 'ID: ' . $product->id . ' - ' . $product->name . "<br>";
                            }
                            continue 3;
                    }
                }
            }
        }

        $page++;
    } while ($products->count() > 0);
    echo "Finito!!";
});

Route::get('/tipologiatest', function () {
    $product = new Product();
    $product = Product::find(85);

    dd($product);
    /*
    $found_key_version = array_search('Tipologia', array_column($product['attributes'], 'name'));
    $tipologia = ($product['attributes'][$found_key_version]->options);
    $tipologia[] = 'Straming';
    $product = $product->map(function ($object) use($tipologia,$found_key_version){

        $object->attributes[$found_key_version]->options = $tipologia;
    });
    */
    $product['description'] = "Prova inserimento con api";
    Product::save($product);
});


Route::get('/wpposts', function () {
    set_time_limit(0);
    ini_set("memory_limit", "512M");
    ob_end_flush();
    ob_implicit_flush(true);

    $log = "";

    $page = 1;

    $all_products = new Collection();
    do {

        $products = Product::all($options = ['per_page' => 100, 'page' => $page, 'search' => '[youtube=']);


        $all_products = $all_products->merge($products);
        $page++;
    } while ($products->count() > 0);
    //dd($all_products);
    foreach ($all_products as $key => $product) {
        try {
            $data['description'] = preg_replace('/(<a\sname="video.?"><\/a>)?(\[youtube=)((https??:\/\/)?(?:youtu\.be\/|(?:www\.|m\.)?youtube\.com\/(?:watch|v|embed)(?:\.php)?(?:\?.*v=|\/))([a-zA-Z0-9\-_]+))(\])/', '$3', $product->description);
            //   dd($data['description']);
            Product::update($product->id, $data);
            echo $product->name . "<br>";
            $log .= '<a href="' . $product->permalink . '">' . $product->name . '</a><br>';
        } catch (\Exception $e) {
            $log .= 'NON RIUSCiTO <a href="' . $product->permalink . '">' . $product->name . '</a><br>';
        }
    }
    echo "Finito";
    Mail::html($log, function ($message) {
        $message->to("luca.pecos@gmail.com");
        //$message->bcc('luca@pecos.it');
        $message->subject("Youtube");
    });
});

Route::get('/prossimauscita', function () {
    set_time_limit(0);
    ini_set("memory_limit", "512M");
    $ora_update = Carbon::now();
    $settingora = Setting::where('key', 'update_products')->first();

    $articles = Article::join(DB::raw('(SELECT IdArticolo, MAX(DataOra) AS data FROM T_WEB_Articoli GROUP BY IdArticolo) b'), function ($join) {
        $join->on('T_WEB_Articoli.IdArticolo', '=', 'b.IdArticolo')
            ->on('T_WEB_Articoli.DataOra', '=', 'b.data');
    })
        ->leftJoin(DB::raw('(SELECT e.IdStatoProdotto, e.Descrizione as DescrizioneStatoProdotto FROM T_WEB_StatiProdotto e JOIN (SELECT IdStatoProdotto, MAX(DataOra) as data1 from T_WEB_StatiProdotto GROUP BY IdStatoProdotto) c ON e.IdStatoProdotto = c.IdStatoProdotto AND e.DataOra = c.data1 ) f'), function ($join) {
            $join->on('T_WEB_Articoli.IdStatoProdotto', '=', 'f.IdStatoProdotto');
        })
        ->leftJoin(DB::raw('(SELECT g.IdTipologia, g.Descrizione as DescrizioneTipologia FROM T_WEB_Tipologie g JOIN (SELECT IdTipologia, MAX(DataOra) as data1 from T_WEB_Tipologie GROUP BY IdTipologia) h ON g.IdTipologia = h.IdTipologia AND g.DataOra = h.data1 ) i'), function ($join) {
            $join->on('T_WEB_Articoli.IdTipologia', '=', 'i.IdTipologia');
        })
        ->leftJoin(DB::raw('(SELECT l.IdTipoFormato, l.Descrizione as DescrizioneFormato FROM T_WEB_TipiFormato l JOIN (SELECT IdTipoFormato, MAX(DataOra) as data1 from T_WEB_TipiFormato GROUP BY IdTipoFormato) m ON l.IdTipoFormato = m.IdTipoFormato AND l.DataOra = m.data1 ) n'), function ($join) {
            $join->on('T_WEB_Articoli.IdTipoFormato', '=', 'n.IdTipoFormato');
        })

        ->leftJoin(DB::raw('(SELECT o.Codice, o.QtaDisponibile FROM T_WEB_Disponibile o JOIN (SELECT Codice, MAX(DataOra) as data1 from T_WEB_Disponibile GROUP BY Codice) p ON o.Codice = p.Codice AND o.DataOra = p.data1 ) q'), function ($join) {
            $join->on('T_WEB_Articoli.IdArticolo', '=', 'q.Codice');
        })


        ->where('T_WEB_Articoli.DataOra', '>', '2022-01-01')
        ->where('DescrizioneStatoProdotto', 'Prossima uscita')
        //->where('DescrizioneTipologia','Video Streaming')
        ->orderBy('Titolo')
        ->get();
    ob_end_flush();
    ob_implicit_flush(true);
    \Log::channel('updateproducts')->notice('Inizio da ' . $settingora->value . "\n");
    $log = 'PRODOTTI INSERITI' . "\n";
    $log1 = 'EVENTUALI PRODOTTI NON INSERITI' . "\n";
    foreach ($articles as $article) {
        $productsku = Product::where('sku', $article->IdArticolo)->first();
        //if(Gm_product::where('id_gm',$article->IdArticolo)->doesntExist())
        if ($productsku->count() == 0) {






            $titolo = null;
            $formato = null;
            $prodotti = null;
            $prodotti = new ModelsProduct();
            $titolo =  $article->Titolo;
            switch ($article->DescrizioneTipologia) {

                case 'Libri':

                    $prodotti = $prodotti->where('name', $titolo)->get();
                    $id = 0;

                    if (!is_null($prodotti) && $prodotti->count() > 0) {
                        foreach ($prodotti as $prodotto) {
                            if (strtolower($prodotto->name) === strtolower($titolo)) {
                                $found_key = array_search('Autore libro', array_column($prodotto->attributes, 'name'));
                                if (array_diff($prodotto->attributes[$found_key]->options, $article->authors) === array_diff($article->authors, $prodotto->attributes[$found_key]->options)) {
                                    $id = $prodotto->id;
                                    $variations = Variation::all($prodotto->id);
                                    foreach ($variations as  $variation) {
                                        $found_key_version = array_search('Versione', array_column($variation->attributes, 'name'));
                                        if ($variation->attributes[$found_key_version]->option == 'Nuovo') {
                                            $id = 0;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    $data1 = [

                        'regular_price' => $article->PrezzoIvato,
                        'sku' => $article->IdArticolo,
                        'sale_price' => $article->PrezzoIvatoScontatoCampagna,
                        'date_on_sale_from' => $article->DataInizioCampagna,
                        'date_on_sale_to' => $article->DataFineCampagna,
                        'manage_stock' => true,
                        'stock_quantity' => $article->stock,
                        'purchasable' => false,

                        'attributes' => [
                            [
                                //'id' => 1,
                                'id' => 6,
                                'option' => 'Nuovo'
                            ]

                        ],
                        'meta_data' => [
                            [
                                'key' => 'ISBN',
                                'value' => $article->Ean13
                            ],
                            [
                                'key' => 'misure',
                                'value' => $article->Misure
                            ],
                            [
                                'key' => 'formato',
                                'value' => $article->DescrizioneFormato
                            ],
                            [
                                'key' => 'pagine',
                                'value' => $article->Pagine
                            ],
                            [
                                'key' => 'edizione',
                                'value' => $article->Edizione
                            ],
                            [
                                'key' => 'ristampa',
                                'value' =>  $article->Ristampa
                            ],

                        ]
                    ];
                    if ($id == 0) {
                        $versione = 'Nuova versione';
                        $category = Category::where('name', $article->argomento);
                        if ($category->count() > 0) {
                            $categoria = $category->first();
                            $categoriaid = $categoria['id'];
                        } else {
                            $categoriaid = 0;
                        }
                        $data = [

                            'name' => $article->Titolo,
                            'type' => 'variable',
                            'short_description' =>  $article->Sottotitolo,
                            'categories' => [
                                ['id' => $categoriaid]

                            ],
                            'status' => 'draft',




                            //'description' => 'Simple product full description.',
                            //'short_description' => 'Simple product short description.',


                            'attributes' => [

                                [
                                    //'id' => 1,
                                    'id' => 6,
                                    'position' => 0,
                                    'visible' => true,
                                    'variation' => true,
                                    'options' => [
                                        'Nuovo',
                                        'Usato',
                                        'PDF',
                                        'Epub',
                                        'Mobi',
                                        'DVD',
                                        'Streaming',
                                        'Download'
                                    ]
                                ],

                                [
                                    //'id' => 5,
                                    'id' => 7,
                                    'visible' => true,

                                    'options' =>
                                    $article->authors


                                ],
                                [
                                    //'id' => 2,
                                    'id' => 8,
                                    'visible' => true,

                                    'options' => [
                                        $article->editore

                                    ]
                                ],
                                [
                                    //'id' => 7,
                                    'id' => 9,
                                    'visible' => true,

                                    'options' => [
                                        $article->DescrizioneTipologia

                                    ]
                                ]
                            ],

                            'default_attributes' => [
                                [
                                    //'id' => 1,
                                    'id' => 6,
                                    'option' => 'Nuovo'
                                ]
                            ],




                        ];

                        //$product = Product::create($data);

                        //$idprodotto= $product['id'];


                        //$variation = Variation::create($idprodotto, $data1);
                        //dd($variation);



                    } else {
                        $versione = "Aggiunta versione";
                        $product = Product::find($id);
                        $old_attributes = $product['attributes'];
                        $attributes = [];
                        foreach ($old_attributes as $old_attribute) {
                            if ($old_attribute->id <> 6) {

                                $attributes[] = [
                                    'id' => $old_attribute->id,
                                    'variation' => $old_attribute->variation,
                                    'visible' => $old_attribute->visible,
                                    'options' => $old_attribute->options
                                ];
                            }
                        }

                        $attributes[] =  [
                            //'id' => 1,
                            'id' => 6,
                            'position' => 0,
                            'visible' => true,
                            'variation' => true,
                            'options' => [
                                'Nuovo',
                                'Usato',
                                'PDF',
                                'Epub',
                                'Mobi',
                                'DVD',
                                'Streaming',
                                'Download'
                            ]
                        ];
                        //dd($attributes);

                        $data = [

                            'attributes' => $attributes


                        ];
                        //Product::update($id, $data);

                        //$variation = Variation::create($id, $data1);
                    }
                    echo $article->Titolo . ' - ' . $article->DescrizioneTipologia . ' - ' . $article->DescrizioneFormato . ' - ' . $versione . '<br>';
                    //$log .= $article->Titolo . ' - ' . $article->DescrizioneTipologia . ' - ' .$article->DescrizioneFormato . ' - '. $versione . ' - ' . $variation['permalink']. "\n";
                    break;

                case 'E-book':

                    if ($article->DescrizioneFormato === 'Epub') {


                        $titolo = rtrim(str_ireplace('EPUB', '', $article->Titolo));

                        $formato = 'Epub';
                    } elseif ($article->DescrizioneFormato === 'Pdf') {
                        $titolo = rtrim(str_ireplace('PDF', '', $article->Titolo));

                        $formato = 'PDF';
                    } elseif ($article->DescrizioneFormato === 'Mobi') {
                        $titolo = rtrim(str_ireplace('MOBI', '', $article->Titolo));


                        $formato = 'Mobi';
                    } else {
                        $log1 .= $article->Titolo . ' - ' . $article->DescrizioneTipologia . ' - ' . $article->DescrizioneFormato . "\n";
                        break;
                    }
                    $titolo = rtrim($titolo);
                    $titolo = rtrim(str_ireplace('EBOOK', '', $titolo));
                    $titolo = rtrim($titolo);
                    $titolo = rtrim(str_ireplace('_', '', $titolo));
                    $titolo = rtrim($titolo);
                    $titolo = rtrim($titolo, '-');
                    $titolo = rtrim($titolo);
                    $titolo = rtrim($titolo, '_');
                    $titolo = rtrim($titolo);

                    $prodotti = $prodotti->where('name', $titolo)->get();
                    $id = 0;

                    if (!is_null($prodotti) && $prodotti->count() > 0) {
                        foreach ($prodotti as $prodotto) {
                            if (strtolower($prodotto->name) === strtolower($titolo)) {
                                $found_key = array_search('Autore libro', array_column($prodotto->attributes, 'name'));
                                if (array_diff($prodotto->attributes[$found_key]->options, $article->authors) === array_diff($article->authors, $prodotto->attributes[$found_key]->options)) {
                                    $id = $prodotto->id;
                                    $variations = Variation::all($prodotto->id);
                                    foreach ($variations as  $variation) {
                                        $found_key_version = array_search('Versione', array_column($variation->attributes, 'name'));
                                        if ($variation->attributes[$found_key_version]->option == $formato) {
                                            $id = 0;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    $data1 = [

                        'regular_price' => $article->PrezzoIvato,
                        'sku' => $article->IdArticolo,
                        'sale_price' => $article->PrezzoIvatoScontatoCampagna,
                        'date_on_sale_from' => $article->DataInizioCampagna,
                        'date_on_sale_to' => $article->DataFineCampagna,
                        //'manage_stock' => true,
                        //'stock_quantity' => $article->stock,
                        'purchasable' => 'false',

                        'attributes' => [
                            [
                                'id' => 6,
                                'option' => $formato
                            ]

                        ],
                        'meta_data' => [
                            [
                                'key' => 'ISBN',
                                'value' => $article->Ean13
                            ],
                            [
                                'key' => 'misure',
                                'value' => $article->Misure
                            ],
                            [
                                'key' => 'formato',
                                'value' => $article->DescrizioneFormato
                            ],
                            [
                                'key' => 'pagine',
                                'value' => $article->Pagine
                            ],
                            [
                                'key' => 'edizione',
                                'value' => $article->Edizione
                            ],
                        ]
                    ];
                    if ($id == 0) {

                        $versione = 'Nuova versione';

                        $category = Category::where('name', $article->argomento);
                        if ($category->count() > 0) {
                            $categoria = $category->first();
                            $categoriaid = $categoria['id'];
                        } else {
                            $categoriaid = 0;
                        }

                        $data = [

                            'name' => $titolo,
                            'type' => 'variable',
                            'short_description' =>  $article->Sottotitolo,
                            'categories' => [
                                ['id' => $categoriaid]

                            ],
                            'status' => 'draft',

                            'attributes' => [

                                [
                                    //'id' => 1,
                                    'id' => 6,
                                    'position' => 0,
                                    'visible' => true,
                                    'variation' => true,
                                    'options' => [
                                        'Nuovo',
                                        'Usato',
                                        'PDF',
                                        'Epub',
                                        'Mobi',
                                        'DVD',
                                        'Streaming',
                                        'Download'
                                    ]
                                ],

                                [
                                    //'id' => 5,
                                    'id' => 7,
                                    'visible' => true,

                                    'options' =>
                                    $article->authors


                                ],
                                [
                                    //'id' => 2,
                                    'id' => 8,
                                    'visible' => true,

                                    'options' => [
                                        $article->editore

                                    ]
                                ],
                                [
                                    //'id' => 7,
                                    'id' => 9,
                                    'visible' => true,

                                    'options' => [
                                        $article->DescrizioneTipologia

                                    ]
                                ]
                            ],

                            'default_attributes' => [
                                [
                                    //'id' => 1,
                                    'id' => 6,
                                    'option' => 'Nuovo'
                                ]
                            ],




                        ];

                        //$product = Product::create($data);

                        //$idprodotto= $product['id'];


                        //$variation = Variation::create($idprodotto, $data1);


                    } else {
                        $versione = "Aggiunta versione";
                        $product = Product::find($id);
                        $old_attributes = $product['attributes'];
                        $attributes = [];
                        foreach ($old_attributes as $old_attribute) {
                            if ($old_attribute->id <> 6) {

                                $attributes[] = [
                                    'id' => $old_attribute->id,
                                    'variation' => $old_attribute->variation,
                                    'visible' => $old_attribute->visible,
                                    'options' => $old_attribute->options
                                ];
                            }
                        }

                        $attributes[] =  [
                            //'id' => 1,
                            'id' => 6,
                            'position' => 0,
                            'visible' => true,
                            'variation' => true,
                            'options' => [
                                'Nuovo',
                                'Usato',
                                'PDF',
                                'Epub',
                                'Mobi',
                                'DVD',
                                'Streaming',
                                'Download'
                            ]
                        ];
                        //dd($attributes);

                        $data = [

                            'attributes' => $attributes


                        ];
                        //Product::update($id, $data);
                        //$variation = Variation::create($id, $data1);
                    }
                    echo $article->Titolo . ' - ' . $article->DescrizioneTipologia . ' - ' . $article->DescrizioneFormato . ' - ' . $versione . '<br>';
                    //$log .= $article->Titolo . ' - ' . $article->DescrizioneTipologia . ' - ' .$article->DescrizioneFormato . ' - '. $versione . ' - ' . $variation['permalink']."\n";
                    break;

                case 'Dvd':
                    $titolo = rtrim($article->Titolo);
                    $titolo = rtrim(str_ireplace('DVD', '', $titolo));
                    $titolo = rtrim($titolo);
                    $titolo = rtrim(str_ireplace('_', '', $titolo));
                    $titolo = rtrim($titolo);
                    $titolo = rtrim($titolo, '-');
                    $titolo = rtrim($titolo);
                    $titolo = rtrim($titolo, '_');
                    $titolo = rtrim($titolo);
                    $prodotti = $prodotti->where('name', $titolo)->get();
                    $id = 0;

                    if (!is_null($prodotti) && $prodotti->count() > 0) {
                        foreach ($prodotti as $prodotto) {
                            if (strtolower($prodotto->name) === strtolower($titolo)) {
                                $found_key = array_search('Autore libro', array_column($prodotto->attributes, 'name'));
                                if (array_diff($prodotto->attributes[$found_key]->options, $article->authors) === array_diff($article->authors, $prodotto->attributes[$found_key]->options)) {
                                    $id = $prodotto->id;
                                    $variations = Variation::all($prodotto->id);
                                    foreach ($variations as  $variation) {
                                        $found_key_version = array_search('Versione', array_column($variation->attributes, 'name'));
                                        if ($variation->attributes[$found_key_version]->option == 'DVD') {
                                            $id = 0;
                                        }
                                    }
                                }
                            }
                        }
                    }

                    $data1 = [

                        'regular_price' => $article->PrezzoIvato,
                        'sku' => $article->IdArticolo,
                        'sale_price' => $article->PrezzoIvatoScontatoCampagna,
                        'date_on_sale_from' => $article->DataInizioCampagna,
                        'date_on_sale_to' => $article->DataFineCampagna,
                        'manage_stock' => true,
                        'stock_quantity' => $article->stock,
                        'purchasable' => false,

                        'attributes' => [
                            [
                                'id' => 6,
                                'option' => 'DVD'
                            ]

                        ],
                        'meta_data' => [
                            [
                                'key' => 'ISBN',
                                'value' => $article->Ean13
                            ],
                            [
                                'key' => 'misure',
                                'value' => $article->Misure
                            ],
                            [
                                'key' => 'formato',
                                'value' => $article->DescrizioneFormato
                            ],
                            [
                                'key' => 'pagine',
                                'value' => $article->Pagine
                            ],
                            [
                                'key' => 'edizione',
                                'value' => $article->Edizione
                            ],
                        ]
                    ];
                    if ($id == 0) {
                        $versione = 'Nuova versione';
                        $category = Category::where('name', $article->argomento);
                        if ($category->count() > 0) {
                            $categoria = $category->first();
                            $categoriaid = $categoria['id'];
                        } else {
                            $categoriaid = 0;
                        }
                        $data = [

                            'name' => $article->Titolo,
                            'type' => 'variable',
                            'short_description' =>  $article->Sottotitolo,
                            'categories' => [
                                ['id' => $categoriaid]

                            ],
                            'status' => 'draft',


                            //'description' => 'Simple product full description.',
                            //'short_description' => 'Simple product short description.',


                            'attributes' => [

                                [
                                    //'id' => 1,
                                    'id' => 6,
                                    'position' => 0,
                                    'visible' => true,
                                    'variation' => true,
                                    'options' => [
                                        'Nuovo',
                                        'Usato',
                                        'PDF',
                                        'Epub',
                                        'Mobi',
                                        'DVD',
                                        'Streaming',
                                        'Download'
                                    ]
                                ],

                                [
                                    //'id' => 5,
                                    'id' => 7,
                                    'visible' => true,

                                    'options' =>
                                    $article->authors


                                ],
                                [
                                    //'id' => 2,
                                    'id' => 8,
                                    'visible' => true,

                                    'options' => [
                                        $article->editore

                                    ]
                                ],
                                [
                                    //'id' => 7,
                                    'id' => 9,
                                    'visible' => true,

                                    'options' => [
                                        $article->DescrizioneTipologia

                                    ]
                                ]
                            ],

                            'default_attributes' => [
                                [
                                    //'id' => 1,
                                    'id' => 6,
                                    'option' => 'Nuovo'
                                ]
                            ],




                        ];

                        //$product = Product::create($data);

                        //$idprodotto= $product['id'];


                        //$variation = Variation::create($idprodotto, $data1);



                    } else {
                        $versione = "Aggiunta versione";
                        $product = Product::find($id);
                        $old_attributes = $product['attributes'];
                        $attributes = [];
                        foreach ($old_attributes as $old_attribute) {
                            if ($old_attribute->id <> 6) {

                                $attributes[] = [
                                    'id' => $old_attribute->id,
                                    'variation' => $old_attribute->variation,
                                    'visible' => $old_attribute->visible,
                                    'options' => $old_attribute->options
                                ];
                            }
                        }

                        $attributes[] =  [
                            //'id' => 1,
                            'id' => 6,
                            'position' => 0,
                            'visible' => true,
                            'variation' => true,
                            'options' => [
                                'Nuovo',
                                'Usato',
                                'PDF',
                                'Epub',
                                'Mobi',
                                'DVD',
                                'Streaming',
                                'Download'
                            ]
                        ];
                        //dd($attributes);

                        $data = [

                            'attributes' => $attributes


                        ];
                        //Product::update($id, $data);

                        //$variation = Variation::create($id, $data1);
                    }
                    echo $article->Titolo . ' - ' . $article->DescrizioneTipologia . ' - ' . $article->DescrizioneFormato . ' - ' . $versione . '<br>';
                    // $log .= $article->Titolo . ' - ' . $article->DescrizioneTipologia . ' - ' .$article->DescrizioneFormato . ' - '. $versione . ' - ' . $variation['permalink']."\n";

                    break;

                case 'Video Streaming':
                case 'Video On Demand':
                    if ($article->DescrizioneFormato === 'Streaming') {


                        $titolo = rtrim($article->Titolo, 'STR');
                        $titolo = rtrim(str_ireplace('streaming', '', $titolo));
                        $formato = 'Streaming';
                    } elseif ($article->DescrizioneFormato === 'Download') {
                        $titolo = rtrim($article->Titolo, 'VOD');
                        $titolo = rtrim(str_ireplace('download', '', $titolo));
                        $formato = 'Download';
                    } else {
                        $log1 .= $article->Titolo . ' - ' . $article->DescrizioneTipologia . ' - ' . $article->DescrizioneFormato . "\n";
                        break;
                    }

                    $titolo = rtrim($titolo);

                    $titolo = rtrim(str_ireplace('_', '', $titolo));
                    $titolo = rtrim($titolo);
                    $titolo = rtrim($titolo, '-');
                    $titolo = rtrim($titolo);
                    $titolo = rtrim($titolo, '_');
                    $titolo = rtrim($titolo);

                    $prodotti = $prodotti->where('name', $titolo)->get();
                    $id = 0;
                    if (!is_null($prodotti) && $prodotti->count() > 0) {
                        foreach ($prodotti as $prodotto) {

                            if (strtolower($prodotto->name) === strtolower($titolo)) {

                                $found_key = array_search('Autore libro', array_column($prodotto->attributes, 'name'));


                                if (array_diff($prodotto->attributes[$found_key]->options, $article->authors) === array_diff($article->authors, $prodotto->attributes[$found_key]->options)) {
                                    $id = $prodotto->id;
                                    $variations = Variation::all($prodotto->id);
                                    foreach ($variations as  $variation) {
                                        $found_key_version = array_search('Versione', array_column($variation->attributes, 'name'));
                                        if ($variation->attributes[$found_key_version]->option == $formato) {
                                            $id = 0;
                                        }
                                    }
                                }
                            }
                        }
                    }

                    $data1 = [

                        'regular_price' => $article->PrezzoIvato,
                        'sku' => $article->IdArticolo,
                        'sale_price' => $article->PrezzoIvatoScontatoCampagna,
                        'date_on_sale_from' => $article->DataInizioCampagna,
                        'date_on_sale_to' => $article->DataFineCampagna,
                        //'manage_stock' => true,
                        //'stock_quantity' => $article->stock,
                        'purchasable' => false,

                        'attributes' => [
                            [
                                'id' => 6,
                                'option' => $formato
                            ]

                        ],
                        'meta_data' => [
                            [
                                'key' => 'ISBN',
                                'value' => $article->Ean13
                            ],
                            [
                                'key' => 'misure',
                                'value' => $article->Misure
                            ],
                            [
                                'key' => 'formato',
                                'value' => $article->DescrizioneFormato
                            ],
                            [
                                'key' => 'pagine',
                                'value' => $article->Pagine
                            ],
                            [
                                'key' => 'edizione',
                                'value' => $article->Edizione
                            ],
                        ]
                    ];
                    if ($id == 0) {
                        $versione = 'Nuova versione';
                        $category = Category::where('name', $article->argomento);
                        if ($category->count() > 0) {
                            $categoria = $category->first();
                            $categoriaid = $categoria['id'];
                        } else {
                            $categoriaid = 0;
                        }

                        $data = [

                            'name' => $titolo,
                            'type' => 'variable',
                            'short_description' =>  $article->Sottotitolo,
                            'categories' => [
                                ['id' => $categoriaid]

                            ],
                            'status' => 'draft',

                            'attributes' => [

                                [
                                    //'id' => 1,
                                    'id' => 6,
                                    'position' => 0,
                                    'visible' => true,
                                    'variation' => true,
                                    'options' => [
                                        'Nuovo',
                                        'Usato',
                                        'PDF',
                                        'Epub',
                                        'Mobi',
                                        'DVD',
                                        'Streaming',
                                        'Download'
                                    ]
                                ],

                                [
                                    //'id' => 5,
                                    'id' => 7,
                                    'visible' => true,

                                    'options' =>
                                    $article->authors


                                ],
                                [
                                    //'id' => 2,
                                    'id' => 8,
                                    'visible' => true,

                                    'options' => [
                                        $article->editore

                                    ]
                                ],
                                [
                                    //'id' => 7,
                                    'id' => 9,
                                    'visible' => true,

                                    'options' => [
                                        $article->DescrizioneTipologia

                                    ]
                                ]
                            ],

                            'default_attributes' => [
                                [
                                    //'id' => 1,
                                    'id' => 6,
                                    'option' => 'Nuovo'
                                ]
                            ],




                        ];

                        //$product = Product::create($data);

                        //$idprodotto= $product['id'];


                        //$variation = Variation::create($idprodotto, $data1);


                    } else {
                        $versione = "Aggiunta versione";
                        $product = Product::find($id);
                        $old_attributes = $product['attributes'];
                        $attributes = [];
                        foreach ($old_attributes as $old_attribute) {
                            if ($old_attribute->id <> 6) {

                                $attributes[] = [
                                    'id' => $old_attribute->id,
                                    'variation' => $old_attribute->variation,
                                    'visible' => $old_attribute->visible,
                                    'options' => $old_attribute->options
                                ];
                            }
                        }

                        $attributes[] =  [
                            //'id' => 1,
                            'id' => 6,
                            'position' => 0,
                            'visible' => true,
                            'variation' => true,
                            'options' => [
                                'Nuovo',
                                'Usato',
                                'PDF',
                                'Epub',
                                'Mobi',
                                'DVD',
                                'Streaming',
                                'Download'
                            ]
                        ];
                        //dd($attributes);

                        $data = [

                            'attributes' => $attributes


                        ];
                        //Product::update($id, $data);
                        //$variation = Variation::create($id, $data1);
                    }
                    echo $article->Titolo . ' - ' . $article->DescrizioneTipologia . ' - ' . $article->DescrizioneFormato . ' - ' . $versione . '<br>';
                    // $log .= $article->Titolo . ' - ' . $article->DescrizioneTipologia . ' - ' .$article->DescrizioneFormato . ' - '. $versione . ' - ' . $variation['permalink']."\n";
                    break;
            }
        }
    }
    echo $log1;
    echo "FINITO!!!";
    //$settingora->value = $ora_update;
    //$settingora->save();
    \Log::channel('updateproducts')->notice($log . $log1);
});


Route::get('/articolidadata', function () {
    set_time_limit(0);
    ini_set("memory_limit", "512M");
    $ora_update = Carbon::now();
    $settingora = Setting::where('key', 'update_products')->first();
    $fromtime = str_replace('-', '', $settingora->value);

    $articles = Article::join(DB::raw('(SELECT IdArticolo, MAX(DataOra) AS data FROM T_WEB_Articoli GROUP BY IdArticolo) b'), function ($join) {
        $join->on('T_WEB_Articoli.IdArticolo', '=', 'b.IdArticolo')
            ->on('T_WEB_Articoli.DataOra', '=', 'b.data');
    })
        ->leftJoin(DB::raw('(SELECT e.IdStatoProdotto, e.Descrizione as DescrizioneStatoProdotto FROM T_WEB_StatiProdotto e JOIN (SELECT IdStatoProdotto, MAX(DataOra) as data1 from T_WEB_StatiProdotto GROUP BY IdStatoProdotto) c ON e.IdStatoProdotto = c.IdStatoProdotto AND e.DataOra = c.data1 ) f'), function ($join) {
            $join->on('T_WEB_Articoli.IdStatoProdotto', '=', 'f.IdStatoProdotto');
        })
        ->leftJoin(DB::raw('(SELECT g.IdTipologia, g.Descrizione as DescrizioneTipologia FROM T_WEB_Tipologie g JOIN (SELECT IdTipologia, MAX(DataOra) as data1 from T_WEB_Tipologie GROUP BY IdTipologia) h ON g.IdTipologia = h.IdTipologia AND g.DataOra = h.data1 ) i'), function ($join) {
            $join->on('T_WEB_Articoli.IdTipologia', '=', 'i.IdTipologia');
        })
        ->leftJoin(DB::raw('(SELECT l.IdTipoFormato, l.Descrizione as DescrizioneFormato FROM T_WEB_TipiFormato l JOIN (SELECT IdTipoFormato, MAX(DataOra) as data1 from T_WEB_TipiFormato GROUP BY IdTipoFormato) m ON l.IdTipoFormato = m.IdTipoFormato AND l.DataOra = m.data1 ) n'), function ($join) {
            $join->on('T_WEB_Articoli.IdTipoFormato', '=', 'n.IdTipoFormato');
        })
        /*
            ->leftJoin(DB::raw('(SELECT o.Codice, o.QtaDisponibile FROM T_WEB_Disponibile o JOIN (SELECT Codice, MAX(DataOra) as data1 from T_WEB_Disponibile GROUP BY Codice) p ON o.Codice = p.Codice AND o.DataOra = p.data1 ) q'), function($join) {
                $join->on('T_WEB_Articoli.IdArticolo', '=', 'q.Codice');
            })
            */

        ->where('data', '>=', $fromtime)
        ->where('DescrizioneStatoProdotto', 'In commercio')
        //->where('Titolo','Incredibilmente crudo')
        //->where('DescrizioneTipologia','Video Streaming')
        ->orderBy('Titolo')
        ->get();

    ob_end_flush();
    ob_implicit_flush(true);
    foreach ($articles as $article) {


        echo $article->IdArticolo . " | " . $article->Titolo . " | " . $article->DescrizioneStatoProdotto . " | " . $article->DescrizioneTipologia . " | " .  $article->DescrizioneFormato . " | " . $article->QtaDisponibile . " | " . $article->data . "<br>";
    }
});

Route::get('/quantita', function () {
    $articles = Stock::join(DB::raw('(SELECT Codice, MAX(DataOra) as data1 from T_WEB_Disponibile GROUP BY Codice) p'), function ($join) {
        $join->on('T_WEB_Disponibile.Codice', '=', 'p.Codice')
            ->on('T_WEB_Disponibile.DataOra', '=', 'p.data1');
    })
        ->where('DataOra', '>', '20220804')
        ->orderBy('T_WEB_Disponibile.Codice')
        ->get();
    ob_end_flush();
    ob_implicit_flush(true);
    foreach ($articles as $article) {
        echo $article->Codice . ' - ' . $article->QtaDisponibile . ' - ' . $article->DataOra . '<br>';
    }
});

Route::get('/autori', function () {
    set_time_limit(0);
    ini_set("memory_limit", "512M");
    ob_end_flush();
    ob_implicit_flush(true);
    $authors = Author::join(
        DB::raw('(SELECT IdAutore, MAX(DataOra) AS data FROM T_WEB_Autori GROUP BY IdAutore) b'),
        function ($join) {
            $join->on('T_WEB_Autori.IdAutore', '=', 'b.IdAutore')
                ->on('T_WEB_Autori.DataOra', '=', 'b.data');
        }
    )->orderBy('T_WEB_Autori.IdAutore')->where('T_WEB_Autori.IdAutore', '>', 351)->get();

    //dd($authors);
    $attribute_id = 7;
    foreach ($authors as $author) {
        //echo $author->IdAutore . " - " .$author->Nome . " " .$author->Cognome."<br>";
        $ricercaautore = ($author->Nome != '' ? trim($author->Nome) . " " : '') . trim($author->Cognome);
        echo $author->Id . " - " . $author->IdAutore . " - " . $ricercaautore . "<br>";
        $terms = Term::all($attribute_id, $options = ['search' => $ricercaautore]);
        foreach ($terms as $term) {
            if (strcmp($term->name, $ricercaautore) == 0) {
                $data = [
                    'name' => trim($author->Nome) . "," . trim($author->Cognome)
                ];
                $term_id = $term->id;
                $termupdate = Term::update($attribute_id, $term_id, $data);
                echo $ricercaautore . " => " . $termupdate['name'] . "<br>";
                break;
            }
        }
    }
});
Route::get('/wooorders', function () {
    /*$all_orders = new Collection();
    $page = 1;
    do{

        $orders = FacadesOrder::all($options = ['per_page' => 100, 'page' => $page,'status'=> ["pending","processing","on-hold"]]);


      $all_orders = $all_orders->merge($orders);
      $page++;
    } while ($orders->count() > 0);
    dd($all_orders);
    foreach($all_orders as $order){
        echo $order->id ."<br>";
    }
*/
    /*
$data = [
    'status' => 'completed',
];
$order = FacadesOrder::update(142,$data);
echo "fatto";
*/
    $orders = Order::where('IdInternet', 28380)->latest('DataOra')->first();
    if (!$orders) {
        echo "inserisci";
    }
});


Route::get('/test30/{id}', function ($id) {
    $clienti = Orderdetail::where('IdInternet', $id)->get();
    /*
    $clienti = Clientegm::where('IdInternet', 37438)->first();
    $clienti->IdNazione = 227;
    $clienti->save();
    */
    dd($clienti);
});

Route::get('/test31', function () {
    $ora_update = Carbon::now();
    $settingora = Setting::where('key', 'update_products')->first();
    //echo $ora_update->diffInDays($settingora->value);
    $totime = new Carbon($settingora->value);
    $totime =  $totime->addDays(15);
    $totime = str_replace('-', '', $totime);
    echo $totime;
});


Route::get('/test32', function () {
    set_time_limit(0);
    ini_set("memory_limit", "512M");
    /* $ora_update = Carbon::now();
                $settingora = Setting::where('key','update_products')->first();
                $fromtime = str_replace('-','',$settingora->value);
                */
    $articles = Article::join(DB::raw('(SELECT IdArticolo, MAX(DataOra) AS data FROM T_WEB_Articoli GROUP BY IdArticolo) b'), function ($join) {
        $join->on('T_WEB_Articoli.IdArticolo', '=', 'b.IdArticolo')
            ->on('T_WEB_Articoli.DataOra', '=', 'b.data');
    })
        ->leftJoin(DB::raw('(SELECT e.IdStatoProdotto, e.Descrizione as DescrizioneStatoProdotto FROM T_WEB_StatiProdotto e JOIN (SELECT IdStatoProdotto, MAX(DataOra) as data1 from T_WEB_StatiProdotto GROUP BY IdStatoProdotto) c ON e.IdStatoProdotto = c.IdStatoProdotto AND e.DataOra = c.data1 ) f'), function ($join) {
            $join->on('T_WEB_Articoli.IdStatoProdotto', '=', 'f.IdStatoProdotto');
        })
        ->leftJoin(DB::raw('(SELECT g.IdTipologia, g.Descrizione as DescrizioneTipologia FROM T_WEB_Tipologie g JOIN (SELECT IdTipologia, MAX(DataOra) as data1 from T_WEB_Tipologie GROUP BY IdTipologia) h ON g.IdTipologia = h.IdTipologia AND g.DataOra = h.data1 ) i'), function ($join) {
            $join->on('T_WEB_Articoli.IdTipologia', '=', 'i.IdTipologia');
        })
        ->leftJoin(DB::raw('(SELECT l.IdTipoFormato, l.Descrizione as DescrizioneFormato FROM T_WEB_TipiFormato l JOIN (SELECT IdTipoFormato, MAX(DataOra) as data1 from T_WEB_TipiFormato GROUP BY IdTipoFormato) m ON l.IdTipoFormato = m.IdTipoFormato AND l.DataOra = m.data1 ) n'), function ($join) {
            $join->on('T_WEB_Articoli.IdTipoFormato', '=', 'n.IdTipoFormato');
        })
        /*
                ->leftJoin(DB::raw('(SELECT o.Codice, o.QtaDisponibile FROM T_WEB_Disponibile o JOIN (SELECT Codice, MAX(DataOra) as data1 from T_WEB_Disponibile GROUP BY Codice) p ON o.Codice = p.Codice AND o.DataOra = p.data1 ) q'), function($join) {
                    $join->on('T_WEB_Articoli.IdArticolo', '=', 'q.Codice');
                })
                */

        //->where('T_WEB_Articoli.DataOra','>',$settingora->value)
        ->where('data', '>=', '20221110 08:00:00')
        ->where(function ($query) {
            $query->where('DescrizioneStatoProdotto', 'In commercio')
                ->orWhere('DescrizioneStatoProdotto', 'In prevendita')
                ->orWhere('DescrizioneStatoProdotto', 'Prossima uscita');
        })
        //->where('DescrizioneTipologia','Video Streaming')
        ->orderBy('Titolo')
        ->get();
    dd($articles);
});

Route::get('/order/{id}', function ($id) {
    $orderwoo = FacadesOrder::find($id);
    $customer = Customer::find($orderwoo['customer_id']);
    dd($customer);
    dd($orderwoo);
    /*
    $changedest = false;
  if (($orderwoo['shipping']->address_1 != null && $orderwoo['shipping']->address_1 != '' && $orderwoo['shipping']->address_1  != $orderwoo['billing']->address_1) || ($orderwoo['shipping']->first_name != null && $orderwoo['shipping']->first_name  != '' && $orderwoo['shipping']->first_name != $orderwoo['billing']->first_name)  ){
    $changedest= true;
  }
  $order = new Order();
  $order->IdInternet = $orderwoo['id'];
  $order->CodClienteInternet = $orderwoo['customer_id'];
  $order->Enabled = 1;
  $order->DataOra = $orderwoo['date_created'];
  $order->Note = $orderwoo['customer_note'];
  $order->Totale = $orderwoo['total'];
  if($orderwoo['payment_method'] == 'wc_gateway_gestpay' ){
    $order->CodPagamentoGM = 'CARTASELLA';
  }
  if($orderwoo['payment_method'] == 'bacs' ){
    $order->CodPagamentoGM = 'BONIFPOSTALE';
    $order->FlagSospeso = 1;
  }
  $order->Spedizioniere = 'POSTE';

  if ($changedest)
  {
      $order->CodDestInternet = $orderwoo['customer_id'];
  }
  $order->save();

  $prodotti = $orderwoo['line_items'];
  foreach ($prodotti as $prodotto){
    $orderdetail = new Orderdetail();
    $orderdetail->IdInternet = $orderwoo['id'];
    $orderdetail->CodArticoloGM = $prodotto->sku;
    $orderdetail->Qta = $prodotto->quantity;
    $orderdetail->PrezzoLordo = $prodotto->total;
    $orderdetail->Enabled = 1;
    $orderdetail->DataOra = $orderwoo['date_created'];
    $orderdetail->save();

  }
  $customer = Customer::find($orderwoo['customer_id']);
  $cliente = new Clientegm();
  $cliente->CodClienteInternet = $customer['id'];
  $cliente->Nominativo = $customer['last_name'] . " " .$customer['first_name'];
  $cliente->Indirizzo = $customer['billing']->address_1 . " ". $customer['billing']->address_2;
  $cliente->Citta = $customer['billing']->city;
  $cliente->Cap = $customer['billing']->postcode;
  $cliente->Provincia = $customer['billing']->state;
  $cliente->Telefono = $customer['billing']->phone;
  $cliente->Email = $customer['billing']->email;
  $cliente->IdNazione = 227;
  $metas = $customer['meta_data'];
  foreach($metas as $meta)
  {

      if ($meta->key == 'cod_fiscale')
      {
          $cliente->CodiceFiscale = $meta->value;
      }
      elseif ($meta->key == 'vat')
      {
        $cliente->PIVA = $meta->value;
      }
  }
  $cliente->IdInternet = $order['id'];
  $cliente->save();

  if($changedest){
    $clientedest = new Clientegmdest();
    $clientedest->CodDestInternet = $order['customer_id'];
    $clientedest->Nominativo = $order['shipping']->last_name . " " .$order['shipping']->first_name;
    $clientedest->Indirizzo = $order['shipping']->address_1 . " ". $order['shipping']->address_2;
    $clientedest->Citta = $order['shipping']->city;
    $clientedest->Cap = $order['shipping']->postcode;
    $clientedest->Provincia = $order['shipping']->state;
    $clientedest->Telefono = $order['shipping']->phone;
    $cliente->IdNazione = 227;
    $clientedest->IdInternet = $order['id'];
    $clientedest->save();
    Log::info('Inserito ordine');
}

    //dd($order['billing']->first_name);
    //echo $order->id ."<br>";
    //echo $order->billing['first_name'];
    $prodotti = $order['line_items'];
  foreach ($prodotti as $prodotto){

    echo $prodotto->sku ."<br>";


  }
*/
});

Route::get('/ordineclientegm/{id}', function ($id) {
    $clients = Clientegm::where('CodClienteInternet', $id)->get();
    dd($clients);
});

Route::get('/provapao', [TestPaoController::class, 'provapao']);


Route::get('/aggiornapreorder/{idarticolo}', function ($idarticolo) {
    $product = Product::where('sku', $idarticolo)->first();

    if ($product) {

        echo 'Prodotto: ' . $product->id . ' - ' . $product->name . '<br>';

        $aggiorna = false;

        if ($aggiorna) {
            Product::update($product->id, $data);
        }
    } else {
        echo "Il prodotto non esiste";
    }
});
