<?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,
            // Perbaikan: Gunakan model() agar lebih aman
            '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');

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

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

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

        // 4. Hitung Total Filtered
        $totalFiltered = $builder->countAllResults(false);

        // 5. Pengurutan & Limit (Pagination)
        $start = $request->getPost('start');
        $length = $request->getPost('length');

        // Urutan Hierarki Polewali Mandar
        $builder->orderBy("CASE 
    WHEN level_jabatan = 'Kepala Dinas' THEN 1 
    WHEN level_jabatan = 'Sekretaris' THEN 2 
    WHEN level_jabatan = 'Kepala Bidang' THEN 3 
    WHEN level_jabatan = 'Pejabat Fungsional' THEN 4 
    WHEN level_jabatan = 'Staf' THEN 5 
    ELSE 6 END", "ASC", false);
        $builder->orderBy('nama_lengkap', 'ASC');

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

        // 6. Menyusun Data untuk DataTables
        $data = [];
        $no = $start + 1;
        foreach ($result as $p) {
            // PERBAIKAN TYPO: Tadi ada tanda petik satu sisa di face_vector'
            $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>';

            $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><span class="badge bg-light text-primary border px-2" style="font-size: 9px;">' . strtoupper($p->level_jabatan) . '</span></div>';
            $row[] = $status_wajah;
            $row[] = $opsi;

            $data[] = $row;
        }

        // 7. Hitung Total Real (recordsTotal)
        // Jika Admin OPD, total real adalah total pegawai di OPD-nya saja
        $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_face_vector()
    {
        $db = \Config\Database::connect();
        $id = $this->request->getPost('id_pegawai');
        $vector = $this->request->getPost('face_vector');

        // Cek apakah data kosong sebelum simpan
        if (empty($vector) || empty($id)) {
            return $this->response->setJSON([
                'status' => 'error',
                'msg' => 'Data Vektor atau ID Pegawai tidak terkirim!'
            ]);
        }

        $simpan = $db->table('pegawai')
            ->where('id_pegawai', $id)
            ->update(['face_vector' => $vector]);

        if ($simpan) {
            return $this->response->setJSON(['status' => 'success', 'msg' => 'Wajah Berhasil Disimpan!']);
        } else {
            return $this->response->setJSON(['status' => 'error', 'msg' => 'Gagal Update Database']);
        }
    }

    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()
    {
        $db = \Config\Database::connect();

        // Mengambil data dari form tambah 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'),
            // Password di-hash demi keamanan
            '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 edit_data($id)
    {
        $db = \Config\Database::connect();
        $data = $db->table('pegawai')->where('id_pegawai', $id)->get()->getRowArray();
        return $this->response->setJSON($data);
    }

    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'),
        ];

        // Password hanya diupdate jika diisi
        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 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.";
    }
}
