<?php

namespace App\Controllers\Admin;

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

class UserManagement extends BaseController
{
    protected UserModel $userModel;

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

    // ─────────────────────────────────────────────────────────────────
    // Helper: cek login
    // ─────────────────────────────────────────────────────────────────
    private function authCheck()
    {
        if (!session()->get('logged_in')) {
            return redirect()->to('/login');
        }
        return null;
    }

    // ─────────────────────────────────────────────────────────────────
    // index() — daftar semua user (kecuali yang deleted)
    // ─────────────────────────────────────────────────────────────────
    public function index()
    {
        if ($redir = $this->authCheck()) return $redir;

        $users = $this->userModel
            ->select('id, name, username, email, role, is_active, created_at')
            ->findAll();

        return view('user_management/index', [
            'title' => 'Manajemen Akun',
            'users' => $users,
        ]);
    }

    // ─────────────────────────────────────────────────────────────────
    // store() — POST, tambah user baru
    // ─────────────────────────────────────────────────────────────────
    public function store()
    {
        if ($redir = $this->authCheck()) return $redir;

        $rules = [
            'name'             => 'required|min_length[3]|max_length[100]',
            'username'         => 'required|min_length[3]|max_length[100]|is_unique[users.username]',
            'email'            => 'permit_empty|valid_email|max_length[100]',
            'role'             => 'required|in_list[superadmin,admin,operator,tata_usaha,kamad]',
            'password'         => 'required|min_length[6]',
            'password_confirm' => 'required|matches[password]',
        ];

        $messages = [
            'username'         => ['is_unique' => 'Username sudah digunakan.'],
            'password'         => ['min_length' => 'Password minimal 6 karakter.'],
            'password_confirm' => ['matches'    => 'Konfirmasi password tidak cocok.'],
        ];

        if (!$this->validate($rules, $messages)) {
            return $this->response->setJSON([
                'success' => false,
                'message' => implode('<br>', $this->validator->getErrors()),
            ]);
        }

        try {
            $email = trim($this->request->getPost('email'));
            $userId = $this->userModel->insert([
                'name'      => $this->request->getPost('name'),
                'username'  => $this->request->getPost('username'),
                'email'     => !empty($email) ? $email : null,
                'role'      => $this->request->getPost('role'),
                'password'  => password_hash($this->request->getPost('password'), PASSWORD_DEFAULT),
                'is_active' => 1,
            ]);

            log_activity('create', 'user_management', $userId, "Menambahkan user baru: " . $this->request->getPost('name') . " (username: " . $this->request->getPost('username') . ")");

            return $this->response->setJSON([
                'success' => true,
                'message' => 'User berhasil ditambahkan.',
            ]);
        } catch (\Exception $e) {
            return $this->response->setJSON([
                'success' => false,
                'message' => 'Gagal menyimpan user: ' . $e->getMessage(),
            ]);
        }
    }

    // ─────────────────────────────────────────────────────────────────
    // update($id) — POST, edit nama/email/role/status
    // ─────────────────────────────────────────────────────────────────
    public function update($id)
    {
        if ($redir = $this->authCheck()) return $redir;

        $user = $this->userModel->find($id);
        if (!$user) {
            return $this->response->setJSON(['success' => false, 'message' => 'User tidak ditemukan.']);
        }

        $rules = [
            'name'  => 'required|min_length[3]|max_length[100]',
            'email' => 'permit_empty|valid_email|max_length[100]',
            'role'  => 'required|in_list[superadmin,admin,operator,tata_usaha,kamad]',
        ];

        if (!$this->validate($rules)) {
            return $this->response->setJSON([
                'success' => false,
                'message' => implode('<br>', $this->validator->getErrors()),
            ]);
        }

        try {
            $email = trim($this->request->getPost('email'));
            $this->userModel->update($id, [
                'name'      => $this->request->getPost('name'),
                'email'     => !empty($email) ? $email : null,
                'role'      => $this->request->getPost('role'),
                'is_active' => (int) $this->request->getPost('is_active'),
            ]);

            log_activity('update', 'user_management', $id, "Mengubah data user: " . $this->request->getPost('name') . " (role: " . $this->request->getPost('role') . ")");

            return $this->response->setJSON([
                'success' => true,
                'message' => 'Data user berhasil diperbarui.',
            ]);
        } catch (\Exception $e) {
            return $this->response->setJSON([
                'success' => false,
                'message' => 'Gagal memperbarui data user: ' . $e->getMessage(),
            ]);
        }
    }

    // ─────────────────────────────────────────────────────────────────
    // resetPassword($id) — POST, reset password user lain
    // ─────────────────────────────────────────────────────────────────
    public function resetPassword($id)
    {
        if ($redir = $this->authCheck()) return $redir;

        $user = $this->userModel->find($id);
        if (!$user) {
            return $this->response->setJSON(['success' => false, 'message' => 'User tidak ditemukan.']);
        }

        $rules = [
            'new_password'         => 'required|min_length[6]',
            'new_password_confirm' => 'required|matches[new_password]',
        ];

        $messages = [
            'new_password'         => ['min_length' => 'Password minimal 6 karakter.'],
            'new_password_confirm' => ['matches'    => 'Konfirmasi password tidak cocok.'],
        ];

        if (!$this->validate($rules, $messages)) {
            return $this->response->setJSON([
                'success' => false,
                'message' => implode('<br>', $this->validator->getErrors()),
            ]);
        }

        $this->userModel->update($id, [
            'password' => password_hash($this->request->getPost('new_password'), PASSWORD_DEFAULT),
        ]);

        log_activity('update', 'user_management', $id, "Mereset password user ID {$id} (" . $user['name'] . ")");

        return $this->response->setJSON([
            'success' => true,
            'message' => 'Password berhasil direset.',
        ]);
    }

    // ─────────────────────────────────────────────────────────────────
    // toggleActive($id) — GET, aktif/nonaktif user
    // ─────────────────────────────────────────────────────────────────
    public function toggleActive($id)
    {
        if ($redir = $this->authCheck()) return $redir;

        $isAjax = $this->request->isAJAX();

        if ((int) $id === (int) session()->get('user_id')) {
            $msg = 'Tidak dapat menonaktifkan akun sendiri.';
            return $isAjax
                ? $this->response->setJSON(['success' => false, 'message' => $msg])
                : redirect()->back()->with('error', $msg);
        }

        $user = $this->userModel->find($id);
        if (!$user) {
            $msg = 'User tidak ditemukan.';
            return $isAjax
                ? $this->response->setJSON(['success' => false, 'message' => $msg])
                : redirect()->back()->with('error', $msg);
        }

        $newStatus = $user['is_active'] ? 0 : 1;
        $this->userModel->update($id, ['is_active' => $newStatus]);

        log_activity('update', 'user_management', $id, "Status akun user ID {$id} (" . $user['name'] . ") diubah menjadi " . ($newStatus ? 'Aktif' : 'Non-Aktif'));

        $msg = $newStatus ? 'User berhasil diaktifkan.' : 'User berhasil dinonaktifkan.';
        return $isAjax
            ? $this->response->setJSON(['success' => true, 'message' => $msg, 'is_active' => $newStatus])
            : redirect()->to('/user-management')->with('success', $msg);
    }

    // ─────────────────────────────────────────────────────────────────
    // delete($id) — GET, soft delete
    // ─────────────────────────────────────────────────────────────────
    public function delete($id)
    {
        if ($redir = $this->authCheck()) return $redir;

        $isAjax = $this->request->isAJAX();

        if ((int) $id === (int) session()->get('user_id')) {
            $msg = 'Tidak dapat menghapus akun sendiri.';
            return $isAjax
                ? $this->response->setJSON(['success' => false, 'message' => $msg])
                : redirect()->back()->with('error', $msg);
        }

        $user = $this->userModel->find($id);
        if (!$user) {
            $msg = 'User tidak ditemukan.';
            return $isAjax
                ? $this->response->setJSON(['success' => false, 'message' => $msg])
                : redirect()->back()->with('error', $msg);
        }

        $this->userModel->delete($id);

        log_activity('delete', 'user_management', $id, "Menghapus user ID {$id} (" . $user['name'] . ")");

        $msg = 'User berhasil dihapus.';
        return $isAjax
            ? $this->response->setJSON(['success' => true, 'message' => $msg])
            : redirect()->to('/user-management')->with('success', $msg);
    }

    // ─────────────────────────────────────────────────────────────────
    // changePassword() — POST, ganti password diri sendiri
    // ─────────────────────────────────────────────────────────────────
    public function changePassword()
    {
        if ($redir = $this->authCheck()) return $redir;

        $userId = session()->get('user_id');
        $user   = $this->userModel->find($userId);

        if (!$user) {
            return $this->response->setJSON(['success' => false, 'message' => 'User tidak ditemukan.']);
        }

        // Validasi password lama
        $oldPassword = $this->request->getPost('old_password');
        if (!password_verify($oldPassword, $user['password'])) {
            return $this->response->setJSON(['success' => false, 'message' => 'Password lama tidak sesuai.']);
        }

        $rules = [
            'new_password'         => 'required|min_length[6]',
            'new_password_confirm' => 'required|matches[new_password]',
        ];

        $messages = [
            'new_password'         => ['min_length' => 'Password baru minimal 6 karakter.'],
            'new_password_confirm' => ['matches'    => 'Konfirmasi password tidak cocok.'],
        ];

        if (!$this->validate($rules, $messages)) {
            return $this->response->setJSON([
                'success' => false,
                'message' => implode('<br>', $this->validator->getErrors()),
            ]);
        }

        $this->userModel->update($userId, [
            'password' => password_hash($this->request->getPost('new_password'), PASSWORD_DEFAULT),
        ]);

        log_activity('update', 'user_management', $userId, "Mengubah password akun pribadi");

        return $this->response->setJSON([
            'success' => true,
            'message' => 'Password berhasil diubah.',
        ]);
    }
}
