<?php

namespace App\Controllers;

use App\Models\UserModel;

class User extends BaseController
{
    protected $userM;

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

    public function index()
    {
        // Proteksi: Mencocokkan session role login Anda
        if (session()->get('role') != 'admin') {
            return redirect()->to('/dashboard')->with('error', 'Akses ditolak! Hanya Admin yang berhak mengelola data pengguna.');
        }

        $data = [
            'title' => 'Manajemen Pengguna Sistem',
            'users' => $this->userM->orderBy('id_user', 'DESC')->findAll()
        ];

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

    public function simpan()
    {
        $this->userM->save([
            'username'     => $this->request->getPost('username'),
            'password'     => password_hash($this->request->getPost('password'), PASSWORD_DEFAULT),
            'nama_lengkap' => $this->request->getPost('nama_lengkap'),
            'surel'        => $this->request->getPost('surel'),
            'role'         => $this->request->getPost('role') // Disimpan ke kolom 'role' database Anda
        ]);

        return redirect()->to('/user')->with('success', 'Akun pengguna baru <b>berhasil ditambahkan</b>.');
    }

    public function update($id)
    {
        $dataUpdate = [
            'username'     => $this->request->getPost('username'),
            'nama_lengkap' => $this->request->getPost('nama_lengkap'),
            'surel'        => $this->request->getPost('surel'),
            'role'         => $this->request->getPost('role') // Diupdate ke kolom 'role' database Anda
        ];

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

        $this->userM->update($id, $dataUpdate);
        return redirect()->to('/user')->with('success', 'Data akun pengguna <b>berhasil diperbarui</b>.');
    }

    public function hapus($id)
    {
        if ($id == session()->get('id_user')) {
            return redirect()->to('/user')->with('error', 'Gagal! Anda tidak dapat menghapus akun Anda sendiri saat sedang login.');
        }

        $this->userM->delete($id);
        return redirect()->to('/user')->with('success', 'Akun pengguna <b>telah dihapus</b>.');
    }
}