<?php
/**
 * Created by PhpStorm.
 * User: jaskokoyn
 * Date: 4/28/2015
 * Time: 6:30 PM
 */
ob_start();
session_start();

define( "OC_DB_HOST", "OCHOST" );
define( "OC_DB_DBNAME", "OCDBNAME" );
define( "OC_DB_USER", "OCUSER" );
define( "OC_DB_PASS", "OCPASS" );

try {
    $db = new PDO(
        'mysql:host=' . OC_DB_HOST . ';dbname=' . OC_DB_DBNAME,
        OC_DB_USER,
        OC_DB_PASS,
        array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8")
    );
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
    echo 'ERROR: ' . $e->getMessage();
}

if(isset($_COOKIE['oc_token']) && !isset($_SESSION['loggedin'])){
    $token  =   $_COOKIE['oc_token'];

    if(ctype_alnum($token)){
        $checkUserQuery =   $db->prepare("SELECT * FROM users WHERE login_token = :t");
        $checkUserQuery->execute(array(
            ":t"    =>  $token
        ));

        if($checkUserQuery->rowCount() === 1){
            $checkUserRow   =   $checkUserQuery->fetch();
            $_SESSION['loggedin']   =   true;
            $_SESSION['uid']        =   intval($checkUserRow['id']);
            $_SESSION['username']   =   $checkUserRow['username'];
        }
    }
}

if(isset($_SESSION['loggedin'])){
    $user =   $db->prepare("SELECT * FROM users WHERE id = :id");
    $user->execute(array(
        ":id"    =>  $_SESSION['uid']
    ));
    $user   =   $user->fetch();
}

if(!isset($_SESSION['username'])){
    $_SESSION['username'] = "Guest" . mt_rand(4,999999);
}

$settingsQuery  =   $db->prepare("SELECT * FROM settings WHERE id = :id");
$settingsQuery->execute(array(
    ":id"   =>  1
));
$settings       =   $settingsQuery->fetch();