<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Auth extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->library('session');
        $this->load->helper('url');
        $this->load->model('Auth_model');
    }

    public function index() {
        if ($this->session->userdata('logged_in')) {
            redirect('dashboard');
        }
        $this->load->view('auth/login');
    }

    public function login() {
        $username = $this->input->post('username');
        $password = $this->input->post('password');

        // Saat login admin OPD
        $admin = $this->Auth_model->login_admin($username, $password);
        if ($admin) {
            $this->session->set_userdata([
                'logged_in' => true,
                'user_id' => $admin->id,
                'nama_pegawai' => $admin->nama_lengkap,
                'role' => $admin->role,
                'unor_id' => $admin->unor_id
            ]);
            redirect('dashboard');
        }

        // Saat login user ASN
        $user = $this->Auth_model->login_user($username, $password);
        if ($user) {
            // ✅ Pastikan kolom wajib ada
            if (empty($user->id_peg) || empty($user->unor_id)) {
                $this->session->set_flashdata('error', 'Data pegawai tidak lengkap.');
                redirect('auth');
            }

            $this->session->set_userdata([
                'logged_in'    => true,
                'role'         => 'user',
                'pegawai_id'   => $user->id_peg,      // ← WAJIB
                'nama_pegawai' => $user->nama,        // ← pastikan kolom 'nama' ada
                'unor_id'      => $user->unor_id      // ← WAJIB
            ]);
            redirect('dashboard');
        }

        $this->session->set_flashdata('error', 'NIP atau password salah.');
        redirect('auth');
    }

    public function logout() {
        $this->session->sess_destroy();
        redirect('auth');
    }
}