<?php

namespace App\Database\Seeds;

use CodeIgniter\Database\Seeder;

class MainSeeder extends Seeder
{
    public function run()
    {
        // 1. Insert Bidang
        $dataBidang = [
            ['nama_bidang' => 'Bidang Perencanaan'],
            ['nama_bidang' => 'Bidang Evaluasi'],
            ['nama_bidang' => 'Bidang Ekonomi'],
        ];
        $this->db->table('bidang')->insertBatch($dataBidang);

        // Get IDs for Bidang
        $bidangModel = $this->db->query("SELECT * FROM bidang")->getResultArray();
        $bidangMap = [];
        foreach($bidangModel as $b) {
            $bidangMap[$b['nama_bidang']] = $b['id'];
        }

        // 2. Insert OPD
        $dataOpd = [
            ['nama_opd' => 'Dinas Kesehatan', 'bidang_id' => $bidangMap['Bidang Perencanaan']],
            ['nama_opd' => 'Dinas Pendidikan', 'bidang_id' => $bidangMap['Bidang Evaluasi']],
            ['nama_opd' => 'Dinas Pekerjaan Umum', 'bidang_id' => $bidangMap['Bidang Ekonomi']],
        ];
        $this->db->table('opd')->insertBatch($dataOpd);
        
        // Get IDs for OPD
        $opdModel = $this->db->query("SELECT * FROM opd")->getResultArray();
        $opdMap = [];
        foreach($opdModel as $o) {
            $opdMap[$o['nama_opd']] = $o['id'];
        }

        // 3. Insert Users
        $dataUsers = [
            [
                'username' => 'superadmin',
                'password' => password_hash('password', PASSWORD_DEFAULT),
                'role'     => 'superadmin',
                'bidang_id'=> null,
                'opd_id'   => null,
                'created_at' => date('Y-m-d H:i:s'),
            ],
            [
                'username' => 'admin_perencanaan',
                'password' => password_hash('password', PASSWORD_DEFAULT),
                'role'     => 'admin_bidang',
                'bidang_id'=> $bidangMap['Bidang Perencanaan'],
                'opd_id'   => null,
                'created_at' => date('Y-m-d H:i:s'),
            ],
            [
                'username' => 'opd_dinkes',
                'password' => password_hash('password', PASSWORD_DEFAULT),
                'role'     => 'opd',
                'bidang_id'=> null,
                'opd_id'   => $opdMap['Dinas Kesehatan'],
                'created_at' => date('Y-m-d H:i:s'),
            ],
        ];

        $this->db->table('users')->insertBatch($dataUsers);
    }
}
