<?php

namespace Database\Seeders;

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

class ProductTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        $this->seedOldData();
    }

    /**
     * Seed old postshop data
     */
    public function seedOldData(): void
    {
        $table = 'products';
        DB::table($table)->delete();

        $datas = collect(json_decode(File::get('database/data/products.json')));

        foreach ($datas as $data) {
            try {
                DB::table($table)->insert([
                    'id' => $data->id,
                    'parent_id' => $data->parent_id,
                    'brand_id' => $data->brand_id,
                    'name' => $data->name,
                    'slug' => $data->slug,
                    'description' => $data->description,
                    'sku' => $data->sku,
                    'barcode' => $data->barcode,
                    'stock' => json_decode($data->options)?->quantity,
                    'security_stock' => $data->security_stock,
                    'old_price_amount' => $data->old_price_amount,
                    'price_amount' => $data->price_amount,
                    'cost_amount' => $data->cost_amount,
                    'seo_title' => $data->seo_title,
                    'seo_description' => $data->seo_description,
                    'options' => json_encode([
                        'back_order' => $data->backorder,
                        'height_unit' => $data->height_unit,
                        'height_value' => $data->height_value,
                        'depth_unit' => $data->depth_unit,
                        'depth_value' => $data->depth_value,
                        'weight_value' => $data->weight_value,
                        'width_unit' => $data->width_unit,
                        'weight_unit' => $data->weight_unit,
                        'width_value' => $data->width_value,
                        'volume_value' => $data->volume_value,
                        'volume_unit' => $data->volume_unit,
                    ]),
                    'is_visible' => $data->is_visible,
                    'created_at' => now(),
                    'updated_at' => now(),
                ]);
            } catch (Exception $e) {
                info(['Ignore error', $e->getMessage()]);
            }
        }

        DB::statement("
            SELECT setval('{$table}_id_seq', (SELECT MAX(id) from {$table}))
        ");
    }
}
