<?php

namespace App\Controllers;

use App\Models\UserModel;
use App\Models\PegawaiModel;

class Auth extends BaseController
{
    public function login()
    {
        if (session()->get('isLoggedIn')) {
            return $this->redirectByRole();
        }
        return view('auth/login');
    }

    public function register()
    {
        if (session()->get('isLoggedIn')) {
            return $this->redirectByRole();
        }
        return view('auth/register');
    }

    public function registerProcess()
    {
        $session = session();
        $userModel = new UserModel();
        $pegawaiModel = new PegawaiModel();
        $db = \Config\Database::connect();

        $rules = [
            'name' => 'required|min_length[3]',
            'nip' => 'required|is_unique[users.nip]',
            'password' => 'required|min_length[5]',
            'confpassword' => 'matches[password]',
            'no_hp' => 'required',
            'jabatan' => 'required',
            'gol_akhir' => 'required',
            'unor' => 'required'
        ];

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

        $userData = [
            'name' => $this->request->getVar('name'),
            'nip' => $this->request->getVar('nip'),
            'username' => $this->request->getVar('nip'), // Use NIP as username
            'email' => $this->request->getVar('email'),
            'password' => password_hash($this->request->getVar('password'), PASSWORD_DEFAULT),
            'is_active' => 2 // Default to Pending
        ];

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

        if ($userId) {
            // Assign default 'user' role
            $role = $db->table('roles')->where('slug', 'user')->get()->getRow();
            if ($role) {
                $db->table('user_roles')->insert([
                    'user_id' => $userId,
                    'role_id' => $role->id
                ]);
            }

            // Sync or Create profile in pegawai table
            $pegawai = $pegawaiModel->where('nip_baru', $userData['nip'])->first();

            $profileData = [
                'user_id' => $userId,
                'nip_baru' => $userData['nip'],
                'nama' => $userData['name'],
                'email' => $userData['email'],
                'no_hp' => $this->request->getVar('no_hp'),
                'jabatan' => $this->request->getVar('jabatan'),
                'gol_akhir' => $this->request->getVar('gol_akhir'),
                'unor' => $this->request->getVar('unor')
            ];

            if ($pegawai) {
                $pegawaiModel->update($pegawai['id'], $profileData);
            } else {
                // If not in master list, create new pegawai record
                $pegawaiModel->insert($profileData);
            }

            $session->setFlashdata('success', 'Registrasi berhasil! Akun Anda telah terdaftar dan sedang menunggu VALIDASI dari Administrator sebelum dapat digunakan.');
            return redirect()->to('/auth/login');
        } else {
            $session->setFlashdata('msg', 'Registrasi gagal, silakan coba lagi.');
            return redirect()->back()->withInput();
        }
    }

    public function loginProcess()
    {
        $session = session();
        $model = new UserModel();
        $username = $this->request->getPost('username');
        $password = $this->request->getPost('password');

        $user = $model->where('username', $username)
            ->orWhere('nip', $username)
            ->first();

        if ($user) {
            if ($user['is_active'] != 1) {
                $statusMsg = ($user['is_active'] == 2) ? 'Akun Anda masih dalam status PENDING (Menunggu Persetujuan Admin).' : 'Akun Anda telah DITOLAK atau DINONAKTIFKAN.';
                $session->setFlashdata('msg', $statusMsg);
                return redirect()->to('/auth/login');
            }

            if (password_verify($password, $user['password'])) {
                $roles = $model->getRoles($user['id']);
                $roleSlugs = array_column($roles, 'slug');

                $sessionData = [
                    'id' => $user['id'],
                    'name' => $user['name'],
                    'photo' => $user['photo'] ?? null,
                    'username' => $user['username'],
                    'nip' => $user['nip'],
                    'roles' => $roleSlugs,
                    'isLoggedIn' => true,
                ];
                $session->set($sessionData);
                return $this->redirectByRole();
            } else {
                $session->setFlashdata('msg', 'Password salah');
                return redirect()->to('/auth/login');
            }
        } else {
            $session->setFlashdata('msg', 'Username tidak ditemukan');
            return redirect()->to('/auth/login');
        }
    }

    public function logout()
    {
        session()->destroy();
        return redirect()->to('/auth/login');
    }

    public function profile()
    {
        if (!session()->get('isLoggedIn')) {
            return redirect()->to('/auth/login');
        }

        $userModel = new UserModel();
        $user = $userModel->select('users.*, pegawai.no_hp')
            ->join('pegawai', 'pegawai.user_id = users.id', 'left')
            ->where('users.id', session()->get('id'))
            ->first();

        $data = [
            'title' => 'Profil Saya',
            'user' => $user
        ];

        return view('auth/profile', $data);
    }

    public function updateProfile()
    {
        $session = session();
        $userModel = new UserModel();
        $userId = $session->get('id');

        $rules = [
            'name' => 'required|min_length[3]',
            'email' => 'required|valid_email',
        ];

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

        $currentData = $userModel->find($userId);
        $updateData = [
            'name' => $this->request->getPost('name'),
            'email' => $this->request->getPost('email'),
        ];

        // Password update logic
        $newPassword = $this->request->getPost('password');
        if (!empty($newPassword)) {
            $updateData['password'] = password_hash($newPassword, PASSWORD_DEFAULT);
        }

        // Photo upload logic
        $photo = $this->request->getFile('photo');
        if ($photo && $photo->isValid() && !$photo->hasMoved()) {
            $newName = $photo->getRandomName();
            if ($photo->move(FCPATH . 'uploads/profile', $newName)) {
                $updateData['photo'] = $newName;

                // Delete old photo if it exists
                if ($currentData['photo'] && file_exists(FCPATH . 'uploads/profile/' . $currentData['photo'])) {
                    unlink(FCPATH . 'uploads/profile/' . $currentData['photo']);
                }

                $session->set('photo', $newName);
            }
        }

        if ($userModel->update($userId, $updateData)) {
            // Sync WhatsApp to Pegawai Table
            $pegawaiModel = new \App\Models\PegawaiModel();
            $noHp = $this->request->getPost('no_hp');
            $pegawai = $pegawaiModel->where('user_id', $userId)->first();

            if ($pegawai) {
                $pegawaiModel->update($pegawai['id'], ['no_hp' => $noHp]);
            }

            $session->set('name', $updateData['name']);
            return redirect()->to('/auth/profile')->with('success', 'Profil berhasil diperbarui.');
        }

        return redirect()->back()->with('error', 'Gagal memperbarui profil.');
    }

    private function redirectByRole()
    {
        $roles = session()->get('roles');
        if (in_array('superadmin', $roles) || in_array('admin', $roles)) {
            return redirect()->to('/admin/dashboard');
        } elseif (in_array('keuangan', $roles)) {
            return redirect()->to('/keuangan/laporan');
        } elseif (in_array('verifikator', $roles)) {
            return redirect()->to('/verifikator/dashboard');
        } else {
            return redirect()->to('/user/dashboard');
        }
    }
}
