<?php

namespace App\Console\Commands;

use App\Models\OrderArchive;
use App\Models\OrderArchivesItem;
use Carbon\Carbon;
use Illuminate\Support\Env;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Mail;

class hooreycaIdNotifier extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */

    protected $signature = 'emegrendeles:hooreycaIdNotifier {--doc : print documentation }';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Send scheduled hooreyca id missing in order notification to Delirest';
    private Carbon $nowTime;
    private Carbon $fromTime;
    protected bool $sendEmail=true;
    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->nowTime=Carbon::now();

        $this->fromTime=Carbon::yesterday();
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle(): int
    {
        $tmp=explode('\\', __CLASS__);
        $className=end($tmp);
        $this->info($className." started");
        $this->sendEmail= config('app.send_hooreyca_id_notification',false);
        //$this->info("Need debug!!!");
        $this->info("Send email:".var_export($this->sendEmail,true));
        $this->checkMissingHooreycaId();
        $this->info($className." end");
        return 0;
    }

    public function info($string, $verbosity = null)
    {
        if($verbosity){
            Log::channel('hooreycaIdNotifier')->info($string, $verbosity);
            parent::info($string.' data: '.var_export($verbosity,true));
        }else{
            Log::channel('hooreycaIdNotifier')->info($string);
            parent::info($string);
        }

    }

    private function checkMissingHooreycaId()
    {
        //$this->fromTime=Carbon::parse('2023-09-18');
        $this->info($this->fromTime->toDateString());
        $Orders=OrderArchive::select(['id','supplier_name','profit_center_name'])->where('sentTime','>',$this->fromTime->toDateString())->get();

        if(count($Orders)<1){
            $this->info('No active Order Notification this moment');
            return;
        }else{
            $this->info('Active Order Notification this moment:'.count($Orders).'');
        }
        //dd($Orders->get()->where('id',12182)->toArray());

        $orderItems=OrderArchivesItem::
            select(['name','hooreycaId','order_archive_id','id'])
            ->whereIn('order_archive_id',$Orders->pluck('id'))
            ->where(function ($query) {
                $query->where('hooreycaId','=','')
                    ->orWhereNull('hooreycaId');
            })

            ->orderBy('name')
            //->distinct()
                ->limit(10)
            //->toSql();
            ->get()        ;
        //dd($orderItems);
        if(count($orderItems)<1){
            $this->info('No missing Hooreyca ID this moment');
            return;
        }else{
            $this->info('Missing Hooreyca ID this moment:'.count($orderItems));
        }
        //debug
        //return;
        //dd($orderItems->toArray());
        $viewData=['fromTime'=>$this->fromTime->format('Y.m.d.'),'items'=>[]];
        foreach ($orderItems->toArray() as $item){
            //dd($Orders->where('id',$item['order_archive_id'])->toArray()[0]);
            //dd($item, $Orders->where('id',$item['order_archive_id']));
            $OrderData=$Orders->where('id',$item['order_archive_id'])->first()->toArray();
            $item=array_merge($item,$OrderData);
            $viewData['items'][]=$item;
            //parent::info('item',['asdasd']);
            $this->info('item',$item);
            //Log::channel('hooreycaIdNotifier')->info('item', $item);
            //var_dump($item);
        }

        if($this->sendEmail){
            $MailResult=Mail::send('email.hooreycaIdNotifier',$viewData,function($m){

                //$subject='Delirest - '.$orderData['profit_center']['name'].' - '.$orderData['humanId'];
                $subject='Hooreyca id missing';
                $m->subject($subject);
                $m->to( explode(',',config('app.mail_to_hooreyca_id_notification','city99@e98.hu')));
                $m->bcc('city99@e98.hu');
            });
            $this->info('Email sent to:'.var_export(explode(',',config('app.mail_to_hooreyca_id_notification','city99@e98.hu'))));
            $this->info('Email result'.
                var_export($MailResult,true));
        }
    }



}
