<?php

namespace App\Controllers\Superadmin;

use App\Controllers\BaseController;
use App\Models\UserModel;
use App\Models\RoleModel;
use App\Models\ActivityLogModel;
use CodeIgniter\Exceptions\PageNotFoundException;

class User extends BaseController
{
    protected $userModel;
    protected $roleModel;
    protected $activityModel;

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

    /**
     * Helper: Logging aktivitas pengguna jika sesi aktif
     */
    private function logAction(string $message): void
    {
        $idUser = session()->get('id_user');
        if ($idUser) {
            $user = $this->userModel->where('id_user', $idUser)->first() ?? $this->userModel->find($idUser);
            if ($user) {
                $this->activityModel->logActivity($idUser, $message);
            }
        }
    }

    public function index()
    {
        $users = $this->userModel
            ->select('users.*, roles.nama_role')
            ->join('roles', 'roles.id_role = users.id_role', 'left')
            ->orderBy('users.id_user', 'DESC')
            ->findAll();

        return view('superadmin/user/index', [
            'title' => 'Manajemen User',
            'users' => $users
        ]);
    }

    public function detail($id)
    {
        $user = $this->userModel
            ->select('users.*, roles.nama_role')
            ->join('roles', 'roles.id_role = users.id_role', 'left')
            ->where('users.id_user', $id)
            ->first();

        if (!$user) {
            throw PageNotFoundException::forPageNotFound('User tidak ditemukan.');
        }

        return view('superadmin/user/detail', [
            'title' => 'Detail User',
            'user'  => $user
        ]);
    }

    public function create()
    {
        return view('superadmin/user/create', [
            'title' => 'Tambah User',
            'roles' => $this->roleModel->findAll()
        ]);
    }

    /**
     * Safe GET fallback redirect ke form create
     */
    public function getStore()
    {
        return redirect()->to('superadmin/user/create');
    }

    public function store()
    {
        if (!$this->validate([
            'username'     => 'required|min_length[4]|is_unique[users.username]',
            'nama_lengkap' => 'required',
            'email'        => 'required|valid_email|is_unique[users.email]',
            'password'     => 'required|min_length[6]',
            'id_role'      => 'required|integer'
        ])) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

        $username = trim($this->request->getPost('username'));

        $this->userModel->insert([
            'username'     => $username,
            'password'     => password_hash($this->request->getPost('password'), PASSWORD_DEFAULT),
            'nama_lengkap' => trim($this->request->getPost('nama_lengkap')),
            'email'        => trim($this->request->getPost('email')),
            'id_role'      => $this->request->getPost('id_role'),
            'is_active'    => 1
        ]);

        $this->logAction('Menambahkan user baru: ' . $username);

        return redirect()->to('superadmin/user')->with('success', 'User ' . $username . ' berhasil ditambahkan.');
    }

    public function edit($id)
    {
        $user = $this->userModel->where('id_user', $id)->first() ?? $this->userModel->find($id);

        if (!$user) {
            throw PageNotFoundException::forPageNotFound('Data user dengan ID #' . $id . ' tidak ditemukan.');
        }

        return view('superadmin/user/edit', [
            'title' => 'Edit User',
            'user'  => $user,
            'roles' => $this->roleModel->findAll()
        ]);
    }

    public function update($id)
    {
        $user = $this->userModel->where('id_user', $id)->first() ?? $this->userModel->find($id);

        if (!$user) {
            throw PageNotFoundException::forPageNotFound('Data user tidak ditemukan.');
        }

        if (!$this->validate([
            'username'     => "required|min_length[4]|is_unique[users.username,id_user,{$id}]",
            'nama_lengkap' => 'required',
            'email'        => "required|valid_email|is_unique[users.email,id_user,{$id}]",
            'id_role'      => 'required|integer'
        ])) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

        $data = [
            'username'     => trim($this->request->getPost('username')),
            'nama_lengkap' => trim($this->request->getPost('nama_lengkap')),
            'email'        => trim($this->request->getPost('email')),
            'id_role'      => $this->request->getPost('id_role')
        ];

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

        $this->userModel->where('id_user', $id)->set($data)->update();
        $this->logAction('Mengubah data user: ' . $user['username']);

        return redirect()->to('superadmin/user')->with('success', 'Data user berhasil diperbarui.');
    }

    public function activate($id)
    {
        $user = $this->userModel->where('id_user', $id)->first() ?? $this->userModel->find($id);

        if (!$user) {
            throw PageNotFoundException::forPageNotFound('User tidak ditemukan.');
        }

        $this->userModel->where('id_user', $id)->set(['is_active' => 1])->update();
        $this->logAction('Mengaktifkan user: ' . $user['username']);

        return redirect()->to('superadmin/user')->with('success', 'User ' . $user['username'] . ' berhasil diaktifkan.');
    }

    public function deactivate($id)
    {
        $user = $this->userModel->where('id_user', $id)->first() ?? $this->userModel->find($id);

        if (!$user) {
            throw PageNotFoundException::forPageNotFound('User tidak ditemukan.');
        }

        if ($id == session()->get('id_user')) {
            return redirect()->back()->with('error', 'Tidak bisa menonaktifkan akun sendiri.');
        }

        $this->userModel->where('id_user', $id)->set(['is_active' => 0])->update();
        $this->logAction('Menonaktifkan user: ' . $user['username']);

        return redirect()->to('superadmin/user')->with('success', 'User ' . $user['username'] . ' dinonaktifkan.');
    }

    public function delete($id)
    {
        if ($id == 1) {
            return redirect()->back()->with('error', 'Superadmin utama tidak boleh dihapus.');
        }

        if ($id == session()->get('id_user')) {
            return redirect()->back()->with('error', 'Tidak bisa menghapus akun sendiri.');
        }

        $user = $this->userModel->where('id_user', $id)->first() ?? $this->userModel->find($id);

        if (!$user) {
            throw PageNotFoundException::forPageNotFound('User tidak ditemukan.');
        }

        $this->logAction('Menghapus user: ' . $user['username']);
        $this->userModel->where('id_user', $id)->delete();

        return redirect()->to('superadmin/user')->with('success', 'User berhasil dihapus.');
    }

    public function resetPasswordForm($id)
    {
        $user = $this->userModel->where('id_user', $id)->first() ?? $this->userModel->find($id);

        if (!$user) {
            throw PageNotFoundException::forPageNotFound('User tidak ditemukan.');
        }

        return view('superadmin/user/reset_password', [
            'title' => 'Konfirmasi Reset Password',
            'user'  => $user
        ]);
    }

    public function resetPassword($id)
    {
        $user = $this->userModel->where('id_user', $id)->first() ?? $this->userModel->find($id);

        if (!$user) {
            throw PageNotFoundException::forPageNotFound('User tidak ditemukan.');
        }

        $data = [
            'password' => password_hash('12345678', PASSWORD_DEFAULT)
        ];

        $this->userModel->where('id_user', $id)->set($data)->update();
        $this->logAction('Reset password user: ' . $user['username']);

        return redirect()->to('superadmin/user')->with('success', 'Password user ' . $user['username'] . ' berhasil direset ke 12345678.');
    }
}