<?php

namespace App\Controllers;
use App\Models\PegawaiModel;

class Pegawai extends BaseController
{
    protected $pegawaiModel;

    public function __construct()
    {
        $this->pegawaiModel = new PegawaiModel();
    }

    // --- FUNGSI GEMBOK LEVEL ---
    private function cekManajemen()
    {
        if (session()->get('role') != 'Admin' && session()->get('role') != 'Kepala KPH') {
            echo "<script>alert('Akses Ditolak! Halaman Khusus Manajemen.'); window.location.href='".base_url('/')."';</script>";
            exit;
        }
    }

    public function index()
    {
        $this->cekManajemen(); // Dikunci
        $data = [
            'title' => 'Data Pegawai & Polhut - KPH III Asahan',
            'pegawai' => $this->pegawaiModel->orderBy('id_pegawai', 'DESC')->findAll()
        ];
        return view('pegawai', $data);
    }

    public function tambah()
    {
        $this->cekManajemen(); // Dikunci
        $data = ['title' => 'Tambah Pegawai - KPH III Asahan'];
        return view('tambah_pegawai', $data);
    }

    public function simpan()
    {
        $this->cekManajemen(); // Dikunci
        $this->pegawaiModel->save([
            'nip'          => $this->request->getPost('nip'),
            'nama_pegawai' => $this->request->getPost('nama_pegawai'),
            'jabatan'      => $this->request->getPost('jabatan'),
            'no_hp'        => $this->request->getPost('no_hp'),
            'status'       => $this->request->getPost('status')
        ]);
        return redirect()->to('/pegawai');
    }

    public function edit($id_pegawai)
    {
        $this->cekManajemen(); // Dikunci
        $data = [
            'title' => 'Edit Data Pegawai - KPH III',
            'pegawai_edit' => $this->pegawaiModel->find($id_pegawai)
        ];
        return view('tambah_pegawai', $data);
    }

    public function update($id_pegawai)
    {
        $this->cekManajemen(); // Dikunci
        $this->pegawaiModel->update($id_pegawai, [
            'nip'          => $this->request->getPost('nip'),
            'nama_pegawai' => $this->request->getPost('nama_pegawai'),
            'jabatan'      => $this->request->getPost('jabatan'),
            'no_hp'        => $this->request->getPost('no_hp'),
            'status'       => $this->request->getPost('status')
        ]);
        return redirect()->to('/pegawai'); 
    }

    public function hapus($id_pegawai)
    {
        $this->cekManajemen(); // Dikunci
        $this->pegawaiModel->delete($id_pegawai);
        return redirect()->to('/pegawai');
    }
}