<?php

namespace Database\Seeders;

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

class MasterDataSeeder extends Seeder
{
    public function run(): void
    {
        // 1. SEED CABANG (BRANCHES)
        $branches = [
            ['id' => 1, 'name' => 'Gudang Pusat Tegal', 'code' => 'TG', 'address' => 'Kawasan Industri Talang, Tegal', 'max_delivery_radius_km' => 15],
            ['id' => 2, 'name' => 'Depo Distribusi Brebes', 'code' => 'PB', 'address' => 'Jalur Pantura Brebes', 'max_delivery_radius_km' => 15],
            ['id' => 3, 'name' => 'Cabang Purwokerto', 'code' => 'PWT', 'address' => 'Jl. Gerilya, Purwokerto Selatan', 'max_delivery_radius_km' => 25],
        ];
        foreach ($branches as $branch) {
            DB::table('branches')->updateOrInsert(['id' => $branch['id']], array_merge($branch, ['created_at' => now(), 'updated_at' => now()]));
        }

        // 2. SEED KATEGORI PRODUK
        $categories = [
            ['id' => 1, 'name' => 'PIPA & FITTING', 'is_active' => 1],
            ['id' => 2, 'name' => 'CAT & KIMIA', 'is_active' => 1],
        ];
        foreach ($categories as $cat) {
            DB::table('categories')->updateOrInsert(['id' => $cat['id']], array_merge($cat, ['created_at' => now()]));
        }

        // 3. SEED TIPE PELANGGAN & PELANGGAN DEFAULT (CASH)
        $customerTypes = [
            ['id' => 1, 'name' => 'RETAIL / ECERAN'],
            ['id' => 2, 'name' => 'GROSIR'],
            ['id' => 3, 'name' => 'SEMI-GROSIR'],
            ['id' => 4, 'name' => 'HOREKA & INSTITUSI'],
            ['id' => 5, 'name' => 'MODERN TRADE / MINIMARKET'],
        ];
        foreach ($customerTypes as $type) {
            DB::table('customer_types')->updateOrInsert(['id' => $type['id']], array_merge($type, ['created_at' => now()]));
        }

        DB::table('customers')->updateOrInsert(
            ['customer_code' => 'CUST-GEN-01'],
            [
                'name' => 'CASH / UMUM (TEGAL)',
                'branch_id' => 1,
                'customer_type_id' => 1,
                'address' => 'Pelanggan Walk-in POS',
                'is_active' => 1,
                'price_level' => '1',
                'default_tax_method' => 'include',
                'created_at' => now()
            ]
        );

        // 4. SEED SUPPLIER UTAMA
        $suppliers = [
            ['id' => 1, 'name' => 'PT. RUCIKA INDONESIA', 'contact_person' => 'Bpk. Hendra', 'phone' => '021-888999', 'term_of_payment' => '30', 'is_pkp' => 1],
            ['id' => 2, 'name' => 'PT. AVIAN BRANDS', 'contact_person' => 'Ibu Diana', 'phone' => '031-777888', 'term_of_payment' => '45', 'is_pkp' => 1],
        ];
        foreach ($suppliers as $sup) {
            DB::table('suppliers')->updateOrInsert(['id' => $sup['id']], array_merge($sup, ['created_at' => now()]));
        }

        // 5. SEED DATA PENDUKUNG OPERASIONAL MOBILE/CANVAS
        $reasons = ['Toko Tutup', 'Stok Masih Banyak', 'Kredit Macet / Overdue', 'Harga Kemahalan', 'Toko Sepi'];
        foreach ($reasons as $i => $reason) {
            DB::table('no_order_reasons')->updateOrInsert(['id' => $i + 1], ['reason_name' => $reason, 'created_at' => now()]);
        }

        DB::table('armadas')->updateOrInsert(
            ['license_plate' => 'G 1234 DBG'],
            ['name' => 'ENGKEL KUNING', 'branch_id' => 1, 'created_at' => now()]
        );

        $expenseCats = [
            ['id' => 3, 'name' => 'BIAYA LISTRIK & AIR'],
            ['id' => 4, 'name' => 'BIAYA GAJI & TUNJANGAN'],
            ['id' => 5, 'name' => 'PARKIR & TOL'],
        ];
        foreach ($expenseCats as $ec) {
            DB::table('expense_categories')->updateOrInsert(['id' => $ec['id']], array_merge($ec, ['created_at' => now()]));
        }

        // 6. SEED AKUN KARYAWAN PENTING
        // PERBAIKAN: Mengubah format email menjadi format username
        $users = [
            ['name' => 'Kasir Tegal', 'username' => 'kasir.tegal', 'role' => 'kasir', 'branch_id' => 1],
            ['name' => 'SADEWO', 'username' => 'admin.tgl', 'role' => 'admin_sales', 'branch_id' => 1],
            ['name' => 'WIDI', 'username' => 'admin.gudang', 'role' => 'admin_gudang', 'branch_id' => 1],
            ['name' => 'Wawan Kurniasih', 'username' => 'wawan.tegal', 'role' => 'salesman', 'branch_id' => 1],
            ['name' => 'SETIAWAN', 'username' => 'driver.wawan', 'role' => 'driver', 'branch_id' => 1],
        ];

        foreach ($users as $u) {
            $user = User::updateOrCreate(
                ['username' => $u['username']], // PERBAIKAN: Menggunakan username sebagai patokan
                [
                    'name' => $u['name'],
                    'password' => Hash::make('password'), // Password default: password
                    'role' => $u['role'],
                    'branch_id' => $u['branch_id'],
                ]
            );
            
            // Assign Role Spatie jika library spatie terpasang
            if(class_exists('\Spatie\Permission\Models\Role')) {
                $user->assignRole($u['role']);
            }
        }
    }
}