<?php
namespace App\Controllers;
use App\Models\UserModel;

class Auth extends BaseController {
    public function index() {
        return view('admin/login');
    }

    public function login_proses() {
        $session = session();
        $username = $this->request->getPost('username');
        $password = $this->request->getPost('password');
        
        $db = \Config\Database::connect();
        $user = $db->table('users')->where('username', $username)->get()->getRowArray();

        if ($user) {
            if (password_verify($password, $user['password'])) {
                // Simpan data user ke Session
                $session->set([
                    'id_user'      => $user['id_user'],
                    'username'     => $user['username'],
                    'nama'         => $user['nama_lengkap'],
                    'role'         => $user['role'],    // admin/penulis/kaprodi
                    'jurusan'      => $user['jurusan'], // slug jurusan jika kaprodi
                    'isLoggedIn'   => true,
                ]);

                // REDIRECT BERDASARKAN ROLE (Mencegah ERR_TOO_MANY_REDIRECTS)
                if ($user['role'] == 'admin') {
                    return redirect()->to(base_url('admin/slider'))->with('success', 'Selamat datang Admin');
                } elseif ($user['role'] == 'kaprodi') {
                    // Langsung ke halaman jurusan miliknya sendiri
                    return redirect()->to(base_url('admin/jurusan/edit/' . $user['jurusan']))->with('success', 'Selamat datang Kaprodi');
                } elseif ($user['role'] == 'penulis') {
                    // Langsung ke daftar berita
                    return redirect()->to(base_url('admin/berita'))->with('success', 'Selamat datang Penulis');
                } else {
                    return redirect()->to(base_url('admin'))->with('success', 'Selamat datang');
                }
                
            } else {
                $session->setFlashdata('msg', 'Password Salah');
                return redirect()->to(base_url('login'));
            }
        } else {
            $session->setFlashdata('msg', 'Username tidak ditemukan');
            return redirect()->to(base_url('login'));
        }
    }

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