<?php

class Login extends CI_Controller {
    public function __construct()
    {
        // $this->load does not exist until after you call this
        parent::__construct(); // Construct CI's core so that you can use it

        $this->load->model('at-admin/Security','security_model');
        $this->load->model('at-admin/Activity','activity_model');


    }
    public function index() {
        $data = [
            'page_title' => 'Courtage HK - 登入',
            '_description' => '登入',
//            '_error' => $msg,
            'username' => $this->input->post('username'),
            'password' => $this->input->post('password'),
            'contact_email' => 'info@at-creative.com',
            'contact_phone' => '(852) 3428 8328'
        ];
        $this->lang->load('users');
        $this->load->library('form_validation');
        $this->form_validation->set_rules('userName', 'lang:users_username', 'required');
        $this->form_validation->set_rules('password', 'lang:users_password', 'required');
        if ($this->form_validation->run() == FALSE) {
            $this->load->view('at-admin/login/index', $data);
            return;
        } else {
            $username = $this->input->post('userName');
            $password = $this->input->post('password');
            $rs = $this->security_model->admin_check($username, $password);
            if ($rs !== false){
                $arr['session_id'] = $this->security_model->getcode();
                $arr['user_id'] = $rs['user_id'];
                $arr['ipaddress'] = $_SERVER['REMOTE_ADDR'];
                $arr['entered'] = date('Y-m-d H:i:s');
                $this->security_model->admin_insert($arr);
                $this->session->set_userdata(array(
                    'session_id'=>$arr['session_id'],
                    'email' => $rs['email'],
                    'image' => $rs['image'],
                    'user_id' => $rs['user_id'],
                    'username' => $rs['username']
                ));
                //end set user data session

                $this->activity_model->msg($rs['user_id'], 'Login to system');
                redirect('at-admin/dashboard');
            }
            else {
                $this->activity_model->msg(0, '$username Login false');
                $this->session->set_flashdata('msg',lang('users_invalid_email_or_password'));
                $this->load->view('at-admin/login/index', $data);
            }
        }
    }



}

?>