<?php

namespace App\Controllers;
use App\Models\UserModel;

class Akun extends BaseController
{
    protected $userModel;

    public function __construct()
    {
        $this->userModel = new UserModel();
    }

    // Pengecekan agar hanya Admin yang bisa mengakses modul ini
    private function cekAdmin()
    {
        if (session()->get('role') != 'Admin') {
            echo "<script>alert('Akses Ditolak! Hanya Admin yang boleh membuka halaman ini.'); window.location.href='".base_url('/')."';</script>";
            exit;
        }
    }

    public function index()
    {
        $this->cekAdmin();
        $data = [
            'title' => 'Manajemen Akun - KPH III',
            'akun'  => $this->userModel->findAll()
        ];
        return view('akun', $data);
    }

    public function tambah()
    {
        $this->cekAdmin();
        $data = ['title' => 'Tambah Akun Baru'];
        return view('form_akun', $data);
    }

    public function simpan()
    {
        $this->cekAdmin();
        $this->userModel->save([
            'nama_lengkap' => $this->request->getPost('nama_lengkap'),
            'username'     => $this->request->getPost('username'),
            // Password harus dienkripsi agar aman
            'password'     => password_hash($this->request->getPost('password'), PASSWORD_DEFAULT),
            'role'         => $this->request->getPost('role')
        ]);
        return redirect()->to('/akun');
    }

    public function edit($id_user)
    {
        $this->cekAdmin();
        $data = [
            'title' => 'Edit Akun',
            'user'  => $this->userModel->find($id_user)
        ];
        return view('form_akun', $data);
    }

    public function update($id_user)
    {
        $this->cekAdmin();
        
        $passwordBaru = $this->request->getPost('password');
        
        $dataUpdate = [
            'nama_lengkap' => $this->request->getPost('nama_lengkap'),
            'username'     => $this->request->getPost('username'),
            'role'         => $this->request->getPost('role')
        ];

        // Jika form password diisi, berarti password ingin diganti
        if (!empty($passwordBaru)) {
            $dataUpdate['password'] = password_hash($passwordBaru, PASSWORD_DEFAULT);
        }

        $this->userModel->update($id_user, $dataUpdate);
        return redirect()->to('/akun');
    }

    public function hapus($id_user)
    {
        $this->cekAdmin();
        // Cegah admin menghapus dirinya sendiri
        if ($id_user == session()->get('id_user')) {
            echo "<script>alert('Anda tidak bisa menghapus akun Anda sendiri yang sedang dipakai!'); window.location.href='".base_url('akun')."';</script>";
        } else {
            $this->userModel->delete($id_user);
            return redirect()->to('/akun');
        }
    }
}