<?php

namespace App\Controllers;

use App\Models\UserModel;

class UserController extends BaseController
{
    public function index()
    {
        $model = new UserModel();
        $data = [
            'users' => $model->findAll(),
            'user' => session()->get(), // Current logged in user
        ];
        return view('users/index', $data);
    }

    public function store()
    {
        $model = new UserModel();
        
        $data = [
            'username' => $this->request->getPost('username'),
            'password_hash' => password_hash($this->request->getPost('password'), PASSWORD_DEFAULT),
            'role' => $this->request->getPost('role'),
            'nama_lengkap' => $this->request->getPost('nama_lengkap'),
            'no_hp' => $this->request->getPost('no_hp'),
        ];
        
        $model->insert($data);
        return redirect()->to('/users')->with('message', 'User berhasil ditambahkan.');
    }

    public function update($id)
    {
        $model = new UserModel();
        
        $data = [
            'username' => $this->request->getPost('username'),
            'role' => $this->request->getPost('role'),
            'nama_lengkap' => $this->request->getPost('nama_lengkap'),
            'no_hp' => $this->request->getPost('no_hp'),
        ];

        $password = $this->request->getPost('password');
        if (!empty($password)) {
            $data['password_hash'] = password_hash($password, PASSWORD_DEFAULT);
        }
        
        $model->update($id, $data);
        return redirect()->to('/users')->with('message', 'Data user berhasil diperbarui.');
    }

    public function delete($id)
    {
        $model = new UserModel();
        $model->delete($id);
        return redirect()->to('/users')->with('message', 'User berhasil dihapus.');
    }
}

