<?php

namespace App\Classes\Jobs\Commands\V2;

use Carbon\Carbon;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
use App\Models\Bank;
use App\Models\Booking;


class DeleteDuplicate1688BankAccountV2CommandJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;


    public function handle()
    {
        Log::info(Carbon::now() . ': Start job - Delete duplicate 1688 account in banks table.');
        $start   = new Carbon();

        // account_no: 1688 LOGIN ID/EMAIL/PHONE
        // holder_name: password
        // bank_branch: 6-digit pin

        $records = Bank::where('type', 3)->get();

        $groupedBanks = $records->groupBy(function($item, $key) {
            return $item['company_id'] . '-' . $item['account_no'];
        });

        foreach ($groupedBanks as $key => $banksWithSameUserAndAccountNo) {
            // Sort banks by created_at or updated_at to find the latest one
            $sortedBanks = $banksWithSameUserAndAccountNo->sortByDesc('created_at');

            // Retain the latest bank
            $latestBank = $sortedBanks->first();

            // Get all IDs except the latest one
            $idsToDelete = $sortedBanks->pluck('id')->slice(1);

            foreach ($idsToDelete as $id) {
                Booking::where('bank_id', $id)->update([
                    'bank_id' => $latestBank->id
                ]);
            }

            Log::info('for company id: ' . $latestBank->company_id . ', account no: ' . $latestBank->account_no . ', duplicated id: ' . $idsToDelete);
            // Delete the rest
            Bank::whereIn('id', $idsToDelete)->delete();
        }

        $end = new Carbon();
        $elapsedTime = $start->diff($end)->format('%H:%I:%S');
        Log::info(Carbon::now() . ': End job - Delete duplicate 1688 account in banks table. ElapsedTime: ' . $elapsedTime . '.');
    }
}
