<?php

namespace App\Console\Commands;

use Carbon\Carbon;
use Codexshaper\WooCommerce\Facades\Product;
use Illuminate\Console\Command;
use App\Setting;
use App\Article;
use App\Mylog;
use Codexshaper\WooCommerce\Models\Product as ModelsProduct;
use Codexshaper\WooCommerce\Facades\Variation;
use Codexshaper\WooCommerce\Facades\Category;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\DB;



class ProductUpdateUsedGm extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'product:used:gmupdate';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Aggiorna prodotti usati da GM';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $aggiornato = false;
        set_time_limit(0);
        ini_set("memory_limit", "512M");
        $ora_update = Carbon::now();
        $settingora = Setting::where('key', 'update_products_used')->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');
               })
               */
            //->groupBy('T_WEB_Articoli.IdArticolo')
            ->where('data', '>=', $fromtime)
            ->where('EAN13', 'LIKE', '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('data')

            //->take(5)
            //->orderBy('ListaAutori')
            ->get();
        Log::channel('updateproductsused')->notice('Inizio da ' . $settingora->value . "\n");
        $loginizio = 'Inizio da ' . $settingora->value . "\n";
        $logfine = 'Fino a ' . $ora_update . "\n";
        $log = ' PRODOTTI USATI INSERITI' . "\n";
        $log1 = 'EVENTUALI PRODOTTI USATI NON INSERITI' . "\n";
        $log2 = 'PRODOTTI USATI AGGIORNATI' . "\n";
        $log3 = 'PRODOTTI USATI NON INSERITI PER PROBLEMI SERVER' . "\n";


        foreach ($articles as $article) {
            try {
                /*
         $settingdata = Setting::where('key','data_product_used')->first();
         $settingdata->value = $article->data;
         $settingdata->save();
         */
                $productsku = Product::where('sku', $article->IdArticolo)->first();
                if ($productsku->count() == 0) {

                    $titolo = null;
                    $formato = null;
                    $titolo =  $article->Titolo;
                    $titolo = rtrim($titolo);
                    $titolo = rtrim(str_ireplace('USATO', '', $titolo));
                    $titolo = rtrim($titolo);

                    $page = 1;

                    $all_products = new Collection();
                    do {
                        $products = Product::all($options = ['per_page' => 100, 'page' => $page, 'search' => $titolo]);
                        $all_products = $all_products->merge($products);
                        $page++;
                    } while ($products->count() > 0);

                    foreach ($all_products as $product) {
                        $variations = Variation::all($product->id);
                        $target_usato = substr($article->Ean13, strlen('USATO'));

                        foreach ($variations as $variation) {
                            foreach ($variation->meta_data as $meta_data) {

                                if ($meta_data->key === 'ISBN') {
                                    // Estrai gli ultimi caratteri dell'ISBN

                                    $isbn_value = substr($meta_data->value, -strlen($target_usato));
                                    //dd($isbn_value);
                                    // Confronta gli ultimi caratteri con il valore desiderato
                                    if ($isbn_value === $target_usato) {
                                        $meta_data->value;
                                        $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' => 'Usato'
                                                ]

                                            ],
                                            '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
                                                ],

                                            ]
                                        ];

                                        $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($product->id, $data);
                                        $variation = Variation::create($product->id, $data1);

                                        $log .= $article->Titolo . ' - ' . $article->Ean13 . " - " . $variation['permalink'] . "\n";

                                        $aggiornato = true;

                                        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 "Modificato " . $article->Titolo ."<br>";
                    $log2 .= $article->Titolo . ' - ' . $article->Ean13 . " - Articolo aggiornato -  " . $variation['permalink'] . "\n";

                    $aggiornato = true;


                    //}




                }
            } catch (\Exception $e) {
                //$log3 .= $article->IdArticolo . ' - '. $article->Titolo ."\n" ;
            }
        }
        $settingora->value = $ora_update;
        $settingora->save();
        if ($aggiornato) {
            Log::channel('updateproductsused')->notice($log . $log2 . $log1 . $log3);
            Log::channel('updateproductsused')->notice('Fino a ' . $ora_update . "\n");
            Mail::raw($loginizio . $log . $log2 . $log1 . $log3 . $logfine, function ($message) {
                $message->to(Mylog::getEmail());
                $message->subject(Mylog::getSubjectEmail("Inserim. nuovi prodotti Usati"));
            });
        }
    }
}
