<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\PegawaiModel;
use App\Models\UserModel;

class Pegawai extends BaseController
{
    protected $db;

    public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->db = \Config\Database::connect();
    }

    public function index()
    {
        $pegawaiModel = new PegawaiModel();
        $data = [
            'title' => 'Manajemen Pegawai',
            'pegawai' => $pegawaiModel->findAll(),
        ];
        return view('admin/pegawai/index', $data);
    }

    public function add()
    {
        return view('admin/pegawai/add', ['title' => 'Tambah Pegawai Baru']);
    }

    public function processAdd()
    {
        $pegawaiModel = new PegawaiModel();
        $userModel = new UserModel();

        $nip = $this->request->getPost('nip_baru');
        $nama = $this->request->getPost('nama');

        $userId = $userModel->insert([
            'username' => $nip,
            'nip' => $nip,
            'name' => $nama,
            'password' => password_hash($nip, PASSWORD_DEFAULT),
            'is_active' => 1
        ]);

        if ($userId) {
            $this->db->table('user_roles')->insert([
                'user_id' => $userId,
                'role_id' => $this->db->table('roles')->where('slug', 'user')->get()->getRow()->id
            ]);

            $postData = $this->request->getPost();
            $postData['user_id'] = $userId;

            $pegawaiModel->insert($postData);
        }

        return redirect()->to('/admin/pegawai')->with('success', 'Pegawai berhasil ditambahkan.');
    }

    public function edit($id)
    {
        $pegawaiModel = new PegawaiModel();
        $data = [
            'title' => 'Edit Data Pegawai',
            'pegawai' => $pegawaiModel->find($id),
        ];
        return view('admin/pegawai/edit', $data);
    }

    public function processEdit($id)
    {
        $pegawaiModel = new PegawaiModel();
        $postData = $this->request->getPost();

        $pegawaiModel->update($id, $postData);

        return redirect()->to('/admin/pegawai')->with('success', 'Data pegawai berhasil diperbarui.');
    }

    public function delete($id)
    {
        $pegawaiModel = new PegawaiModel();
        $pegawai = $pegawaiModel->find($id);

        if ($pegawai && $pegawai['user_id']) {
            $userModel = new UserModel();
            $userModel->delete($pegawai['user_id']);
        }

        $pegawaiModel->delete($id);
        return redirect()->to('/admin/pegawai')->with('success', 'Pegawai berhasil dihapus.');
    }

    public function template()
    {
        $filename = "template_biodata_lengkap_pegawai.csv";
        header("Content-Description: File Transfer");
        header("Content-Disposition: attachment; filename=$filename");
        header("Content-Type: application/csv;");

        $file = fopen('php://output', 'w');
        // Header Lengkap
        $header = [
            'NIP_BARU',
            'NIP_LAMA',
            'NIK',
            'NAMA',
            'GELAR_DEPAN',
            'GELAR_BELAKANG',
            'TEMPAT_LAHIR',
            'TANGGAL_LAHIR',
            'JENIS_KELAMIN',
            'AGAMA',
            'STATUS_KAWIN',
            'EMAIL',
            'NO_HP',
            'STATUS_CPNS_PNS',
            'KARTU_ASN_VIRTUAL',
            'NO_SK_CPNS',
            'TGL_SK_CPNS',
            'TMT_CPNS',
            'NO_SK_PNS',
            'TGL_SK_PNS',
            'TMT_PNS',
            'GOL_AWAL',
            'GOL_AKHIR',
            'TMT_GOLONGAN',
            'MK_TAHUN',
            'MK_BULAN',
            'JENIS_JABATAN',
            'JABATAN',
            'TMT_JABATAN',
            'TINGKAT_PENDIDIKAN',
            'NAMA_PENDIDIKAN',
            'TAHUN_LULUS',
            'UNOR',
            'UNIT_KERJA_INDUK',
            'INSTANSI_KERJA',
            'LOKASI_KERJA'
        ];
        fputcsv($file, $header);

        // Contoh Data
        $sample = [
            '198001012010011001',
            '',
            '7501234567890001',
            'BUDI SANTOSO',
            'Drs.',
            'M.Si',
            'GORONTALO',
            '1980-01-01',
            'Laki-laki',
            'Islam',
            'Menikah',
            'budi@example.com',
            '08123456789',
            'PNS',
            '123456',
            '800/SK/01',
            '2010-01-01',
            '2010-01-01',
            '800/SK/PNS/02',
            '2011-01-01',
            '2011-01-01',
            'II/a',
            'III/d',
            '2022-04-01',
            '12',
            '4',
            'Jabatan Struktural',
            'Kepala Sub Bagian Umum',
            '2020-01-01',
            'S2',
            'MANAJEMEN',
            '2015',
            'SUB BAGIAN UMUM',
            'DINAS PERIKANAN',
            'PEMERINTAH KABUPATEN BOALEMO',
            'KAB. BOALEMO'
        ];
        fputcsv($file, $sample);
        fclose($file);
        exit;
    }

    public function import()
    {
        $file = $this->request->getFile('file_import');

        if ($file && $file->isValid() && !$file->hasMoved()) {
            $pegawaiModel = new PegawaiModel();
            $userModel = new UserModel();
            $roleId = $this->db->table('roles')->where('slug', 'user')->get()->getRow()->id;

            $count = 0;
            if (($handle = fopen($file->getTempName(), "r")) !== FALSE) {
                fgetcsv($handle, 2000, ","); // Skip header

                while (($data = fgetcsv($handle, 2000, ",")) !== FALSE) {
                    $nip = $data[0] ?? null;
                    $nama = $data[3] ?? null;

                    if ($nip && $nama) {
                        $existing = $userModel->where('nip', $nip)->first();
                        if (!$existing) {
                            $userId = $userModel->insert([
                                'username' => $nip,
                                'nip' => $nip,
                                'name' => $nama,
                                'password' => password_hash($nip, PASSWORD_DEFAULT),
                                'is_active' => 1
                            ]);

                            if ($userId) {
                                $this->db->table('user_roles')->insert([
                                    'user_id' => $userId,
                                    'role_id' => $roleId
                                ]);

                                $pegawaiModel->insert([
                                    'user_id' => $userId,
                                    'nip_baru' => $nip,
                                    'nip_lama' => $data[1] ?? '',
                                    'nik' => $data[2] ?? '',
                                    'nama' => $nama,
                                    'gelar_depan' => $data[4] ?? '',
                                    'gelar_belakang' => $data[5] ?? '',
                                    'tempat_lahir' => $data[6] ?? '',
                                    'tanggal_lahir' => $data[7] ?? null,
                                    'jenis_kelamin' => $data[8] ?? '',
                                    'agama' => $data[9] ?? '',
                                    'status_kawin' => $data[10] ?? '',
                                    'email' => $data[11] ?? '',
                                    'no_hp' => $data[12] ?? '',
                                    'status_cpns_pns' => $data[13] ?? 'PNS',
                                    'kartu_asn_virtual' => $data[14] ?? '',
                                    'nomor_sk_cpns' => $data[15] ?? '',
                                    'tanggal_sk_cpns' => $data[16] ?? null,
                                    'tmt_cpns' => $data[17] ?? null,
                                    'nomor_sk_pns' => $data[18] ?? '',
                                    'tanggal_sk_pns' => $data[19] ?? null,
                                    'tmt_pns' => $data[20] ?? null,
                                    'gol_awal' => $data[21] ?? '',
                                    'gol_akhir' => $data[22] ?? '',
                                    'tmt_golongan' => $data[23] ?? null,
                                    'masa_kerja_tahun' => $data[24] ?? 0,
                                    'masa_kerja_bulan' => $data[25] ?? 0,
                                    'jenis_jabatan' => $data[26] ?? 'Jabatan Fungsional Umum/Pelaksana',
                                    'jabatan' => $data[27] ?? '',
                                    'tmt_jabatan' => $data[28] ?? null,
                                    'tingkat_pendidikan' => $data[29] ?? '',
                                    'pendidikan' => $data[30] ?? '',
                                    'tahun_lulus' => $data[31] ?? '',
                                    'unor' => $data[32] ?? '',
                                    'unit_kerja_induk' => $data[33] ?? '',
                                    'instansi_kerja' => $data[34] ?? '',
                                    'lokasi_kerja' => $data[35] ?? ''
                                ]);
                                $count++;
                            }
                        }
                    }
                }
                fclose($handle);
            }
            return redirect()->to('/admin/pegawai')->with('success', "$count data biodata lengkap pegawai berhasil diimport.");
        }

        return redirect()->to('/admin/pegawai')->with('error', 'Gagal mengupload file.');
    }
}
