<?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 App\Services\ProductLogger;
use App\Stock;
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 TestPao extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'product:testpao';

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

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

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        try {
            $mostra_solo_qta_negative = true;

            $log = "";
            echo "\n*** INIZIO ***";
            $aggiornato = false;
            set_time_limit(0);
            ini_set("memory_limit", "512M");
            $settingora = Setting::where('key', 'update_products_qta')->first();
            $productLogger = new ProductLogger($settingora, 'testpao');
            $fromtime = str_replace('-', '', $settingora->value);

            $productLogger->addLog('info', "Articoli: \n");

            echo "\nArticoli: \n";

            $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');
                })
                ->where('data', '>=', $fromtime)
                ->where(function ($query) {
                    $query->where('DescrizioneStatoProdotto', 'In commercio')
                        ->orWhere('DescrizioneStatoProdotto', 'In prevendita')
                        ->orWhere('DescrizioneStatoProdotto', 'Prossima uscita');
                })
                //->where('DescrizioneTipologia','Video Streaming')
                ->orderBy('Titolo')
                ->take(2)
                ->get();


            if ($articles) {
                // log the count of the articles
                echo "Num Articoli: " . $articles->count();
                $productLogger->addLog('info', "Quanti Articoli: " . $articles->count());


                $ind = 0;
                foreach ($articles as $article) {
                    try {
                        $ind++;
                        echo "\nArticolo " . $ind . " " . $article->Titolo . " qta = " . $article->stock;

                        $mostra = false;
                        if ($mostra_solo_qta_negative) {
                            if ($article->stock < 0) {
                                $mostra = true;
                            }
                        } else {
                            $mostra = true;
                        }
                        if ($mostra) {
                            if (is_object($article)) {
                                $strarticolo = json_encode($article, JSON_PRETTY_PRINT);
                                if ($strarticolo !== false) {
                                    echo $strarticolo;
                                    $productLogger->addLog('info', $strarticolo);
                                }
                            }

                            if ($article->stock)
                                echo "\r\n QTA = " . $article->stock . "\r\n";
                        }

                        $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
                                            ],
                                            [
                                                'key' => 'DataPubblicazione',
                                                'value' =>  $article->DataPubblicazione
                                            ],
                
                                        ]
                                    ];
                                    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;
                                        }
                                    }
                                    break;
                            }
                        }
                    } catch (\Exception $e) {
                        echo "Error: " . $e->getMessage();

                        $productLogger->addLog('info', $e->getMessage());
                    }
                }
            }

            // get the last record of Stock
            echo "\nLast record Stock ...";

            $lastrecordStock = Stock::latest('DataOra')->take(1)->get();

            $productLogger->addLog('info', '\n');

            foreach ($lastrecordStock as $stock) {
                $productLogger->addLog('info', "Codice: " . $stock->Codice);
                $productLogger->addLog('info', " QtaDisp: " . $stock->QtaDisponibile);
                $productLogger->addLog('info', " DataOra: " . $stock->DataOra);

                // Get the productsku record by $stock->Codice 
                $productsku = Product::where('sku', $stock->Codice)->first();

                if ($productsku->count() > 0) {
                    // log the productsku record
                    $productskustr = json_encode($productsku, JSON_PRETTY_PRINT);
                    echo $productskustr;
                    $productLogger->addLog('info', "\n" . $productskustr);
                }

                $productLogger->addLog('info', "\n");
            }

            echo "************** FINE *********** ";

            // Select all the fields of the Stock table        

        } catch (\Exception $e) {
            $productLogger->addLog('info',  $e->getMessage());
            echo "Error: " . $e->getMessage();
        }

        $productLogger->setLogandSendEmail('Test Paolo');

        if (true) {
            // Send the email 
            Mail::raw($log, function ($message) {
                $message->to(Mylog::getEmail());
                $message->subject(Mylog::getSubjectEmail("TESTPAO"));
            });
        }
    }
}
