<?php

    /**
     * File for the login action.
     *
     * Implements an action function to be called from the {@see Controller}.
     * 
     * @category Action
     */

    /**
     * Logs the user in.
     *
     * Reads the POST parameters looking for the following KEYS:
     *  uname
     *  password
     * If there is a match, it sets cookies and session variables, and
     * redirects to the user homepage.
     * 
     * @param resource $db Database connection. 
     * @return int 0 on success, negative values on error.
     * @category Action
     */
    function action($db = null){
        if (!isset($_POST['uname'], $_POST['password'])){
            return -1;
        }
        $uname = SQLite3::escapeString($_POST['uname']);
        if (strlen($uname) == 0){
            return -2;
        }
        $password = SQLite3::escapeString($_POST['password']);
        if (strlen($password) == 0){
            return -3;
        }
        $password = hash('sha256', $password);
        $q = $db->query("SELECT uid FROM player WHERE upper(name) = upper('$uname') AND password = '$password';");
        $r = $q->fetchArray(SQLITE3_ASSOC);
        if (!$r){
            return -4;
        }
        $uid = $r["uid"];
        setcookie("uid", $uid, time() + 5 * 24 * 60 * 60); // 5 Days
        session_regenerate_id();
        $_SESSION['session'] = true;
        $_SESSION['name'] = $uname;
        $_SESSION['uid'] = $uid;
        header("Location: /$uid/");
        die();
        return 0;
    }
?>

