<?php

namespace Database\Seeders;

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

class DatabaseSeeder extends Seeder
{
    use WithoutModelEvents;

    /**
     * Seed the application's database.
     */
    public function run(): void
    {
        // --- 1. SEED USER OWNER ---
        // PERBAIKAN: Ubah email menjadi username
        User::updateOrCreate(
            ['username' => 'owner'], 
            [
                'name' => 'Super Admin',
                'password' => Hash::make('password'),
                'role' => 'owner',
            ]
        );

        // --- 2. SEED DAFTAR AKUN (CHART OF ACCOUNTS) ---
        $accounts = [
            // ASSETS (1xxx)
            ['code' => '1001', 'name' => 'Kas Kecil', 'group' => 'asset', 'category' => 'Kas/Bank'],
            ['code' => '1002', 'name' => 'Kas Besar', 'group' => 'asset', 'category' => 'Kas/Bank'],
            ['code' => '1003', 'name' => 'Bank Mandiri Utama', 'group' => 'asset', 'category' => 'Kas/Bank'],
            ['code' => '1004', 'name' => 'Bank BCA cabang tegal', 'group' => 'asset', 'category' => 'Kas/Bank'],
            ['code' => '1005', 'name' => 'Deposito', 'group' => 'asset', 'category' => 'Kas/Bank'],
            ['code' => '1006', 'name' => 'Bank BCA Cabang Purwokerto', 'group' => 'asset', 'category' => 'Kas/Bank'],
            ['code' => '1007', 'name' => 'Bank BCA Cabang Brebes', 'group' => 'asset', 'category' => 'Kas/Bank'],
            ['code' => '1101', 'name' => 'Piutang Pelanggan', 'group' => 'asset', 'category' => 'Piutang'],
            ['code' => '1103', 'name' => 'Account Receivable IDR', 'group' => 'asset', 'category' => 'Piutang'],
            ['code' => '1104', 'name' => 'Advance Purchase IDR', 'group' => 'asset', 'category' => 'Piutang'],
            ['code' => '1105', 'name' => 'Piutang Titipan Kanvas', 'group' => 'asset', 'category' => 'Piutang'],
            ['code' => '1106', 'name' => 'Piutang Karyawan / Kasbon', 'group' => 'asset', 'category' => 'Piutang'], // AKUN HRD
            ['code' => '1190', 'name' => 'R/K Pusat', 'group' => 'asset', 'category' => 'Kas/Bank'],
            ['code' => '1191', 'name' => 'R/K Cabang Tegal', 'group' => 'asset', 'category' => 'Kas/Bank'],
            ['code' => '1192', 'name' => 'R/K Cabang Purwokerto', 'group' => 'asset', 'category' => 'Kas/Bank'],
            ['code' => '1193', 'name' => 'R/K Cabang Brebes', 'group' => 'asset', 'category' => 'Kas/Bank'],
            ['code' => '1200', 'name' => 'Persediaan Barang Dagang', 'group' => 'asset', 'category' => 'Persediaan'],
            ['code' => '1201', 'name' => 'Barang Terkirim', 'group' => 'asset', 'category' => 'Persediaan'],
            ['code' => '1300', 'name' => 'Perlengkapan', 'group' => 'asset', 'category' => 'Aktiva Lancar'],
            ['code' => '1400', 'name' => 'Sewa Gedung Dibayar Dimuka', 'group' => 'asset', 'category' => 'Aktiva Lancar'],
            ['code' => '1500', 'name' => 'Asuransi Dibayar Dimuka', 'group' => 'asset', 'category' => 'Aktiva Lancar'],
            ['code' => '1600', 'name' => 'PPn Masukan', 'group' => 'asset', 'category' => 'Aktiva Lancar'],
            ['code' => '1701', 'name' => 'Tanah', 'group' => 'asset', 'category' => 'Aktiva Tetap'],
            ['code' => '1702', 'name' => 'Gedung', 'group' => 'asset', 'category' => 'Aktiva Tetap'],
            ['code' => '1703', 'name' => 'Kendaraan', 'group' => 'asset', 'category' => 'Aktiva Tetap'],
            ['code' => '1704', 'name' => 'Peralatan', 'group' => 'asset', 'category' => 'Aktiva Tetap'],
            ['code' => '1705', 'name' => 'Inventaris Kantor', 'group' => 'asset', 'category' => 'Aktiva Tetap'],
            ['code' => '1710', 'name' => 'Akumulasi Depresiasi Fixed Asset', 'group' => 'asset', 'category' => 'Aktiva Tetap'],

            // LIABILITIES (2xxx)
            ['code' => '2101', 'name' => 'Hutang Dagang (Supplier)', 'group' => 'liability', 'category' => 'Hutang Dagang'],
            ['code' => '2102', 'name' => 'Uang Muka Penjualan', 'group' => 'liability', 'category' => 'Hutang Dagang'],
            ['code' => '2103', 'name' => 'PPn Keluaran', 'group' => 'liability', 'category' => 'Hutang Lancar Lainnya'],
            ['code' => '2105', 'name' => 'Hutang Giro Keluar', 'group' => 'liability', 'category' => 'Hutang Lancar Lainnya'],
            ['code' => '2110', 'name' => 'Hutang Upah Pabrik (BTKL)', 'group' => 'liability', 'category' => 'Hutang Lancar Lainnya'], // AKUN HRD
            ['code' => '2112', 'name' => 'Hutang Gaji & Tunjangan Staf', 'group' => 'liability', 'category' => 'Hutang Lancar Lainnya'], // AKUN HRD
            ['code' => '2113', 'name' => 'Hutang BPJS Ketenagakerjaan / Kesehatan', 'group' => 'liability', 'category' => 'Hutang Lancar Lainnya'], // AKUN HRD
            ['code' => '2115', 'name' => 'Hutang PPh 21', 'group' => 'liability', 'category' => 'Hutang Lancar Lainnya'], // AKUN HRD
            ['code' => '2200', 'name' => 'Hutang Pembelian Belum Ditagih', 'group' => 'liability', 'category' => 'Hutang Lancar Lainnya'],
            ['code' => '2300', 'name' => 'Hutang Jangka Panjang', 'group' => 'liability', 'category' => 'Hutang Jangka Panjang'],

            // EQUITY (3xxx)
            ['code' => '3100', 'name' => 'Modal Disetor', 'group' => 'equity', 'category' => 'Ekuitas'],
            ['code' => '3200', 'name' => 'Retained Earnings (Laba Ditahan)', 'group' => 'equity', 'category' => 'Ekuitas'],

            // REVENUE (4xxx & 7xxx)
            ['code' => '4001', 'name' => 'Pendapatan Penjualan', 'group' => 'revenue', 'category' => 'Pendapatan'],
            ['code' => '4002', 'name' => 'Pendapatan Jasa Kirim', 'group' => 'revenue', 'category' => 'Pendapatan'],
            ['code' => '4003', 'name' => 'Retur Penjualan', 'group' => 'revenue', 'category' => 'Pendapatan'],
            ['code' => '4004', 'name' => 'Potongan Penjualan', 'group' => 'revenue', 'category' => 'Pendapatan'],
            ['code' => '7100', 'name' => 'PENDAPATAN DILUAR USAHA', 'group' => 'revenue', 'category' => 'Pendapatan Lain'],

            // EXPENSES (5xxx, 6xxx, & 7xxx)
            ['code' => '5000', 'name' => 'Harga Pokok Penjualan (HPP)', 'group' => 'expense', 'category' => 'HPP'],
            ['code' => '5001', 'name' => 'Biaya Upah Harian Pabrik (BTKL Aktual)', 'group' => 'expense', 'category' => 'HPP'], // AKUN HRD
            ['code' => '6101', 'name' => 'Biaya Iklan', 'group' => 'expense', 'category' => 'Beban Operasional'],
            ['code' => '6102', 'name' => 'Biaya Komisi', 'group' => 'expense', 'category' => 'Beban Operasional'],
            ['code' => '6201', 'name' => 'Biaya Gaji & Tunjangan', 'group' => 'expense', 'category' => 'Beban Operasional'],
            ['code' => '6211', 'name' => 'Biaya Listrik', 'group' => 'expense', 'category' => 'Beban Operasional'],
            ['code' => '6212', 'name' => 'Biaya PAM (Air)', 'group' => 'expense', 'category' => 'Beban Operasional'],
            ['code' => '6215', 'name' => 'Biaya Ekspedisi & Pos', 'group' => 'expense', 'category' => 'Beban Operasional'],
            ['code' => '6221', 'name' => 'Biaya Sewa Gedung', 'group' => 'expense', 'category' => 'Beban Operasional'],
            ['code' => '7201', 'name' => 'Biaya Bunga Pinjaman', 'group' => 'expense', 'category' => 'Beban Lain-lain'],
            ['code' => '7202', 'name' => 'Biaya Admin Bank', 'group' => 'expense', 'category' => 'Beban Lain-lain'],
        ];

        foreach ($accounts as $account) {
            DB::table('accounts')->updateOrInsert(
                ['code' => $account['code']],
                array_merge($account, [
                    'is_active' => 1,
                    'created_at' => now(), 
                    'updated_at' => now()
                ])
            );
        }

        // --- 3. SEED SETTING DEFAULT AKUN (MAPPING) ---
        $defaultMappings = [
            ['setting_key' => 'cash_sales_account', 'code' => '1105'],
            ['setting_key' => 'bank_bca_account', 'code' => '1004'],
            ['setting_key' => 'bank_mandiri_account', 'code' => '1003'],
            ['setting_key' => 'inventory_account', 'code' => '1200'],
            ['setting_key' => 'sales_revenue_account', 'code' => '4001'],
            ['setting_key' => 'cost_of_goods_sold_account', 'code' => '5000'],
            ['setting_key' => 'shipping_revenue_account', 'code' => '4002'],
            ['setting_key' => 'ppn_output_account', 'code' => '2103'],
            ['setting_key' => 'payable_account', 'code' => '2101'],
            ['setting_key' => 'receivable_account', 'code' => '1101'],
            ['setting_key' => 'sales_discount_account', 'code' => '4004'],
            ['setting_key' => 'sales_return_account', 'code' => '4003'],
            ['setting_key' => 'ppn_input_account', 'code' => '1600'],
            ['setting_key' => 'default_migration_equity_account', 'code' => '3100'],
            ['setting_key' => 'default_receivable_account', 'code' => '1101'],
            ['setting_key' => 'dp_purchase_account', 'code' => '1104'],
            ['setting_key' => 'persediaan_barang', 'code' => '1200'],
            ['setting_key' => 'hutang_usaha', 'code' => '2101'],
            ['setting_key' => 'giro_payable_account', 'code' => '2105'],
            
            // === TAMBAHAN MAPPING UNTUK PAYROLL & HRD ===
            ['setting_key' => 'employee_receivable_account', 'code' => '1106'],
            ['setting_key' => 'payable_salary_account', 'code' => '2112'], 
            ['setting_key' => 'payable_bpjs_account', 'code' => '2113'], 
            ['setting_key' => 'payable_pph21_account', 'code' => '2115'],
            ['setting_key' => 'expense_salary_account', 'code' => '6201'],
            ['setting_key' => 'expense_btkl_account', 'code' => '5001'],
            ['setting_key' => 'payable_btkl_account', 'code' => '2110'], 
            ['setting_key' => 'payable_bpjs_tk_account', 'code' => '2113'], 
            ['setting_key' => 'payable_bpjs_kes_account', 'code' => '2113'],
        ];

        foreach ($defaultMappings as $map) {
            $account = DB::table('accounts')->where('code', $map['code'])->first();
            if ($account) {
                DB::table('accounting_settings')->updateOrInsert(
                    ['setting_key' => $map['setting_key']],
                    [
                        'account_id' => $account->id,
                        'created_at' => now(),
                        'updated_at' => now()
                    ]
                );
            }
        }

        // --- 4. SEED APP SETTINGS ---
        DB::table('app_settings')->updateOrInsert(
            ['id' => 1],
            [
                'brand_name' => 'P-LINK ERP',
                'is_online_store_open' => 1,
                'brand_logo' => 'logos/A33vcJRE3vE0kt6E0El3lByHiDrdZzT5qvBSWDhX.png',
                'primary_color' => 'Blue',
                'admin_whatsapp' => '62816664477',
                'whatsapp_format' => "Halo admin, saya mau pesan :\n{items}\n\nTotal            : {total}\nPelanggan   : {customer} \nAlamat        : {address}",
                'created_at' => now(),
                'updated_at' => now()
            ]
        );

        // --- 5. SEED SETTINGS (Tarif PPN & Poin) ---
        $settings = [
            ['key' => 'ppn_rate', 'label' => 'Tarif PPN (%)', 'value' => '11', 'type' => 'number'],
            ['key' => 'point_rate', 'label' => 'Konversi Poin (Rp per 1 Poin)', 'value' => '1000000', 'type' => 'number'],
        ];

        foreach ($settings as $setting) {
            DB::table('settings')->updateOrInsert(
                ['key' => $setting['key']],
                array_merge($setting, [
                    'created_at' => now(),
                    'updated_at' => now()
                ])
            );
        }

        // --- 6. PANGGIL SEEDER LAINNYA SESUAI URUTAN RELASI ---
        $this->call([
            PermissionSeeder::class,   // 1. Buat Hak Akses & Role duluan
            RegionSeeder::class,       // 2. Buat data Provinsi, Kota, Kecamatan
            MasterDataSeeder::class,   // 3. Buat Cabang, Karyawan (assign role), Pelanggan, dll
        ]);
    }
}