<?php

namespace Database\Seeders;

use App\Models\SystemSetting;
use App\Models\User;

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;

class UserSeeder extends Seeder
{
    public function run(): void
    {
        $items = [
            [
                'name' => 'Admin',
                'email' => 'admin@gmail.com',
                'phone_number' => '08911232',
                'password' => Hash::make('secret2025'),
                'role' => 'admin',
            ],
            [
                'name' => 'User',
                'email' => 'user@gmail.com',
                'phone_number' => '08911234',
                'password' => Hash::make('secret2025'),
                'role' => 'user',
            ]
        ];

        DB::beginTransaction();

        try {
            $user_balance = SystemSetting::getNewUserBalance();

            foreach ($items as $item) {
                $user = User::where('email', $item['email'])->first();
                if ($user) {
                    $this->command->warn("User {$user->name} already exists.");
                    continue;
                }
                $user = User::create($item);

                if (!$user)
                    $this->command->error("Failed to create user.");
            }

            DB::commit();

            $this->command->info('Users created successfully.');
        } catch (\Exception $e) {
            DB::rollBack();
            $this->command->error($e->getMessage());
        }
    }
}
