<?php

namespace App\Controllers\Admin;

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

class User extends BaseController
{
    public function index()
    {
        $userModel = new UserModel();
        $db = \Config\Database::connect();

        $users = $userModel->select('users.*')
            ->findAll();

        foreach ($users as &$user) {
            $user['roles'] = $userModel->getRoles($user['id']);
        }

        $data = [
            'title' => 'Manajemen Pengguna',
            'users' => $users,
        ];

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

    public function add()
    {
        $roleModel = new RoleModel();

        $data = [
            'title' => 'Tambah User Baru',
            'roles' => $roleModel->findAll(),
        ];
        return view('admin/user/add', $data);
    }

    public function processAdd()
    {
        $userModel = new UserModel();
        $db = \Config\Database::connect();

        $rules = [
            'username' => 'required|is_unique[users.username]',
            'nip' => 'permit_empty|is_unique[users.nip]',
            'name' => 'required',
            'password' => 'required|min_length[5]',
            'role_id' => 'required'
        ];

        if (!$this->validate($rules)) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

        $userData = [
            'username' => $this->request->getPost('username'),
            'nip' => $this->request->getPost('nip'),
            'name' => $this->request->getPost('name'),
            'email' => $this->request->getPost('email'),
            'no_hp' => $this->request->getPost('no_hp'),
            'password' => password_hash($this->request->getPost('password'), PASSWORD_DEFAULT),
            'is_active' => $this->request->getPost('is_active') ?? 1,
        ];

        $userId = $userModel->insert($userData);

        if ($userId) {
            $db->table('user_roles')->insert([
                'user_id' => $userId,
                'role_id' => $this->request->getPost('role_id')
            ]);

            // Sync with Pegawai if NIP exists
            if (!empty($userData['nip'])) {
                $pegawaiModel = new PegawaiModel();
                $noHp = $this->request->getPost('no_hp');
                $pegawai = $pegawaiModel->where('nip_baru', $userData['nip'])->first();
                if ($pegawai) {
                    $pegawaiModel->update($pegawai['id'], [
                        'user_id' => $userId,
                        'no_hp' => $noHp
                    ]);
                }
            }
        }

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

    public function edit($id)
    {
        $userModel = new UserModel();
        $roleModel = new RoleModel();

        $user = $userModel->find($id);
        if (!$user) {
            return redirect()->to('/admin/user')->with('error', 'User tidak ditemukan.');
        }

        $userRoles = $userModel->getRoles($id);
        $user['role_id'] = !empty($userRoles) ? $userRoles[0]['id'] : null;

        // no_hp is now in users table

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

    public function processEdit($id)
    {
        $userModel = new UserModel();
        $db = \Config\Database::connect();

        $rules = [
            'username' => "required|is_unique[users.username,id,{$id}]",
            'nip' => "permit_empty|is_unique[users.nip,id,{$id}]",
            'name' => 'required',
            'role_id' => 'required'
        ];

        if (!$this->validate($rules)) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

        $userData = [
            'username' => $this->request->getPost('username'),
            'nip' => $this->request->getPost('nip'),
            'name' => $this->request->getPost('name'),
            'email' => $this->request->getPost('email'),
            'no_hp' => $this->request->getPost('no_hp'),
            'is_active' => $this->request->getPost('is_active') ?? 1,
        ];

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

        $userModel->update($id, $userData);

        // Update Role
        $db->table('user_roles')->where('user_id', $id)->delete();
        $db->table('user_roles')->insert([
            'user_id' => $id,
            'role_id' => $this->request->getPost('role_id')
        ]);

        // Sync with Pegawai if NIP exists
        if (!empty($userData['nip'])) {
            $pegawaiModel = new PegawaiModel();
            $noHp = $this->request->getPost('no_hp');
            $pegawai = $pegawaiModel->where('nip_baru', $userData['nip'])->first();
            if ($pegawai) {
                $pegawaiModel->update($pegawai['id'], [
                    'user_id' => $id,
                    'no_hp' => $noHp
                ]);
            }
        }

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

    public function delete($id)
    {
        $userModel = new UserModel();
        $userModel->delete($id);
        return redirect()->to('/admin/user')->with('success', 'User berhasil dihapus.');
    }

    public function setStatus($id, $status)
    {
        $userModel = new UserModel();
        $user = $userModel->find($id);
        if ($user) {
            $userModel->update($id, ['is_active' => $status]);
            $msg = 'Status user berhasil diperbarui.';
            if ($status == 1) $msg = 'User berhasil DISETUJUI (Aktif).';
            if ($status == 0) $msg = 'User berhasil DITOLAK (Nonaktif).';
            if ($status == 2) $msg = 'User diubah statusnya menjadi PENDING.';
            return redirect()->to('/admin/user')->with('success', $msg);
        }
        return redirect()->to('/admin/user')->with('error', 'User tidak ditemukan.');
    }

    public function toggle($id)
    {
        $userModel = new UserModel();
        $user = $userModel->find($id);
        if ($user) {
            // If active (1), make it inactive (0). If anything else (0 or 2), make it active (1).
            $newStatus = ($user['is_active'] == 1) ? 0 : 1;
            $userModel->update($id, ['is_active' => $newStatus]);
        }
        return redirect()->to('/admin/user')->with('success', 'Status user berhasil diubah.');
    }
}
