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

class Auth extends CI_Controller
{

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

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

    public function login()
    {
        $this->load->library('form_validation');

        // Set validation rules
        $this->form_validation->set_rules('username', 'Username', 'required|trim');
        $this->form_validation->set_rules('password', 'Password', 'required|trim');

        if ($this->form_validation->run() == FALSE) {
            $this->load->view('auth/login');
        } else {
            $username = $this->input->post('username');
            $password = $this->input->post('password');

            $admin = $this->Admin_model->check_login($username, $password);

            if ($admin) {
                // Set session data
                $session_data = array(
                    'admin_id' => $admin->id,
                    'username' => $admin->username,
                    'nama_lengkap' => $admin->nama_lengkap,
                    'email' => $admin->email,
                    'level' => $admin->level,
                    'logged_in' => TRUE
                );

                $this->session->set_userdata($session_data);

                // Redirect to dashboard
                redirect('admin/dashboard');
            } else {
                $this->session->set_flashdata('error', 'Username atau password salah!');
                redirect('auth');
            }
        }
    }

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