<?php

class UserController {

    
/**
     * Display login form
     * Handles URI /user
     * Handles URI /user/index
     */
    
public function indexAction() {
        return 
View::create('base')
            ->
with('page''login');
    }

    
/**
     * Handle POST request made with jQuery Ajax
     * Handles URI /user
     * Handles URI /user/index
     */
    
public function indexAjax() {
        
$validator Validator::create(array(
            
'email' => 'required|email',
            
'password' => 'required|min:5|max:32'
        
));

        
$uas Request::userAgent();

        if (
$validator->failed()) {
            
Log::notice("Bad login request using {$uas}");
            return 
Json::create(array(
                
'success' => false,
                
'message' => 'Your input is invalid',
                
'errors' => $validator->getMessages()
            ));
        }

        
$params $validator->getParamsObj();

        
$user User::fetchOne(array(
            
'email' => $params->email,
            
'password' => $params->password
        
));

        if (
$user === false) {
            
Log::notice("Failed login request using {$uas}");
            return 
Json::create(array(
                
'success' => false,
                
'message' => 'Wrong e-mail or password'
            
));
        } else {
            
$user->last_login_ip Request::ip();
            
$user->last_login_time Db::expr('NOW()');
            
$user->save();

            
Log::info("User #{$user->id} logged in using {$uas}");
            
Session::set('user'$user->getData());

            return 
Json::create(array(
                
'success' => true
            
));
        }
    }

}