<?php

namespace Database\Seeders;

use App\Models\User;
use Exception;
use File;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;

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

    /**
     * Starter kit data
     */
    public function seedStarterKit(): void
    {
        collect([
            [
                'first_name' => 'Nurmuhammet',
                'last_name' => 'Allanov',
                'email' => 'nurmuhammet@mail.com',
                'password' => bcrypt('payload10'),
            ],
            [
                'first_name' => 'Admin',
                'last_name' => 'Admin',
                'email' => 'admin@smartelektronika.com',
                'password' => bcrypt('PuteraSeroja'),
            ]
        ])->each(function ($data) {
            $user = User::create($data);

            $user->assignRole('admin');
        });
    }

    /**
     * Seed old postshop data
     */
    public function seedOldData(): void
    {
        User::truncate();

        $users = json_decode(File::get('database/data/users.json'));

        $table = 'users';
        foreach ($users as $user) {
            if ($user->deleted_at) {
                continue;
            }

            try {
                DB::table($table)->insert([
                    'id' => $user->id,
                    'first_name' => $user->first_name,
                    'last_name' => $user->last_name,
                    'email' => $user->email,
                    'phone_number' => $user->phone_number,
                    'email_verified_at' => $user->email_verified_at,
                    'password' => $user->password ?: bcrypt('gizlin'),
                    'verified' => $user->verified_by_admin,
                    'remember_token' => $user->remember_token,
                    'created_at' => $user->created_at,
                    'updated_at' => $user->updated_at,
                ]);
            } catch (Exception $e) {
                info(['users error: ' => $e->getMessage()]);
            }
        }

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