<?php

namespace App\Console\Commands;

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

class ImportPrices extends Command
{
    protected $signature = 'app:import-prices';
    protected $description = 'Import prices from prices table to price_data table';

    public function handle()
    {
        $this->info('Starting import process...');

        $priceRecords = DB::table('prices')->get();
        $this->info('Fetched ' . $priceRecords->count() . ' records from the prices table.');

        $insertData = [];
        $this->info('Memory usage before loop: ' . memory_get_usage(true));

        foreach ($priceRecords as $priceRecord) {
            $this->info('Processing price record ID: ' . $priceRecord->id);
            $decodedPrices = json_decode($priceRecord->json_data, true);

            if (json_last_error() !== JSON_ERROR_NONE) {
                $this->error('Invalid JSON for price record ID: ' . $priceRecord->id . ' - Error: ' . json_last_error_msg());
                continue;
            }

            if (!is_array($decodedPrices) || empty($decodedPrices)) {
                $this->error('No valid data found for price record ID: ' . $priceRecord->id);
                continue;
            }

            foreach ($decodedPrices as $cityData) {
                foreach ($cityData as $cityId => $data) {
                    $rate = ($data['price'] === null || $data['price'] === '') ? '11' : $data['price'];
                    $this->info('Rate for city ID ' . $cityId . ': ' . $rate);

                    $insertData[] = [
                        'price_id' => $priceRecord->id,
                        'price_city_id' => $cityId,
                        'rate' => $rate,
                        'record_date' => $priceRecord->record_date,
                        'created_at' => now(),
                        'updated_at' => now(),
                    ];
                }
            }
        }

        $this->info('Finished processing all price records.');
        $this->info('Total records to insert: ' . count($insertData));
        $this->info('Insert Data: ' . json_encode($insertData, JSON_PRETTY_PRINT));

        if (!empty($insertData)) {
            DB::enableQueryLog();
            try {
                $chunks = array_chunk($insertData, 500);
                foreach ($chunks as $chunk) {
                    DB::table('price_data')->insert($chunk);
                }
                $this->info('Prices imported successfully! Total records inserted: ' . count($insertData));
            } catch (\Exception $e) {
                $this->error('Error during insertion: ' . $e->getMessage());
                \Log::error('Error during insertion: ', ['error' => $e]);
            }
            $this->info('Executed Queries: ' . json_encode(DB::getQueryLog(), JSON_PRETTY_PRINT));
        } else {
            $this->error('No prices to import.');
        }
    }
}
