<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class PopulateProductOrganisations extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'populate:product-organisations {--product_id= : The product ID to associate with organisations}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Populate product_organisations table with organisation IDs';

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        // Get the product ID from the command argument
        $productId = $this->option('product_id');
        
        if (!$productId) {
            $this->error('Please provide a product ID using the --product_id option.');
            return 1;
        }

        // Get the current timestamp for created_at and updated_at
        $timestamp = now();

        // Insert data from the organisations table into the product_organisations table
        DB::table('organisations')->orderBy('id')->select('id')->chunk(100, function ($organisations) use ($timestamp, $productId) {
            foreach ($organisations as $organisation) {
                DB::table('product_organisations')->insert([
                    'organisation_id' => $organisation->id,
                    'product_id' => $productId,
                    'is_active' => 1,
                    'created_at' => $timestamp,
                    'updated_at' => $timestamp,
                ]);
            }
        });

        $this->info('Product organisations have been populated successfully.');
        return 0;
    }
}
