<?php namespace App\Controllers;

use App\Models\UserModel;
use App\Models\GuruModel;

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

    public function create()
    {
        $guruModel = new GuruModel();
        $data['guru'] = $guruModel->findAll(); // ambil data guru
        return view('users/create', $data);
    }

    public function store()
    {
        $model = new UserModel();

        $model->insert([
            'username' => $this->request->getPost('username'),
            'password' => password_hash($this->request->getPost('password'), PASSWORD_DEFAULT),
            'nama'     => $this->request->getPost('nama'),
            'role'     => $this->request->getPost('role'),
            'id_guru'  => $this->request->getPost('id_guru') ?? null
        ]);

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

    public function edit($id)
    {
        $model = new UserModel();
        $guruModel = new GuruModel();

        $data['user'] = $model->find($id);
        $data['guru'] = $guruModel->findAll();

        return view('users/edit', $data);
    }

    public function update($id)
{
    $model = new UserModel();

    // Ambil data input
    $username = $this->request->getPost('username');
    $nama     = $this->request->getPost('nama');
    $role     = $this->request->getPost('role');
    $idGuru   = $this->request->getPost('id_guru');
    $password = $this->request->getPost('password');

    // Siapkan data update
    $data = [
        'username' => $username,
        'nama'     => $nama,
        'role'     => $role,
        'id_guru'  => $idGuru ?: null
    ];

    // Jika password diisi, update juga
    if (!empty($password)) {
        $data['password'] = password_hash($password, PASSWORD_DEFAULT);
    }

    // Update ke database
    $model->update($id, $data);

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