<?php

use App\Models\Booking;
use App\Models\Transaction;
use App\Classes\ValueObjects\Constants\TransactionType;

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;

class UpdateTransactionBillOwnerSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        DB::beginTransaction();

        $bookings = Booking::all();

        foreach ($bookings as $booking) {

            $transactions = $booking->transactions()->bills()->get();
            foreach ($transactions as $row) {
                $key = 0;
                $bills = $booking->transactions()->bills()->where('original_amount', '=', $row->original_amount)->get();
                if(count($bills) > 1){ $key = $bills->search(function($bill)use($row){ return $bill->id === $row->id; }); }
                $paymentTransaction = $booking->transactions()->payments()->complete()->where('original_amount', '=', $row->original_amount)->skip($key)->first();

                $row->owner_type = Transaction::class;
                $row->owner_id = $paymentTransaction->id;
                $row->updated_at = $row->updated_at;
                $row->update();
            }
        }

        DB::commit();
    }
}
