<?php

namespace App\Console\Commands;

use App\Models\PackingList;
use Carbon\Carbon;
use Illuminate\Console\Command;

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Fix PackingList';

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

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $packingLists = PackingList::whereDoesntHave('packages')->get();

        if ($packingLists->isNotEmpty()) {
            $this->info(Carbon::now() . ' : ' . $this->description . ' cron started.');
            $start = Carbon::now();

            $restoredPackagesCount = 0;
            $restoredPackagesIds = [];

            // Eager loading packages for all packing lists
            $packingLists->load(['packages' => function ($query) {
                $query->onlyTrashed();
            }]);

            foreach ($packingLists as $packingList) {
                $deletedPackages = $packingList->packages->filter(function ($package) use ($restoredPackagesIds) {
                    // Filter out packages that have already been restored
                    return !in_array($package->id, $restoredPackagesIds);
                });

                if ($deletedPackages->isNotEmpty()) {
                    $groupedPackages = $deletedPackages->groupBy(function ($item) {
                        return $item->only(['type', 'description', 'width', 'height', 'length', 'weight', 'quantity']);
                    });

                    foreach ($groupedPackages as $group) {
                        $latestPackage = $group->sortByDesc('created_at')->first();

                        // Check if the package ID is already restored before attempting to restore it
                        if (!in_array($latestPackage->id, $restoredPackagesIds)) {
                            $latestPackage->restore();
                            $this->info('Package ID: ' . $latestPackage->id . ' has been restored');
                            $restoredPackagesCount++;
                            $restoredPackagesIds[] = $latestPackage->id;
                        }
                    }
                }
            }

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

            $this->info(Carbon::now() . ' : Done ' . $this->description . '. ElapsedTime: ' . $elapsedTime . '.');
            $this->info('Restored Packages Count: ' . $restoredPackagesCount);
        }
    }
}
