<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;

class User extends BaseController
{
    protected $db;

    public function __construct()
    {
        $this->db = \Config\Database::connect();
        // Cek Session Admin
        if (session()->get('role') != 'admin') {
            header('Location: ' . base_url('admin'));
            exit;
        }
    }

    public function index()
    {
        $data = [
            'title' => 'Kelola Pengguna - Admin Panel',
            'users' => $this->db->table('users')->get()->getResultArray()
        ];
        return view('admin/user/index', $data);
    }

    public function simpan()
    {
        $password = $this->request->getPost('password');
        
        $data = [
            'username'     => $this->request->getPost('username'),
            'nama_lengkap' => $this->request->getPost('nama_lengkap'),
            'password'     => password_hash($password, PASSWORD_DEFAULT),
            'role'         => $this->request->getPost('role'),
            'jurusan'      => $this->request->getPost('jurusan') ?: null
        ];

        $this->db->table('users')->insert($data);
        return redirect()->back()->with('success', 'User baru berhasil ditambahkan');
    }

    public function update($id)
    {
        $data = [
            'username'     => $this->request->getPost('username'),
            'nama_lengkap' => $this->request->getPost('nama_lengkap'),
            'role'         => $this->request->getPost('role'),
            'jurusan'      => $this->request->getPost('jurusan') ?: null
        ];

        // Ganti password hanya jika diisi
        $new_pass = $this->request->getPost('new_password');
        if (!empty($new_pass)) {
            $data['password'] = password_hash($new_pass, PASSWORD_DEFAULT);
        }

        $this->db->table('users')->where('id_user', $id)->update($data);
        return redirect()->back()->with('success', 'Data user berhasil diperbarui');
    }

    public function hapus($id)
    {
        // Cegah hapus diri sendiri
        if ($id == session()->get('id_user')) {
            return redirect()->back()->with('error', 'Anda tidak bisa menghapus akun sendiri!');
        }

        $this->db->table('users')->where('id_user', $id)->delete();
        return redirect()->back()->with('success', 'User berhasil dihapus');
    }
}