<?php

namespace App\Console\Commands;

use App\Models\Container;
use App\Models\ContainerPackingList;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class FixDuplicateContainerReference extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'fix-duplicate-container-reference';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Fix all duplicated container reference';


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

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        ini_set('memory_limit', '-1');

        $this->info(Carbon::now() . ' : Started.');
        $start   = new Carbon();

        $duplicatedContainers = Container::select('reference', DB::raw('COUNT(reference) as count'))
            ->groupBy('reference')
            ->having('count', '>', 1)
            ->get();

        foreach ($duplicatedContainers as $duplicatedContainer) {
            $containers = Container::where('reference', $duplicatedContainer->reference)->get();

            $containers = $containers->sortByDesc(function ($container) {
                return $container->packingLists->count();
            });

            $firstContainer = $containers->shift();

            foreach ($containers as $container) {
                $firstContainer->packingLists()->syncWithoutDetaching($container->packingLists);
                $container->packingLists()->detach();
                $this->info('Deleted container ' . $container->id);
                $container->delete();
            }
        }

        $end = new Carbon();
        $elapsedTime = $start->diff($end)->format('%H:%I:%S');

        $this->info(Carbon::now() . ' : Done. ElapsedTime: ' . $elapsedTime);
    }
}
