<?php

namespace Database\Seeders;

use App\Models\Supplier;
use App\Models\User;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Hash;

class SupplierSeeder extends Seeder
{
    public function run(): void
    {
        $suppliers = [
            [
                'code'           => 'SUP-001',
                'name'           => 'PT Sumber Makmur',
                'contact_person' => 'Andi Wijaya',
                'email'          => 'supplier1@gembira.id',
                'phone'          => '081234567890',
                'address'        => 'Jl. Industri No. 10, Jakarta Barat',
                'create_account' => true,
            ],
            [
                'code'           => 'SUP-002',
                'name'           => 'CV Jaya Abadi',
                'contact_person' => 'Budi Santoso',
                'email'          => 'supplier2@gembira.id',
                'phone'          => '081298765432',
                'address'        => 'Jl. Raya Bogor KM 30, Depok',
                'create_account' => true,
            ],
            [
                'code'           => 'SUP-003',
                'name'           => 'UD Berkah Sentosa',
                'contact_person' => 'Dewi Lestari',
                'email'          => 'supplier3@gembira.id',
                'phone'          => '082112345678',
                'address'        => 'Jl. Ahmad Yani No. 55, Surabaya',
                'create_account' => false,
            ],
        ];

        foreach ($suppliers as $data) {
            $userId = null;

            if ($data['create_account']) {
                $user = User::updateOrCreate(
                    ['email' => $data['email']],
                    [
                        'name'      => $data['name'],
                        'password'  => Hash::make('password123'),
                        'is_active' => true,
                    ]
                );
                $user->syncRoles(['supplier']);
                $userId = $user->id;
            }

            Supplier::updateOrCreate(
                ['code' => $data['code']],
                [
                    'name'           => $data['name'],
                    'contact_person' => $data['contact_person'],
                    'email'          => $data['email'],
                    'phone'          => $data['phone'],
                    'address'        => $data['address'],
                    'user_id'        => $userId,
                ]
            );
        }
    }
}
