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

class Login extends CI_Controller
{

    public function index()
    {
        $this->load->view('login');
    }

    public function logout()
    {
        $this->load->model('User_model');
        $logged_out = $this->User_model->logout($_SESSION["username"]);
        if ($logged_out) {
            unset($_SESSION["id"]);
            unset($_SESSION["username"]);
            unset($_SESSION["usertype"]);
            unset($_SESSION['usertype']);
            unset($_SESSION['user_login']);
            unset($_SESSION['countSermon']);
            unset($_SESSION['countServices']);
            unset($_SESSION['countPosts']);
            unset($_SESSION['countUsers']);
            $this->load->helper('url');            
        }
        redirect('admin');
    }

    public function checklogin()
    {
        $username = $_POST['login'];
        $password = $_POST['password'];

        $this->load->model('User_model');
        $this->load->model('Message_archive');
        $this->load->model('Services_model');
        $this->load->model('Post_model');


        $user = $this->User_model->get_logged_in_user($username, $password);


        if ($user != null) {
            $countSermon = $this->Message_archive->count_all();
            $countServices = $this->Services_model->count_all();
            $countUsers = $this->User_model->count_all();
            $countPosts = $this->Post_model->count_all();

            $_SESSION['username'] = $user->login;
            $_SESSION['user'] = $user->full_name;
            $_SESSION['usertype'] = $user->user_class;
            $_SESSION['user_login'] = $user->last_login_date;
            $_SESSION['countSermon'] = $countSermon;
            $_SESSION['countServices'] = $countServices;
            $_SESSION['countUsers'] = $countUsers;
            $_SESSION['countPosts'] = $countPosts;
            $this->load->helper('url');
            if($user->user_class == 'ADMIN')
                redirect('admin');
            else{
                           $this->load->helper('url');
            redirect('login?msg=User not permitted to login here!&type=error&log=' . $username); 
            }
        } else {
            $this->load->helper('url');
            redirect('login?msg=Login%20Information%20Incorrect%20or%20User%20Information%20Not%20Found!%20Check%20and%20try%20again%20later!&type=error&log=' . $username);
        }
    }
}
