<?php

namespace App\Console\Commands;

use App\Enums\OrderFlag;
use App\Http\Controllers\OrderController;
use App\Models\OrderArchive;
use App\Models\SupplierNotifier as SupplierNotifierModel;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class supplierNotifier extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'emegrendeles:supplierNotifier {--doc : print documentation }';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Send scheduled unprocessed order notification to supplier';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    protected bool $sendEmail = false;

    protected int $minHour = 0;

    protected array $notifierHour = [3, 8, 24];

    protected array $workHour = [
        1 => [4, 18],
        2 => [4, 18],
        3 => [4, 18],
        4 => [4, 18],
        5 => [4, 16],
        6 => [23, -1],
        0 => [23, -1],

    ];

    protected array $nextDay = [
        1 => 2,
        2 => 3,
        3 => 4,
        4 => 5,
        5 => 1,
        6 => 1,
        0 => 1,
    ];

    private Carbon $nowTime;

    public function __construct()
    {
        parent::__construct();
        $this->minHour = $this->notifierHour[0];
        $this->nowTime = Carbon::now();
        $this->sendEmail = env('SEND_SUPPLIER_NOTIFICATION', false);
    }

    public function info($string, $verbosity = null)
    {
        if ($verbosity) {
            Log::channel('supplierNotifier')->info($string, $verbosity);
        } else {
            Log::channel('supplierNotifier')->info($string);
        }
        parent::info($string, $verbosity);
    }

    /**
     * Execute the console command.
     */
    public function handle(): int
    {
        $this->info('Supplier Notifier Started');
        // Log::channel('supplierNotifier')->info('Supplier Notifier Started',['requestData'=>var_export($request->server(),true)]);
        // $name = $this->ask('What is your name?');
        // $this->info('hello '.$name);
        // $this->error('error','sdsd');
        // $this->warn('warn','pppp');
        // $this->exampleProgressBar();
        // $this->testTimes();
        // $this->testSupplierNotifierModel();

        /*        $s=new SupplierNotifierModel();
                $s->makeNotificationsForOrderArchive(12179);*/
        $this->info(get_current_user());
        $this->checkUnprocessedOrderNotification();

        $this->info('Supplier Notifier end');

        return 0;
    }

    private function testSupplierNotifierModel($timeStr = null)
    {

        $timeStr = '2023-09-08 15:12:12'; // péntek in work
        $timeStr = '2023-09-08 6:12:12'; // péntek +3+8
        $timeStr = '2023-09-08 17:12:12'; // péntek out of  work
        $timeStr = '2023-09-08 11:12:12'; // péntek +3
        $timeStr = '2023-09-04 07:12:12'; // hetfő +3+8
        $timeStr = '2023-09-04 03:12:12'; // hetfő before work
        $timeStr = '2023-09-04 18:12:12'; // hetfő out of  work
        $timeStr = '2023-09-04 07:12:12'; // hetfő +3+8
        $timeStr = '2023-09-18 07:13:56';
        $SupplierNotifier = new SupplierNotifierModel;
        // $SupplierNotifier->makeTime($timeStr);
        $SupplierNotifier->makeNotificationsForOrderArchive(12180);
    }

    public function exampleProgressBar($max = null)
    {
        if (! $max) {
            $max = 100;
        }

        $bar = $this->output->createProgressBar($max);
        $bar->start();
        for ($i = 0; $i < $max; $i++) {
            usleep(300);
            $bar->advance();
        }
        $bar->finish();
    }

    private function sendNotification(int $orderArchiveId)
    {
        // $orderData=app(OrderController::class)->getOrderData($orderArchiveId);
        $orderData = app(OrderController::class)->getOrderData(null, getOrderFromOrderArchive($orderArchiveId));
        $orderData['feedBackIdLinkParam'] = base64_encode($orderData['feedBackId']);
        $orderData['sentTime'] = Carbon::now()->toDateTimeString();
        $orderData['noPrintButton'] = true;
        $HTMLInvoice = view('modules.order.invoice')->with($orderData
        )->render();
        $HTMLOrder = view('email.order')->with(['orderHTMLInvoice' => $HTMLInvoice,
            'orderData' => $orderData,
        ]
        )->render();

        $subject = 'EMLÉKEZTETŐ A Szállítói webrendelőn érkezett megrendelés visszaigazolására ';
        $fileType = $orderData['supplier']['emailAttachmentType'];
        $attachments = app(OrderController::class)->getEmailAttachment($orderData, $fileType);
        $to = [];
        if ($orderData['customNotificationEmail'] && $orderData['customNotificationEmail'] != 'NULL') {
            $to[] = $orderData['customNotificationEmail'];
        }

        if (env('APP_STAGE', 'DEV') == 'PROD') {
            $to[] = $orderData['supplier']['orderEmail'];
            if ($orderData['supplier']['orderEmail2']) {
                $to[] = $orderData['supplier']['orderEmail2'];
            }
        } else {
            $to[] = env('MAIL_TO_ORDER_ADDRESS');
        }
        $bcc = [];
        if (env('MAIL_TO_ORDER_ADDRESS') != 'city@e98.hu') {
            $bcc[] = ('city@e98.hu');
        }

        $this->info('Notification sent: '.$orderArchiveId.' address:'.implode(',', array_merge($to, $bcc)));

        if ($this->sendEmail) {
            \Mail::send('email.supplierNotifier', [
                'originalEmailHTML' => $HTMLOrder,
            ], function ($m) use ($fileType, $attachments, $to, $bcc) {

                // $subject='Delirest - '.$orderData['profit_center']['name'].' - '.$orderData['humanId'];
                $subject = 'EMLÉKEZTETŐ A Szállítói webrendelőn érkezett megrendelés visszaigazolására';
                /*            if($orderData['orderFlag']==OrderFlag::modifier){
                                $subject.=' MÓDOSÍTÁS';
                            }*/
                $m->subject($subject);

                foreach ($to as $address) {
                    $m->to($address);
                }
                foreach ($bcc as $address) {
                    $m->bcc($address);
                }

                // $m->attach($attach,['as'=>$fileNameWithExt]);
                if ($fileType !== 'none') {
                    if (is_array($attachments) && count($attachments) > 0) {
                        foreach ($attachments as $attachData) {
                            $m->attachData($attachData['attach'], $attachData['fileNameWithExt']);
                        }
                    }
                }
            });
        }

    }

    public function checkUnprocessedOrderNotification()
    {

        $Orders = OrderArchive::select('id')->where('sentTime', '>', Carbon::now()->subWeek()->toDateTimeString())->whereNull('confirmed')->get();
        // OrderArchive::groupBy()
        // dd($Orders->toArray());

        $NeedNotification = SupplierNotifierModel::whereIn('order_archive_id', $Orders->pluck('id'))
            ->whereNull('sent')
            // ->where('id','<',1)
            ->where('need_send', '<', DB::raw("'".Carbon::now()->toDateTimeString()."'"))
            ->orderBy('need_send');
        //        dd($NeedNotification->toSql(),$NeedNotification->getBindings());

        $orderFinished = [];
        if ($NeedNotification->get()->count() < 1) {
            $this->info('No active Supplier Order Notification this moment');

            return;
        }

        foreach ($NeedNotification->get() as $notification) {
            // var_dump($notification->order_archive_id);
            // dd($notification->order_archive_id);
            if (! in_array($notification->order_archive_id, $orderFinished)) {
                $this->sendNotification($notification->order_archive_id);
                $orderFinished[] = $notification->order_archive_id;
                // var_dump('add'.$notification->order_archive_id);
                // var_dump($notification->toArray());
            }
        }

        /*
         * kodnál az összes olyat ami régebbi mint mostani dátum hogy ne küldjön újat.
         */
        $Notifies = SupplierNotifierModel::whereIn('order_archive_id', $orderFinished)->whereNull('sent')->where('need_send', '<', Carbon::now());
        if ($Notifies->get()->count() > 0) {
            $Nid = $Notifies->pluck('id')->toArray();
            $Notifies->update(['sent' => Carbon::now()]);
            $this->info('SupplierNotifier update:'.implode(',', $Nid));
        }
    }

    public function testTimes()
    {

        /*
         * Pl: hétfőn 7 órakkor leadott megrendelés emlékeztető hetfő 10,15 óra.
         */
        /*  $searchDay = 'Monday';
          $searchDate = new Carbon(); //or whatever Carbon instance you're using
          $lastDay = Carbon::createFromTimeStamp(strtotime("last $searchDay", $searchDate->timestamp));
          $lastDay->setTime(7,rand(0,58));
          $checkTime=$lastDay->toDateTimeString();
          //$this->nowTime=$lastDay->setTime(7+rand(0,13),rand(0,58));
          $this->nowTime=$lastDay->setTime(10,rand(0,58));
          $this->nowTime=$lastDay->setTime(15,rand(0,58));
          $this->info('nowTime>'.$this->nowTime->toDateTimeString());
          $this->diffTime($checkTime);*/
        $checkTime = Carbon::parse('2023-09-04');
        $checkTime->setTime(7, rand(0, 58));
        $nowTime = Carbon::parse('2023-09-04');
        $nowTime->setTime(10, 59);
        $nowTime->setTime(15, 59);
        $this->nowTime = $nowTime;
        // $this->info('nowTime>'.$this->nowTime->toDateTimeString());
        // $this->diffTime($checkTime);

        /*
         * hétfőn 21 órakkor leadott megrendelés emlékeztető kedd 7,12 óra.
         */
        $checkTime = Carbon::parse('2023-09-04');
        $checkTime->setTime(21, rand(0, 58));
        $nowTime = Carbon::parse('2023-09-05');
        /*
                $nowTime->setTime(5,59);
                $nowTime->setTime(7,59);
                $nowTime->setTime(10,59);
                $nowTime->setTime(12,59);

        */
        $nowTime->setTime(12, 59);
        $this->nowTime = $nowTime;
        //        $this->info('nowTime>'.$this->nowTime->toDateTimeString());
        //        $this->diffTime($checkTime);

        /*
         * Kedden 18 órakkor leadott megrendelés emlékeztető Szerda 7,12 óra.
         */
        $checkTime = Carbon::parse('2023-09-05');
        $checkTime->setTime(18, rand(0, 58));
        $nowTime = Carbon::parse('2023-09-06');
        /*
                $nowTime->setTime(5,59);
                $nowTime->setTime(7,59);
                $nowTime->setTime(10,59);
                $nowTime->setTime(12,59);

        */
        $nowTime->setTime(12, 59);
        $this->nowTime = $nowTime;
        //        $this->info('nowTime>'.$this->nowTime->toDateTimeString().' '.$this->nowTime->format('l'));
        //        $this->diffTime($checkTime);

        /*
         * Péntek 13 órakkor leadott megrendelés emlékeztető hétfő 7,12 óra.
         */
        $checkTime = Carbon::parse('2023-09-08');
        $checkTime->setTime(13, rand(0, 58));
        $nowTime = Carbon::parse('2023-09-11');
        /*
                $nowTime->setTime(5,59);
                $nowTime->setTime(7,59);
                $nowTime->setTime(10,59);
                $nowTime->setTime(12,59);

        */
        $nowTime->setTime(16, 50);
        $this->nowTime = $nowTime;

        /*
        $this->info('nowTime>'.$this->nowTime->toDateTimeString().' '.$this->nowTime->format('l'));
        $this->makeTime($checkTime);
        */

        /*
         * Péntek 13 órakkor leadott megrendelés emlékeztető hétfő 7,12 óra.
         */
        $checkTime = Carbon::parse('2023-09-08');
        $checkTime->setTime(19, rand(0, 58));

        $nowTime = Carbon::parse('2023-09-11');
        /*
                $nowTime->setTime(5,59);
                $nowTime->setTime(7,59);
                $nowTime->setTime(10,59);
                $nowTime->setTime(12,59);

        */
        $nowTime->setTime(16, 50);
        $this->nowTime = $nowTime;
        $this->makeTime($checkTime);

        /*
        $this->info('nowTime>'.$this->nowTime->toDateTimeString().' '.$this->nowTime->format('l'));
        $this->diffTime($checkTime);
*/

    }
}
