<?php

namespace App\Console\Commands;

use App\Models\Order;
use App\Models\OrderNumber;
use App\Models\ProductGroup;
use Box\Spout\Common\Exception\IOException;
use Box\Spout\Common\Exception\UnsupportedTypeException;
use Box\Spout\Reader\Exception\ReaderNotOpenedException;
use Carbon\Carbon;
use Illuminate\Console\Command;

class EmegrendelesOrderNumberChange extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'emegrendeles:orderNumberChange {workerNumber=1}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Change and convert order numbers ';

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

    private function getMaxSupplierOrderNumber(): int
    {
        // SELECT max(supplierOrderNumber) FROM `order_archives` WHERE deliveryDate>'2025-01-01';

        return \DB::table('order_archives')
            ->where('deliveryDate', '>', '2025-01-01')
            ->max('supplierOrderNumber');
    }

    private function setDefaultOrderNumberForSuppliers(): void
    {
        $this->info('Start setDefaultOrderNumberForSuppliers');
        $supplierIds = \DB::table('order_archives')
            ->selectRaw('DISTINCT(supplier_id)')
            ->orderBy('supplier_id')
            ->get();
        foreach ($supplierIds as $supplierId) {

            $o = OrderNumber::create([
                'id' => $this->startOrderNumber,
                'year' => 25,
                'supplier_id' => $supplierId->supplier_id,
                'order_id' => 1000 + $supplierId->supplier_id,
            ]);

        }
        $this->info('End setDefaultOrderNumberForSuppliers');
    }

    private function changeTable()
    {
        $this->info('Start changeTable');
        $this->info('change id field, and add supplier_order_number field');
        \Schema::table('order_numbers', function (\Illuminate\Database\Schema\Blueprint $table) {

            $table->integer('id')->change()->unsigned();
            $table->dropIndex('PRIMARY');
            $table->integer('supplier_order_number')->unsigned()->after('id');
            // $table->string('new_column');
            // $table->dropColumn('old_column');
            // $table->integer('existing_column')->nullable();
        });
        $this->info('set supplier_order_number = id');
        \DB::table('order_numbers')->update(['supplier_order_number' => \DB::raw('id')]);
        $startId = 10000;
        $this->info('recreate id field value');
        foreach (\DB::table('order_numbers')->get() as $orderNumber) {
            \DB::table('order_numbers')
                ->where('id', $orderNumber->id)
                ->where('order_id', $orderNumber->order_id)
                ->update(['id' => $startId]);
            $startId++;
        }
        \Schema::table('order_numbers', function (\Illuminate\Database\Schema\Blueprint $table) {
            /*
             ALTER TABLE `order_numbers` CHANGE `id` `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT, add PRIMARY KEY (`id`);
             */
            // $table->integer('id')->change()->autoIncrement()->primary();
            $this->info(' set id field auto increment and primary key');
            \DB::statement('ALTER TABLE `order_numbers` CHANGE `id` `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT, ADD PRIMARY KEY (`id`)');
            $this->info(' set unique key on supplier_order_number, year, supplier_id');
            $table->unique(['supplier_order_number', 'year', 'supplier_id'], 'unique_supplier_order_number_year_supplier_id');

        });

    }

    private function createSupplierOrderNumber(int $orderId): ?array
    {
        $ret = [];
        if ($Order = Order::find($orderId)) {
            // dd($Order->toArray());
            if ($o = OrderNumber::where('order_id', $orderId)->get()->first()) {
            } else {
                $orderYear = Carbon::createFromDate($Order->deliveryDate)->format('y');
                $maxSupplierOrderNumber = OrderNumber::where('supplier_id', $Order->supplier_id)
                    ->where('year', $orderYear)
                    ->max('supplier_order_number');
                $nextSupplierOrderNumber = $maxSupplierOrderNumber ? ($maxSupplierOrderNumber + 1) : 1;
                $this->info($maxSupplierOrderNumber.' '.$nextSupplierOrderNumber);
                $maxRetry = 5;
                while ($maxRetry > 0) {
                    try {
                        $o = OrderNumber::create([
                            'supplier_order_number' => $nextSupplierOrderNumber,
                            'year' => $orderYear,
                            'supplier_id' => $Order->supplier_id,

                        ]);
                        $o->order_id = $orderId;
                        $o->save();
                        break;
                    } catch (\Exception $e) {
                        $this->error('Error creating OrderNumber for supplier:'.$Order->supplier_id.' - '.$e->getMessage());
                        $maxRetry--;
                        $nextSupplierOrderNumber++;
                        usleep(rand(400, 600));
                    }
                }
                if (! $o) {
                    $this->error('Error creating OrderNumber for supplier:'.$Order->supplier_id.' - maxRetry');
                    throw new \Exception('Error creating OrderNumber for supplier:'.$Order->supplier_id);

                    return null;
                }
            }
            $ret = $o->toArray();
        } else {
            $ret = null;
        }

        return $ret;
    }

    /**
     * Execute the console command.
     *
     *
     * @throws IOException
     * @throws UnsupportedTypeException
     * @throws ReaderNotOpenedException
     */
    public function handle(): int
    {
        var_dump(config('app.env', 'env'.now()));
        var_dump(config('app.stage', 'fuck'.now()));

        $this->changeTable();
        /*
        $supplierOrderNumber=$this->createSupplierOrderNumber(16605);
        dd($supplierOrderNumber);
        $this->info("created supplier order number $supplierOrderNumber");
        */

        // $this->generateRandomSupplierNumber();
        return 0;
        /*

        ALTER TABLE `order_numbers` CHANGE `id` `id` INT(10) UNSIGNED NOT NULL;
        ALTER TABLE `order_numbers` DROP PRIMARY KEY;
        ALTER TABLE `order_numbers` ADD `supplier_order_number` INT UNSIGNED NOT NULL AFTER `id`;


                //$name = $this->argument('name');
                \Schema::disableForeignKeyConstraints();
                ProductGroup::truncate();
                \Schema::enableForeignKeyConstraints();
                $this->info('Import End');
                return 0;
         */
    }
}
