<?php

use App\OrderPackage;
use App\Services\OrderPackageService;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class AddOwnerIdToOrderPackages extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('order_packages', function (Blueprint $table) {
            //
            $table->bigInteger('owner_id')->nullable()->index();

        });

        $this->changeOwnerId();

    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('order_packages', function (Blueprint $table) {
            //
            $table->dropColumn('owner_id');
        });
    }

    public function changeOwnerId()
    {
        /**
         * @var OrderPackageService  $order_packages_service
         */
        $order_packages_service = app(OrderPackageService::class);
        OrderPackage::query()->with('order')->chunkById(200,function($order_packages)use($order_packages_service){
            $update_params = [];
            $update_params[] = ['id','owner_id'];
            foreach ($order_packages as $order_package) {
                if($order_package->order && $order_package->order->owner_id){
                    $update_params[] = [
                        'id'=>$order_package->id,
                        'owner_id'=>$order_package->order->owner_id
                    ];
                }
            }
            $order_packages_service->batchUpdate($update_params);
        });
    }
}
