<?php

namespace Database\Seeders\New;

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use JsonMachine\Items;
use JsonMachine\JsonDecoder\ExtJsonDecoder;

class CustomersTableSeeder extends Seeder
{
    public function run()
    {
        $table = 'users';
        DB::table($table)->truncate();

        $items = Items::fromFile(
            database_path('data/customers.json'),
            ['decoder' => new ExtJsonDecoder(true)]
        );

        foreach ($items as $data) {
            DB::table($table)->insert([
                'id' => $data['id'],
                'first_name' => $data['firstname'] ?? Str::random(6),
                'last_name' => $data['lastname'] ?? Str::random(6),
                'email' => $data['email'],
                'phone_number' => preg_match('/^993/', $data['phone']) ? preg_replace('/^993/', '', $data['phone']) : null,
                'created_at' => $data['created_at'],
                'updated_at' => $data['updated_at'],
            ]);
        }

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