<?php
/**
 * Created by PhpStorm.
 * User: jaskokoyn
 * Date: 2/15/2015
 * Time: 8:26 PM
 */

require('../../inc/db.php');
include('../../inc/functions.php');

$params                     =   getParams();
$output                     =   array('status' =>  1);

if( !isReady( $params, array("username", "pass") ) ){
    $output['message']      =   "Please fill in all fields!";
    dj($output);
}

$username                   =   secure($params['username']);
$pass                       =   secure($params['pass'], true);
$rm                         =   (isset($params['rm'])) ? secure($params['rm']) : false;

$selectUserQuery            =   $db->prepare("SELECT * FROM users WHERE username = :u AND pass = :p ");
$selectUserQuery->execute(array(
    ":u"                    =>  $username,
    ":p"                    =>  $pass,
));

if($selectUserQuery->rowCount() !== 1){
    $output['message']      =   "Invalid username/password combination.";
    dj($output);
}

$selectUserRow              =   $selectUserQuery->fetch();

if($rm){
    $token                  =   get_random_string( mt_rand(64, 128) );
    $updateUserQuery        =   $db->prepare("UPDATE users SET login_token = :t WHERE id = :id");
    $updateUserQuery->execute(array(
        ":t"                =>  $token,
        ":id"               =>  $selectUserRow['id']
    ));
    setcookie( "oc_token", $token, (time() + 999999), "/" );
}

$output['status']           =   2;
$_SESSION['loggedin']       =   true;
$_SESSION['uid']            =   $selectUserRow['id'];
$_SESSION['username']       =   $username;

dj($output);