<?php

namespace App\Console\Commands;

use App\Models\Bank;
use App\Models\Booking;
use Illuminate\Console\Command;
use Carbon\Carbon;
use Illuminate\Support\Facades\Log;

class DeleteDuplicate1688BankAccount extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'banks:deleteDuplicate1688Account';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Delete duplicate 1688 account in banks table';

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

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        // 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
                ]);
            }
        
            $this->info('for company id: ' . $latestBank->company_id . ', account no: ' . $latestBank->account_no . ', duplicated id: ' . $idsToDelete);
            // Delete the rest
            Bank::whereIn('id', $idsToDelete)->delete();
        }
    }
}
