<?php
/**
 * Login
 *
 */
class Login extends Controller {

    function Login()
    {
        parent::Controller();
    }
    
    public function index()
    {
        // ログイン処理をし、indexページに戻る。
        $this->load->library('phpsession');
        $this->load->helper(array('form', 'url'));
        
        $this->load->library('form_validation');
        $this->form_validation->set_error_delimiters('<div class="error">', '</div>');
        
        $this->form_validation->set_rules('username', 'ユーザ名', 'trim|required|xss_clean');
        $this->form_validation->set_rules('password', 'パスワード', 'trim|required|xss_clean');
        
        if ($this->form_validation->run() == FALSE)
        {
            $this->load->view('super/login/index');
        }
        else
        {
            $username = set_value('username');
            $password = set_value('password');
            
            // username, passwordをチェックする
            $this->db->where('username', $username);
            $this->db->where('password', sha1($password));
            $this->db->where('status', 1);
            $query = $this->db->get('supers', 1);
            if ($query->num_rows() > 0)
            {
                $row = $query->row_array();
                $this->phpsession->save('super',
                    array('userid' => $row['userid'],
                          'username' => $row['username'],
                          'name' => $row['name'],
                          'email' => $row['email']));
                // 最終ログイン日時を更新する
                $data = array('last_login' => date("Y-m-d H:i:s"));
                $this->db->where('adminid', $row['adminid']);
                $this->db->update('admins', $data);
                redirect('super/hotels/index/');
            }
            else
            {
                $data['error'] = array();
                $data['error'][] = 'ユーザ名、またはパスワードが間違っています。';
                $this->load->vars($data);
                $this->load->view('super/login/index');
            }
        }
    }
    
    /**
     * ログアウト
     */
    public function logout()
    {
        $this->load->helper(array('form', 'url'));
        $this->load->library('phpsession');
        
        $this->phpsession->clear('super');
        redirect('super/login/index');
    }
}
