<?php

namespace App\Controllers;

use App\Models\UserModel;

class User extends BaseController
{
    protected $userModel;

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

    public function index()
    {
        // Pastikan hanya admin yang bisa akses
        if (session()->get('role') != 'admin') {
            return redirect()->to('/dashboard');
        }

        $data = [
            'title' => 'Manajemen User',
            'users' => $this->userModel->findAll()
        ];
        return view('user/index', $data);
    }

    public function simpanUser()
    {
        if (session()->get('role') != 'admin') return redirect()->to('/dashboard');

        $id = $this->request->getPost('id');
        $data = [
            'name' => $this->request->getPost('name'),
            'username' => $this->request->getPost('username'),
            'role' => $this->request->getPost('role'),
        ];
        
        $password = $this->request->getPost('password');
        if (!empty($password)) {
            $data['password'] = password_hash($password, PASSWORD_DEFAULT);
        }

        if ($id) $this->userModel->update($id, $data);
        else $this->userModel->insert($data);

        return redirect()->to('/users');
    }

    public function hapusUser($id)
    {
        if (session()->get('role') != 'admin') return redirect()->to('/dashboard');
        
        if ($id != session()->get('id')) {
            $this->userModel->delete($id);
        }
        return redirect()->to('/users');
    }
}
