<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\UserModel;

class Users extends BaseController
{
    protected $userModel;

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

        if (!session()->get('logged_in')) {
            header('Location: ' . base_url('login'));
            exit;
        }

        if (session()->get('role') != 'admin') {
            header('Location: ' . base_url('/'));
            exit;
        }
    }

    public function index()
    {
        $data['title'] = 'Data Users';

        $data['users'] = $this->userModel
            ->orderBy('id', 'DESC')
            ->findAll();

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

    public function store()
    {
        $this->userModel->save([
            'nama_lengkap' => $this->request->getPost('nama_lengkap'),
            'username'     => $this->request->getPost('username'),
            'password'     => password_hash(
                $this->request->getPost('password'),
                PASSWORD_DEFAULT
            ),
            'role'         => $this->request->getPost('role')
        ]);

        return redirect()->to('/admin/users')
            ->with('success', 'Data berhasil ditambahkan');
    }

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

        if ($this->request->getPost('password') != '') {

            $data['password'] = password_hash(
                $this->request->getPost('password'),
                PASSWORD_DEFAULT
            );
        }

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

        return redirect()->to('/admin/users')
            ->with('success', 'Data berhasil diubah');
    }

    public function delete($id)
    {
        $this->userModel->delete($id);

        return redirect()->to('/admin/users')
            ->with('success', 'Data berhasil dihapus');
    }
}
