<?php

namespace App\Controllers;

use App\Models\OpdModel;

class Pegawai extends BaseController
{
    public function index()
    {
        $level = session()->get('level');
        $id_opd_session = session()->get('id_opd');
        $opdModel = new OpdModel();

        $data = [
            'title'    => 'Manajemen Pegawai',
            'level'    => $level,
            'opd_list' => ($level == 'kabupaten')
                ? $opdModel->findAll()
                : $opdModel->where('id_opd', $id_opd_session)->findAll()
        ];

        return view('pegawai/index', $data);
    }

    public function ajax_list()
    {
        $db = \Config\Database::connect();
        $request = \Config\Services::request();

        $level = session()->get('level');
        $id_opd_session = session()->get('id_opd');
        $filter_opd = $request->getPost('filter_opd');

        $builder = $db->table('pegawai')
            ->select('pegawai.*, opd.nama_opd')
            ->join('opd', 'pegawai.id_opd = opd.id_opd');

        // 1. Filter Akses
        if ($level == 'opd') {
            $builder->where('pegawai.id_opd', $id_opd_session);
        } elseif (!empty($filter_opd)) {
            $builder->where('pegawai.id_opd', $filter_opd);
        }

        // 2. Fitur Pencarian
        $searchValue = $request->getPost('search')['value'];
        if ($searchValue) {
            $builder->groupStart()
                ->like('pegawai.nama_lengkap', $searchValue)
                ->orLike('pegawai.nip', $searchValue)
                ->groupEnd();
        }

        $totalFiltered = $builder->countAllResults(false);

        $start = $request->getPost('start');
        $length = $request->getPost('length');

        // 3. LOGIKA URUTAN ESELON (UTAMA & SANGAT KETAT)
        // Urutan: II.a > II.b > III.a > III.b > IV.a > IV.b > Non Eselon > Dash (-)
        $builder->orderBy("CASE 
    /* 1. Kelompok Pimpinan Tinggi (Eselon II) */
    WHEN TRIM(eselon) = 'II.a' THEN 1
    WHEN TRIM(eselon) = 'II.b' THEN 2
    
    /* 2. Kelompok Administrator (Eselon III) */
    WHEN TRIM(eselon) = 'III.a' THEN 3
    WHEN TRIM(eselon) = 'III.b' THEN 4
    
    /* 3. Kelompok Pengawas (Eselon IV) */
    WHEN TRIM(eselon) = 'IV.a' THEN 5
    WHEN TRIM(eselon) = 'IV.b' THEN 6
    
    /* 4. Kelompok Fungsional (Meskipun Eselonnya strip/kosong) */
    WHEN level_jabatan LIKE '%Fungsional%' THEN 7
    
    /* 5. Kelompok Staf / Umum */
    WHEN level_jabatan LIKE '%Staf%' OR TRIM(eselon) = 'Non Eselon' THEN 8
    
    /* 6. Sisanya (Data tidak lengkap) */
    WHEN TRIM(eselon) = '-' THEN 9
    ELSE 10 END", "ASC", false);

        // Urutan tambahan berdasarkan nama jika kasta jabatannya sama
        $builder->orderBy('nama_lengkap', 'ASC');

        $result = $builder->limit($length, $start)->get()->getResult();

        $data = [];
        $no = $start + 1;
        foreach ($result as $p) {
            // Badge Status Wajah
            $status_wajah = !empty($p->face_vector)
                ? '<span class="badge bg-success-subtle text-success border border-success-subtle px-3 py-2"><i class="fas fa-check-circle me-1"></i> AKTIF</span>'
                : '<span class="badge bg-danger-subtle text-danger border border-danger-subtle px-3 py-2"><i class="fas fa-times-circle me-1"></i> BELUM ADA</span>';

            // Badge Level Jabatan (Warna disesuaikan dengan gambar Bapak)
            $lv = strtoupper($p->level_jabatan ?? '');
            $badge_class = 'bg-light text-primary'; // Default Staf

            if (strpos($lv, 'PIMPINAN TINGGI') !== false || strpos($lv, 'ADMINISTRATOR') !== false || strpos($lv, 'FUNGSIONAL') !== false) {
                $badge_class = 'bg-primary text-white'; // Biru Tua seperti di gambar
            } elseif (strpos($lv, 'STAF') !== false) {
                $badge_class = 'bg-info-subtle text-info'; // Biru Muda
            }

            $opsi = '<div class="btn-group shadow-sm">
                    <button onclick="openEnroll(\'' . $p->id_pegawai . '\', \'' . $p->nama_lengkap . '\')" class="btn btn-sm btn-white border text-primary" title="Enroll Wajah"><i class="fas fa-camera"></i></button>
                    <button onclick="openEdit(\'' . $p->id_pegawai . '\')" class="btn btn-sm btn-white border text-warning" title="Edit"><i class="fas fa-edit"></i></button>
                    <a href="' . base_url('pegawai/hapus/' . $p->id_pegawai) . '" class="btn btn-sm btn-white border text-danger" onclick="return confirm(\'Hapus pegawai ini?\')"><i class="fas fa-trash"></i></a>
                 </div>';

            $row = [];
            $row[] = '<span class="ps-3 small text-muted">' . $no++ . '.</span>';
            $row[] = '<div><div class="fw-bold small">' . $p->nama_lengkap . '</div><div class="text-muted small" style="font-size: 10px;">NIP. ' . $p->nip . '</div></div>';

            $row[] = '<div>
                    <div class="small fw-bold text-dark">' . $p->jabatan . '</div>
                    <div class="text-muted" style="font-size: 9px;">' . ($p->pangkat ?? '-') . ' | ' . ($p->eselon ?? '-') . '</div>
                    <span class="badge ' . $badge_class . ' border px-2 mt-1" style="font-size: 9px;">' . strtoupper($p->level_jabatan) . '</span>
                  </div>';

            $row[] = '<div class="text-center"><span class="badge bg-info-subtle text-info border px-3">' . ($p->status_asn ?? '-') . '</span></div>';
            $row[] = $status_wajah;
            $row[] = $opsi;

            $data[] = $row;
        }

        $totalRealBuilder = $db->table('pegawai');
        if ($level == 'opd') {
            $totalRealBuilder->where('id_opd', $id_opd_session);
        }
        $totalReal = $totalRealBuilder->countAllResults();

        return $this->response->setJSON([
            "draw"            => intval($request->getPost('draw')),
            "recordsTotal"    => $totalReal,
            "recordsFiltered" => $totalFiltered,
            "data"            => $data,
        ]);
    }

    public function simpan()
    {
        $db = \Config\Database::connect();
        $data = [
            'id_opd'        => $this->request->getPost('id_opd'),
            'nip'           => $this->request->getPost('nip'),
            'nama_lengkap'  => $this->request->getPost('nama_lengkap'),
            'jabatan'       => $this->request->getPost('jabatan'),
            'level_jabatan' => $this->request->getPost('level_jabatan'),
            'pangkat'       => $this->request->getPost('pangkat'),
            'eselon'        => $this->request->getPost('eselon'),
            'status_asn'    => $this->request->getPost('status_asn'),
            'password'      => password_hash($this->request->getPost('password'), PASSWORD_DEFAULT),
        ];

        $db->table('pegawai')->insert($data);
        return redirect()->to('pegawai')->with('success', 'Pegawai baru berhasil ditambahkan.');
    }

    public function update()
    {
        $db = \Config\Database::connect();
        $id = $this->request->getPost('id_pegawai');

        $data = [
            'id_opd'        => $this->request->getPost('id_opd'),
            'nip'           => $this->request->getPost('nip'),
            'nama_lengkap'  => $this->request->getPost('nama_lengkap'),
            'jabatan'       => $this->request->getPost('jabatan'),
            'level_jabatan' => $this->request->getPost('level_jabatan'),
            'pangkat'       => $this->request->getPost('pangkat'),
            'eselon'        => $this->request->getPost('eselon'),
            'status_asn'    => $this->request->getPost('status_asn'),
        ];

        if ($this->request->getPost('password')) {
            $data['password'] = password_hash($this->request->getPost('password'), PASSWORD_DEFAULT);
        }

        $db->table('pegawai')->where('id_pegawai', $id)->update($data);
        return redirect()->to('pegawai')->with('success', 'Data pegawai berhasil diperbarui.');
    }

    public function edit_data($id)
    {
        $db = \Config\Database::connect();
        $data = $db->table('pegawai')->where('id_pegawai', $id)->get()->getRowArray();
        return $this->response->setJSON($data);
    }

    public function hapus($id)
    {
        $db = \Config\Database::connect();
        $db->table('pegawai')->where('id_pegawai', $id)->delete();
        return redirect()->to('pegawai')->with('success', 'Data pegawai berhasil dihapus.');
    }

    public function simpan_face_vector()
    {
        $db = \Config\Database::connect();
        $id = $this->request->getPost('id_pegawai');
        $vector = $this->request->getPost('face_vector');
        $db->table('pegawai')->where('id_pegawai', $id)->update(['face_vector' => $vector]);
        return $this->response->setJSON(['status' => 'success', 'msg' => 'Wajah Berhasil Disimpan!']);
    }

    public function generate_password_nip()
    {
        // Cek Keamanan: Hanya admin yang boleh jalankan
        if (session()->get('level') != 'kabupaten') {
            return "Akses Ditolak!";
        }

        $db = \Config\Database::connect();

        // 1. Ambil semua pegawai yang password-nya belum di-hash (panjang karakter kurang dari 60)
        // Karena hasil password_hash itu selalu 60 karakter.
        $pegawai = $db->table('pegawai')
            ->where('CHAR_LENGTH(password) <', 60)
            ->orWhere('password', NULL)
            ->get()->getResultArray();

        $berhasil = 0;
        foreach ($pegawai as $p) {
            // 2. Ambil NIP sebagai password, lalu di-hash
            $hashPassword = password_hash($p['nip'], PASSWORD_DEFAULT);

            // 3. Update ke database
            $db->table('pegawai')
                ->where('id_pegawai', $p['id_pegawai'])
                ->update(['password' => $hashPassword]);

            $berhasil++;
        }

        return "Selesai! Berhasil mengamankan $berhasil password pegawai. Sekarang mereka bisa login menggunakan NIP masing-masing.";
    }

    public function ajax_generate_password()
    {
        // 1. Keamanan: Cek Level
        if (session()->get('level') != 'kabupaten') {
            return $this->response->setJSON(['status' => 'error', 'message' => 'Akses ditolak!']);
        }

        $db = \Config\Database::connect();

        // 2. Tentukan limit per batch (misal 50 pegawai per proses)
        $limit = 50;

        // 3. Hitung total pegawai yang butuh perbaikan password
        $query_count = $db->table('pegawai')
            ->groupStart()
            ->where('CHAR_LENGTH(password) <', 60)
            ->orWhere('password', NULL)
            ->groupEnd();

        $total_sisa = $query_count->countAllResults(false); // false agar builder tidak reset

        // 4. Ambil data sebanyak limit
        $pegawai = $query_count->limit($limit)->get()->getResultArray();

        if (empty($pegawai)) {
            return $this->response->setJSON([
                'status' => 'finish',
                'message' => 'Semua password sudah aman (ter-hash).'
            ]);
        }

        $berhasil = 0;
        foreach ($pegawai as $p) {
            $hashPassword = password_hash($p['nip'], PASSWORD_DEFAULT);
            $db->table('pegawai')
                ->where('id_pegawai', $p['id_pegawai'])
                ->update(['password' => $hashPassword]);
            $berhasil++;
        }

        return $this->response->setJSON([
            'status' => 'process',
            'processed' => $berhasil,
            'remaining' => $total_sisa - $berhasil
        ]);
    }
}
