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

class Auth extends CI_Controller {

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

    public function index() {
        if ($this->session->userdata('admin_logged_in')) {
            redirect('dashboard');
        }
        $data['error_msg'] = $this->session->flashdata('login_error');
        $this->load->view('auth/login', $data);
    }

    // Party project style - AJAX method, echo 1 = success, echo 2 = fail
    public function login_validation() {
        $username = $this->input->post('username', TRUE);
        $password = $this->input->post('password');

        if (empty($username) || empty($password)) {
            echo 2;
            return;
        }

        $data = $this->Auth_model->login($username, $password);

        if (!empty($data)) {
            $this->session->set_userdata([
                'admin_logged_in' => TRUE,
                'admin_id'        => $data[0]->id,
                'admin_name'      => $data[0]->full_name,
                'admin_username'  => $data[0]->username,
                'admin_role'      => $data[0]->role,
            ]);
            echo 1;
        } else {
            echo 2;
        }
    }

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