<?php

namespace App\Controllers;

use App\Models\UserModel;

class Users extends BaseController
{
    public function index(): string
    {
        $userModel = new UserModel();
        return view('users/index', $this->viewData([
            'users' => $userModel->getAll(),
        ]));
    }

    public function save(): \CodeIgniter\HTTP\ResponseInterface
    {
        $id       = (int) ($this->request->getPost('id') ?? 0);
        $nama     = trim($this->request->getPost('nama') ?? '');
        $username = trim($this->request->getPost('username') ?? '');
        $password = $this->request->getPost('password') ?? '';
        $role     = $this->request->getPost('role') ?? 'viewer';
        $isActive = (int) ($this->request->getPost('is_active') ?? 1);

        if ($nama === '' || $username === '') {
            return $this->jsonError('Nama dan username wajib diisi.');
        }
        if (! in_array($role, ['administrator', 'viewer'], true)) {
            return $this->jsonError('Role tidak valid.');
        }

        $userModel = new UserModel();

        // Check username uniqueness
        $existing = $userModel->findByUsername($username);
        if ($existing && $existing['id'] !== $id) {
            return $this->jsonError('Username sudah digunakan.');
        }

        $data = ['nama' => $nama, 'username' => $username, 'role' => $role, 'is_active' => $isActive];
        if ($password !== '') {
            $data['password'] = password_hash($password, PASSWORD_BCRYPT);
        }

        if ($id > 0) {
            $userModel->update($id, $data);
            $this->logActivity('user_update', "Update user: $username");
        } else {
            if ($password === '') return $this->jsonError('Password wajib diisi untuk user baru.');
            $data['password'] = password_hash($password, PASSWORD_BCRYPT);
            $userModel->insert($data);
            $this->logActivity('user_create', "Tambah user: $username");
        }

        return $this->jsonSuccess('User berhasil disimpan.');
    }

    public function delete(int $id): \CodeIgniter\HTTP\ResponseInterface
    {
        if ($id === (int) session('user_id')) {
            return $this->jsonError('Tidak dapat menghapus akun sendiri.');
        }
        $userModel = new UserModel();
        $user = $userModel->find($id);
        if (! $user) return $this->jsonError('User tidak ditemukan.', 404);

        $userModel->delete($id);
        $this->logActivity('user_delete', "Hapus user: {$user['username']}");

        return $this->jsonSuccess('User berhasil dihapus.');
    }

    public function toggle(int $id): \CodeIgniter\HTTP\ResponseInterface
    {
        if ($id === (int) session('user_id')) {
            return $this->jsonError('Tidak dapat menonaktifkan akun sendiri.');
        }
        $userModel = new UserModel();
        $user = $userModel->find($id);
        if (! $user) return $this->jsonError('User tidak ditemukan.', 404);

        $newStatus = $user['is_active'] ? 0 : 1;
        $userModel->update($id, ['is_active' => $newStatus]);
        $this->logActivity('user_toggle', "Toggle status user {$user['username']} → " . ($newStatus ? 'aktif' : 'nonaktif'));

        return $this->jsonSuccess('Status user diperbarui.', ['is_active' => $newStatus]);
    }
}
