<?php

namespace App\Controllers;

use App\Controllers\BaseController;
use CodeIgniter\HTTP\ResponseInterface;

class Auth extends BaseController
{
    public function login()
    {
        // Jika user sudah login, arahkan ke dashboard sesuai rolenya
        if (session()->get('isLoggedIn')) {
            return $this->redirectByRole(session()->get('role'));
        }

        return view('auth/login'); // Kita akan membuat view ini nanti jika diperlukan
    }

    public function attemptLogin()
    {
        $session = session();
        $userModel = new \App\Models\UserModel();

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

        // Validasi input sederhana
        if (empty($username) || empty($password)) {
            return redirect()->back()->with('error', 'Username dan password wajib diisi.');
        }

        // Cari user berdasarkan username
        $user = $userModel->where('username', $username)->first();

        if ($user) {
            // Jika user ditemukan, cek status
            if ($user['status'] !== 'active') {
                return redirect()->back()->with('error', 'Akun Anda tidak aktif. Silakan hubungi admin.');
            }

            // Verifikasi password (password_verify cocok untuk hash PHP standar)
            if (password_verify((string)$password, $user['password_hash'])) {
                // Set data ke session
                $sessionData = [
                    'id'         => $user['id'],
                    'username'   => $user['username'],
                    'nama'       => $user['nama'],
                    'role'       => $user['role'],
                    'isLoggedIn' => true,
                ];
                $session->set($sessionData);

                // Redirect sesuai role
                return $this->redirectByRole($user['role']);
            } else {
                $session->setFlashdata('error', 'Password yang Anda masukkan salah.');
                return redirect()->back();
            }
        } else {
            $session->setFlashdata('error', 'Username tidak ditemukan.');
            return redirect()->back();
        }
    }

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

    /**
     * Fungsi private pembantu untuk menentukan arah redirect berdasarkan role
     */
    private function redirectByRole(string $role)
    {
        // Anda dapat menambahkan semua logika redirect role Anda di sini
        switch ($role) {
            case 'Admin':
                return redirect()->to('/admin/home');
            case 'Mahasiswa':
                return redirect()->to('/mahasiswa/home');
            case 'Dosen':
                return redirect()->to('/dosen/home');
            case 'TU':
                return redirect()->to('/tu/home');
            case 'Keuangan':
                return redirect()->to('/keuangan/home');
            case 'Administrasi Keuangan':
                return redirect()->to('/administrasi-keuangan/home');
            case 'Administrator PMB':
                return redirect()->to('/admin-pmb/home');
            case 'Administrator Prodi':
                return redirect()->to('/admin-prodi/home');
            case 'Dosen Belum-NIDN':
                return redirect()->to('/dosen-non-nidn/home');
            case 'Pimpinan':
                return redirect()->to('/pimpinan/home');
            default:
                return redirect()->to('/login')->with('error', 'Role tidak dikenali.');
        }
    }
}
