Index: pages/_app.js
===================================================================
--- pages/_app.js	(revision 41d3f60370077ca99cfecfaf1b8e6b74ea364357)
+++ pages/_app.js	(revision 6568bdeae3dbd082b040ec9b3d752c195313b7e5)
@@ -1,16 +1,6 @@
 import '../styles/globals.css'
 
-import { store } from '../redux/store'
-import { Provider } from 'react-redux'
-import { SessionProvider } from 'next-auth/react'
-
-function MyApp({ Component, pageProps: {session, ...pageProps} }) {
-  return (
-    <SessionProvider session={session}>
-      <Provider store={store}>
-        <Component {...pageProps} />
-      </Provider>
-    </SessionProvider>
-  )
+function MyApp({ Component, pageProps }) {
+  return <Component {...pageProps} />
 }
 
Index: pages/activate/[id].js
===================================================================
--- pages/activate/[id].js	(revision 41d3f60370077ca99cfecfaf1b8e6b74ea364357)
+++ 	(revision )
@@ -1,81 +1,0 @@
-import React from 'react'
-
-import { useRouter } from 'next/router'
-
-import { useEffect, useState } from 'react'
-import { useDispatch, useSelector } from 'react-redux'
-
-import { setStyle } from '../../redux/reducers/styleSlice'
-
-import Head from 'next/head'
-
-import axios from "axios";
-
-const Activate = (props) => {
-    const dispatch = useDispatch();
-
-    const router = useRouter();
-
-    const styleState = useSelector(state => state.style);
-    
-    const [activated, setActivated] = useState(false);
-    
-    useEffect(() => {
-        // display loading screen
-        dispatch(setStyle({
-            ...styleState.style,
-            displayLoadingScreen: true,
-        }));
-
-        const emailActivationId = props.id;
-
-        axios.get(`/api/postgre/activate/${emailActivationId}?action=activate_account`).then(res => {
-            if (res.data?.success) {
-                setActivated(true);
-            }
-            
-            dispatch(setStyle({
-                ...styleState.style,
-                displayLoadingScreen: false,
-            }));
-        });
-    }, []);
-
-    function goHome() {
-        router.push('/');
-    }
-
-    return (
-        <>
-            <Head>
-                <title>Caessino - Activate account</title>
-            </Head>
-
-            <div className="fullscreen fs-centered activateScreen">
-                { activated ? (
-                    <div>
-                        <h3>Your account is activated.</h3>
-                        <h3>You may now login at Caessino.</h3>
-                        <button onClick={() => goHome()} className="primaryButton">Go To The Homepage</button>
-                    </div>
-                ) : (
-                    <div>
-                        <h3>Wrong email activation id.</h3>
-                        <h3>We were unable to activate your account.</h3>
-                        <button onClick={() => goHome()} className="primaryButton">Go To The Homepage</button>
-                    </div>
-                )}
-            </div>
-        </>
-    )
-}
-
-export default Activate
-
-export async function getServerSideProps(context) {
-    return {
-      props: {
-        id: context.query.id
-      },
-    }
-  }
Index: pages/admin/index.js
===================================================================
--- pages/admin/index.js	(revision 41d3f60370077ca99cfecfaf1b8e6b74ea364357)
+++ 	(revision )
@@ -1,37 +1,0 @@
-import Head from 'next/head'
-
-import React from 'react'
-import Complaints from '../../components/admin/Complaints'
-import Dashboard from '../../components/admin/Dashboard'
-import LiveGames from '../../components/admin/LiveGames'
-import Login from '../../components/admin/Login'
-
-import { useSelector } from 'react-redux';
-import Loading from '../../components/Loading'
-
-const Admin = () => {
-    const adminState = useSelector(state => state.admin);
-
-    return (
-        <div>
-            <Head>
-                <title>Caessino - Admin dashboard</title>
-            </Head>
-
-
-            <Loading/>
-
-            { adminState.admin.session_id === '' ? (
-                <Login/>
-            ) : (
-                <Dashboard/>
-            )}
-
-            { adminState.admin.displays.complaintsScreen && <Complaints/> }
-            
-            { adminState.admin.displays.liveGamesScreen && <LiveGames/> }
-        </div>
-    )
-}
-
-export default Admin
Index: pages/api/auth/[...nextauth].js
===================================================================
--- pages/api/auth/[...nextauth].js	(revision 41d3f60370077ca99cfecfaf1b8e6b74ea364357)
+++ 	(revision )
@@ -1,12 +1,0 @@
-import NextAuth from 'next-auth'
-import GoogleProvider from 'next-auth/providers/google'
-
-export default NextAuth({
-    providers: [
-        GoogleProvider({
-            clientId: process.env.GOOGLE_CLIENT_ID,
-            clientSecret: process.env.GOOGLE_CLIENT_SECRET
-        })
-    ],
-    secret: process.env.NEXT_SECRET,
-})
Index: pages/api/blackjack/calculateEarnings.js
===================================================================
--- pages/api/blackjack/calculateEarnings.js	(revision 41d3f60370077ca99cfecfaf1b8e6b74ea364357)
+++ 	(revision )
@@ -1,71 +1,0 @@
-import { checkIfSameValue, checkIfSameColour, checkIfSameSuit, checkIfStraight } from './checkCardCombinations'
-
-export function calculateEarnings(room) {
-    let betEarnings = 0;
-
-    if (room.outcome === 'draw') {
-        betEarnings = room.initialBet;
-    }
-    else if (room.outcome === 'player_won' || room.outcome === 'dealer_busted') {
-        betEarnings = 2 * room.initialBet;
-    }
-    else if (room.outcome === 'player_lost' || room.outcome === 'player_busted') {
-        betEarnings = -1 * room.initialBet;
-    }
-
-    return betEarnings;
-}
-  
-export function calculateSideBetEarnings(room) {
-    let sideBetEarnings = -1 * room.sideBet;
-  
-    if (room.sideBetName != '') {
-      if (room.sideBetName === 'mixed_pair') {
-        if (checkIfSameValue(room.playerCards)) {
-          sideBetEarnings = room.sideBet * 5;
-        }
-      }
-      else if (room.sideBetName === 'coloured_pair') {
-        if (checkIfSameValue(room.playerCards) && checkIfSameColour(room.playerCards)) {
-          sideBetEarnings = room.sideBet * 12;
-        }
-      }
-      else if (room.sideBetName === 'perfect_pair') {
-        if (checkIfSameValue(room.playerCards) && checkIfSameSuit(room.playerCards)) {
-          sideBetEarnings = room.sideBet * 25;
-        }
-      }
-      else if (room.sideBetName === 'flush') {
-        const tmpCards = room.playerCards.slice().concat(room.dealerCards[0]);
-        if (checkIfSameSuit(tmpCards)) {
-          sideBetEarnings = room.sideBet * 5;
-        }
-      }
-      else if (room.sideBetName === 'straight') {
-        const tmpCards = room.playerCards.slice().concat(room.dealerCards[0]);
-        if (checkIfStraight(tmpCards)) {
-          sideBetEarnings = room.sideBet * 10;
-        }
-      }
-      else if (room.sideBetName === 'three_of_a_kind') {
-        const tmpCards = room.playerCards.slice().concat(room.dealerCards[0]);
-        if (checkIfSameValue(tmpCards)) {
-          sideBetEarnings = room.sideBet * 30;
-        }
-      }
-      else if (room.sideBetName === 'straight_flush') {
-        const tmpCards = room.playerCards.slice().concat(room.dealerCards[0]);
-        if (checkIfStraight(tmpCards) && checkIfSameSuit(tmpCards)) {
-          sideBetEarnings = room.sideBet * 40;
-        }
-      }
-      else if (room.sideBetName === 'suited_triple') {
-        const tmpCards = room.playerCards.slice().concat(room.dealerCards[0]);
-        if (checkIfSameSuit(tmpCards) && checkIfSameValue(tmpCards)) {
-          sideBetEarnings = room.sideBet * 100;
-        }
-      }
-    }
-  
-    return sideBetEarnings;
-}
Index: pages/api/blackjack/checkCardCombinations.js
===================================================================
--- pages/api/blackjack/checkCardCombinations.js	(revision 41d3f60370077ca99cfecfaf1b8e6b74ea364357)
+++ 	(revision )
@@ -1,88 +1,0 @@
-export function checkIfSameValue(cards) {
-    for (let i = 1; i < cards.length; i++) {
-      if (cards[i][1] !== cards[i-1][1]) {
-        return false;
-      }
-    }
-  
-    return true;
-}
-  
-function checkIf2CardsAreSameColour(card1, card2) {
-    if (card1[0] === card2[0]) return true;
-    if (card1[0] === 'H' && card2[0] === 'D') return true;
-    if (card1[0] === 'D' && card2[0] === 'H') return true;
-    if (card1[0] === 'S' && card2[0] === 'C') return true;
-    if (card1[0] === 'C' && card2[0] === 'S') return true;
-    return false;
-}
-  
-export function checkIfSameColour(cards) {
-    for (let i = 1; i < cards.length; i++) {
-      if (!checkIf2CardsAreSameColour(cards[i], cards[i-1])) {
-        return false;
-      }
-    }
-  
-    return true;
-}
-  
-export function checkIfSameSuit(cards) {
-    for (let i = 1; i < cards.length; i++) {
-      if (cards[i][0] !== cards[i-1][0]) {
-        return false;
-      }
-    }
-  
-    return true;
-}
-  
-export function checkIfStraight(cards) {
-    let values = ['A', '2', '3', '4', '5', '6', '7', '8', '9', 'X', 'J', 'Q', 'K'];
-  
-    let valuesInCards = [];
-    for (let i = 0; i < cards.length; i++) {
-      valuesInCards.push(cards[i][1]);
-    }
-  
-    let temp = values.reduce((c, v, i) => Object.assign(c, {[v]: i}), {});
-  
-    valuesInCards = valuesInCards.sort((a, b) => temp[a] - temp[b]);
-  
-    let idx = values.indexOf(valuesInCards[0]);
-  
-    let straight = true;
-  
-    for (let i = 0; i < valuesInCards.length; i++) {
-      if (valuesInCards[i] !== values[idx]) {
-        straight = false;
-        break; 
-      }
-  
-      idx++;
-      if (idx >= temp.length) {
-        straight = false;
-        break;
-      }
-    }
-  
-    if (straight) {
-      return true;
-    }
-  
-    values = ['2', '3', '4', '5', '6', '7', '8', '9', 'X', 'J', 'Q', 'K', 'A'];
-    temp = values.reduce((c, v, i) => Object.assign(c, {[v]: i}), {});
-  
-    valuesInCards = valuesInCards.sort((a, b) => temp[a] - temp[b]);
-  
-    idx = values.indexOf(valuesInCards[0]);
-  
-    for (let i = 0; i < valuesInCards.length; i++) {
-      if (valuesInCards[i] !== values[idx]) return false;
-  
-      idx++;
-      if (idx >= temp.length) return false;
-    }
-  
-    return true;
-}
Index: pages/api/blackjack/gameStates.js
===================================================================
--- pages/api/blackjack/gameStates.js	(revision 41d3f60370077ca99cfecfaf1b8e6b74ea364357)
+++ 	(revision )
@@ -1,114 +1,0 @@
-import { rooms } from "../postgre";
-
-const singleDeck = ["SA", "S2", "S3", "S4", "S5", "S6", "S7", "S8", "S9", "SX", "SJ", "SQ", "SK",
-                    "HA", "H2", "H3", "H4", "H5", "H6", "H7", "H8", "H9", "HX", "HJ", "HQ", "HK",
-                    "CA", "C2", "C3", "C4", "C5", "C6", "C7", "C8", "C9", "CX", "CJ", "CQ", "CK",
-                    "DA", "D2", "D3", "D4", "D5", "D6", "D7", "D8", "D9", "DX", "DJ", "DQ", "DK"    ];
-
-/* We are using 5 decks */
-const deck = singleDeck.concat(singleDeck).concat(singleDeck).concat(singleDeck).concat(singleDeck);
-
-/**
- * Sample game state (Begining of the game)
- */
-export let game = {
-  credits: -1,
-  username: '',
-  displayName: '',
-  deck: [...deck],
-  status: '_1_room_created',      // statuses: _1_room_created, _2_made_initial_bet, _3_made_side_bet, _4_cards_on_the_table, _5_game_over
-  playerCards: [],
-  dealerName: 'Lazar',
-  dealerCards: [],
-  initialBet: 0,
-  sideBet: 0,
-  sideBetName: '',
-  outcome: '',
-  earnings: 0,
-  sideBetOutcome: '',
-  sideBetEarnings: 0,
-  messageTitle: '',
-  messageDescription: '',
-  betOutcomeMessageShown: true,
-  sideBetOutcomeMessageShown: true,
-}
-
-export function getGame(session_id) {
-  if (rooms[session_id] !== undefined) {
-    return {
-      success: true,
-      game: rooms[session_id],
-    }
-  }
-
-  return {
-      success: false,
-      game: {...game, playerCards: [...game.playerCards], dealerCards: [...game.dealerCards]},
-  };
-}
-
-export function getRestrictedGameObject(session_id) {
-  const { success, game } = getGame(session_id)
-
-  return {
-    ...game,
-    dealerCards: game.status.includes('_5_') ? game.dealerCards : game.dealerCards.length > 0 ? [game.dealerCards[0]].concat(['back']) : [],
-  }
-}
-
-/**
- * Replace deck if empty
- */
-function checkDeckSize(game) {
-  if (game.deck.length === 0) {
-    game.deck = [...deck];
-  }
-}
-  
-/**
- * Draw a SINGLE random card
- */
-export function drawASingleCard(room) {
-    checkDeckSize(room);
-    let idx = Math.floor(Math.random() * room.deck.length);
-    let card = room.deck[idx];
-  
-    room.deck.splice(idx, 1);
-  
-    return card;
-}
-  
-/**
- * Deal the initial hand of cards
- */
-export function getInitialCards(room) {
-    room.playerCards.push(drawASingleCard(room));
-    room.playerCards.push(drawASingleCard(room));
-  
-    room.dealerCards.push(drawASingleCard(room));
-    room.dealerCards.push(drawASingleCard(room));
-}
-
-/**
- * Calculate the hand value
- */
-export function calculateHandValue(cards) {
-    let value = 0;
-    let aces = 0;
-    for (let i = 0; i < cards.length; i++) {
-      let card = cards[i];
-      if (card.substring(1) === 'A') {
-        value += 11;
-        aces++;
-      } else if (card.substring(1) === 'X' || card.substring(1) === 'J' || card.substring(1) === 'Q' || card.substring(1) === 'K') {
-        value += 10;
-      } else {
-        value += parseInt(card.substring(1));
-      }
-    }
-    while (value > 21 && aces > 0) {
-      value -= 10;
-      aces--;
-    }
-    return value;
-}
Index: pages/api/blackjack/index.js
===================================================================
--- pages/api/blackjack/index.js	(revision 41d3f60370077ca99cfecfaf1b8e6b74ea364357)
+++ 	(revision )
@@ -1,433 +1,0 @@
-import axios from 'axios';
-
-require('dotenv').config();
-
-import { game, drawASingleCard, getInitialCards, calculateHandValue, getGame, getRestrictedGameObject } from './gameStates';
-import { calculateEarnings, calculateSideBetEarnings } from './calculateEarnings';
-
-import { rooms, saveGameInHistory, update_rooms_to_database } from '../postgre/index'
-
-/**
- * Set up a room
- */
-function createARoom(session_id, displayName, username) {
-  let room = {
-    ...game, displayName: displayName, username: username, playerCards: [...game.playerCards], dealerCards: [...game.dealerCards],
-  }
-
-  rooms[session_id] = room;
-}
-
-/**
- * ********************* BEGIN OF REQUEST HANDLER *********************
- */
-export default async function handler(req, res) {
-  /**
-   * GET method
-   */
-   if (req.method === 'GET') {
-    /**
-     * /---------------------- GET ----------------------/
-     * If game status is _5_game_over, restart the room for a new game.
-     * @action play_again
-     * @param session_id
-     */
-    if (req.query.action === 'play_again' && req.query?.session_id) {
-      const session_id = req.query.session_id;
-
-      if (rooms[session_id] !== undefined && rooms[session_id].status.substr(1, 1) === '5') {
-        rooms[session_id] = {...game, displayName: rooms[session_id].displayName, username: rooms[session_id].username, playerCards: [...game.playerCards], dealerCards: [...game.dealerCards]};
-
-        rooms[session_id].betOutcomeMessageShown = true;
-
-        update_rooms_to_database();
-      }
-
-      res.end();
-    }
-
-    /**
-     * /---------------------- GET ----------------------/
-     * If game status is _4_cards_on_the_table, turn off the alert for side bet outcome
-     * @action continue_from_side_bet
-     * @param session_id
-     */
-     if (req.query.action === 'continue_from_side_bet' && req.query?.session_id) {
-      const session_id = req.query.session_id;
-
-      if (rooms[session_id] !== undefined && rooms[session_id].status.substr(1, 1) === '4') {
-        rooms[session_id].sideBetOutcomeMessageShown = true;
-
-        update_rooms_to_database();
-      }
-
-      res.end();
-    }
-
-    /**
-     * /---------------------- GET ----------------------/
-     * If game status is _4_cards_on_the_table, draw cards for the dealer while handValue < 17, and calculate game outcome and player earnings.
-     * Also, update the player's credits and stats in the database through /api/postgre?action=add_credits.
-     * @action stand
-     * @param session_id
-     */
-    if (req.query.action === 'stand' && req.query?.session_id) {
-      const session_id = req.query.session_id;
-
-      if (rooms[session_id] !== undefined && rooms[session_id].status.substr(1, 1) === '4') {
-        const room = rooms[session_id];
-
-        while (calculateHandValue(room.dealerCards) < 17) {
-          room.dealerCards.push(drawASingleCard(room));
-        }
-
-        room.status = '_5_game_over';
-
-        if (calculateHandValue(room.dealerCards) > 21) {
-          room.outcome = 'dealer_busted';
-        }
-        else if (calculateHandValue(room.playerCards) > calculateHandValue(room.dealerCards)) {
-          room.outcome = 'player_won';
-        }
-        else if (calculateHandValue(room.playerCards) < calculateHandValue(room.dealerCards)) {
-          room.outcome = 'player_lost';
-        }
-        else {
-          room.outcome = 'draw';
-        }
-
-        room.earnings = calculateEarnings(room);
-
-        if (room.outcome === 'draw') {
-          room.messageTitle = 'Draw!';
-          room.messageDescription = `You got your $${room.earnings} back`
-        }
-        else if (room.outcome === 'player_won') {
-          room.messageTitle = 'You won!';
-          room.messageDescription = `You won $${room.earnings}`
-        }
-        else if (room.outcome === 'dealer_busted') {
-          room.messageTitle = `Dealer ${room.dealerName} busted!`;
-          room.messageDescription = `You won $${room.earnings}`
-        }
-        else if (room.outcome === 'player_lost') {
-          room.messageTitle = 'You lost!';
-          room.messageDescription = `You lost $${-1*room.earnings}`
-        }
-        room.betOutcomeMessageShown = false;
-
-        rooms[session_id] = room;
-
-        axios.get(`${process.env.HOME_URL}/api/postgre/?action=add_credits&session_id=${session_id}&credits=${room.earnings}&game=blackjack&outcome=${room.outcome}`).then(postgreRes => {
-          if (postgreRes.data?.success) {
-            rooms[session_id].credits = postgreRes.data?.credits;
-
-            res.json({
-              success: true,
-              status: rooms[session_id].status,
-              playerCards: rooms[session_id].playerCards,
-              dealerCards: rooms[session_id].dealerCards,
-              outcome: rooms[session_id].outcome,
-              earnings: rooms[session_id].earnings,
-              credits: postgreRes.data?.credits,
-            })
-
-            update_rooms_to_database();
-          }
-          else {
-            res.json({
-              success: false,
-            })
-          }
-        });
-
-        rooms[session_id].finished = new Date().toGMTString();
-        saveGameInHistory('blackjack', rooms[session_id], rooms[session_id].username);
-
-        return ;
-      }
-
-      res.json({
-        success: false,
-      })
-    }
-
-    /**
-     * /---------------------- GET ----------------------/
-     * If game status is _4_cards_on_the_table, draw a card for the player.
-     * If player busts, update the player's stats in the database through /api/postgre?action=add_credits.
-     * @action hit_a_card
-     * @param session_id
-     */
-    if (req.query.action === 'hit_a_card' && req.query?.session_id) {
-      const session_id = req.query.session_id;
-
-      if (rooms[session_id] !== undefined && rooms[session_id].status.substr(1, 1) === '4') {
-        const room = rooms[session_id];
-
-        room.playerCards.push(drawASingleCard(room));
-
-        rooms[session_id] = room;
-
-        if (calculateHandValue(room.playerCards) > 21) {
-          room.status = '_5_game_over';
-          room.outcome = 'player_busted';
-          
-          room.earnings = calculateEarnings(room);
-
-          room.messageTitle = 'You busted!';
-          room.messageDescription = `You lost $${-1*room.earnings}`
-          
-          room.betOutcomeMessageShown = false;
-
-          rooms[session_id] = room;
-
-          axios.get(`${process.env.HOME_URL}/api/postgre/?action=add_credits&session_id=${session_id}&credits=${room.earnings}&game=blackjack&outcome=${room.outcome}`).then(postgreRes => {
-            if (postgreRes.data?.success) {
-              rooms[session_id].credits = postgreRes.data?.credits;
-
-              res.json({
-                success: true,
-                status: rooms[session_id].status,
-                playerCards: rooms[session_id].playerCards,
-                outcome: rooms[session_id].outcome,
-                earnings: rooms[session_id].earnings,
-                credits: postgreRes.data?.credits,
-              })
-            
-              update_rooms_to_database();
-            }
-            else {
-              res.json({
-                success: false,
-              })
-            }
-          });
-          
-          rooms[session_id].finished = new Date().toGMTString();
-          saveGameInHistory('blackjack', rooms[session_id], rooms[session_id].username);
-        }
-        else {
-          res.json({
-            success: true,
-            status: rooms[session_id].status,
-            playerCards: rooms[session_id].playerCards,
-            outcome: rooms[session_id].outcome,
-            earnings: rooms[session_id].earnings,
-          })
-            
-          update_rooms_to_database();
-        }
-
-        return ;
-      }
-
-      res.json({
-        success: false,
-      })
-    }
-
-     /**
-     * /---------------------- GET ----------------------/
-     * If game status is _3_made_side_bet, check if the player won the side bet or not (if they placed a side bet of course).
-     * Update the player's stats in the database through /api/postgre?action=add_credits.
-     * @action get_initial_cards
-     * @param session_id
-     */
-    if (req.query.action === 'get_initial_cards' && req.query?.session_id) {
-      const session_id = req.query.session_id;
-
-      if (rooms[session_id] !== undefined && rooms[session_id].status.substr(1, 1) === '3') {
-        const room = rooms[session_id];
-
-        getInitialCards(room);
-
-        room.status = '_4_cards_on_the_table';
-
-        rooms[session_id] = room;
-
-        update_rooms_to_database();
-
-        if (room.sideBetName !== '' && room.sideBetName !== 'none') {
-          room.sideBetEarnings = calculateSideBetEarnings(room);
-          room.sideBetOutcome = room.sideBetEarnings > 0 ? 'side_bet_won' : 'side_bet_lost';
-
-          if (room.sideBetOutcome === 'side_bet_won') {
-            room.messageTitle = `You won the side bet!`;
-            room.messageDescription = `You won $${room.sideBetEarnings}`
-          }
-          else if (room.sideBetOutcome === 'side_bet_lost') {
-            room.messageTitle = `You lost the side bet!`;
-            room.messageDescription = `You lost $${-1*room.sideBetEarnings}`
-          }
-
-          room.sideBetOutcomeMessageShown = false;
-          
-          rooms[session_id] = room;
-
-          axios.get(`${process.env.HOME_URL}/api/postgre/?action=add_credits&session_id=${session_id}&credits=${room.sideBetEarnings}`).then(postgreRes => {
-            if (postgreRes.data?.success) {
-              rooms[session_id].credits = postgreRes.data?.credits;
-
-              update_rooms_to_database();
-            }
-          });
-        }
-      }
-
-      res.end();
-    }
-
-    /**
-     * /---------------------- GET ----------------------/
-     * If game status is _2_made_initial_bet, place a side bet if the user has chosen one.
-     * @action make_side_bet
-     * @param session_id
-     * @param bet
-     * @param betName
-     */
-    if (req.query.action === 'make_side_bet' && req.query?.session_id && req.query?.bet && req.query?.betName) {
-      const session_id = req.query.session_id;
-
-      if (rooms[session_id] !== undefined && rooms[session_id].status.substr(1, 1) === '2') {
-        if (req.query?.skip !== 'true' && parseInt(req.query.bet) <= 0) {
-            return ;
-        }
-
-        axios.get(`${process.env.HOME_URL}/api/postgre?action=take_credits&session_id=${session_id}&credits=${req.query.bet}`).then(postgreRes => {
-          if (postgreRes.data?.success) {
-            rooms[session_id].credits = postgreRes.data?.credits;
-
-            const room = rooms[session_id];
-
-            room.sideBet = parseInt(req.query.bet);
-            room.sideBetName = req.query.betName;
-            room.status = '_3_made_side_bet';
-
-            rooms[session_id] = room;
-
-            res.json({
-              success: true,
-            })
-            
-            update_rooms_to_database();
-          }
-          else {
-            res.end();
-          }
-        });
-      }
-    }
-    
-    /**
-     * /---------------------- GET ----------------------/
-     * If game status is _1_room_created, get the initial bet placed by the player.
-     * @action make_initial_bet
-     * @param session_id
-     * @param bet
-     */
-    if (req.query.action === 'make_initial_bet' && req.query?.session_id && req.query?.bet) {
-      const session_id = req.query.session_id;
-
-      if (rooms[session_id] !== undefined && rooms[session_id].status.substr(1, 1) === '1') {
-        if (parseInt(req.query.bet) <= 0) return ;
-
-        axios.get(`${process.env.HOME_URL}/api/postgre?action=take_credits&session_id=${session_id}&credits=${req.query.bet}`).then(postgreRes => {
-          if (postgreRes.data?.success) {
-            rooms[session_id].credits = postgreRes.data?.credits;
-
-            const room = rooms[session_id];
-
-            room.initialBet = parseInt(req.query.bet);
-            room.status = '_2_made_initial_bet';
-
-            rooms[session_id] = room;
-            
-            update_rooms_to_database();
-          }
-        });
-      }
-
-      res.end();
-    }
-
-    /**
-     * /---------------------- GET ----------------------/
-     * Updates the state periodically
-     * @action update_state
-     * @param session_id
-     */
-     if (req.query.action === 'update_state' && req.query?.session_id) {
-      const session_id = req.query.session_id;
-
-      const { success, game } = getGame(session_id);
-
-      res.json({
-          success: true,
-          blackjackGame: getRestrictedGameObject(session_id),
-      })
-    }
-
-    /**
-     * /---------------------- GET ----------------------/
-     * If the player is not in an existing room, create a room for them.
-     * If they are reconnecting, get the room they were in.
-     * @action get_player_info_on_enter
-     * @param session_id
-     */
-    if (req.query.action === 'get_player_info_on_enter' && req.query?.session_id) {
-      const session_id = req.query.session_id;
-
-      axios.get(`${process.env.HOME_URL}/api/postgre?action=check_if_logged_in&session_id=${session_id}`).then(postgreRes => {
-        if (postgreRes.data?.success) {
-          if (rooms[session_id] !== undefined) {
-            // room exists
-          }
-          else {
-            createARoom(session_id, postgreRes.data?.displayName, postgreRes.data?.username);
-          }
-    
-          let dealerCardsTmp = [];
-          if (rooms[session_id].status.substr(1, 1) != '5') { // 5 == game_over
-            rooms[session_id].dealerCards.forEach((card, i) => {
-              if (i === 0) {
-                dealerCardsTmp.push(card);
-              }
-              else {
-                dealerCardsTmp.push('back');
-              }
-            })
-          }
-          else {
-            dealerCardsTmp = rooms[session_id].dealerCards;
-          }
-    
-          res.json({
-            success: true,
-            status: rooms[session_id].status,
-            initialBet: rooms[session_id].initialBet,
-            sideBet: rooms[session_id].sideBet,
-            sideBetName: rooms[session_id].sideBetName,
-            playerCards: rooms[session_id].playerCards,
-            dealerCards: dealerCardsTmp,
-            outcome: rooms[session_id].outcome,
-            earnings: rooms[session_id].earnings,
-            displayName: postgreRes.data?.displayName,
-            session_id: postgreRes.data?.session_id,
-            credits: postgreRes.data?.credits,
-          })
-            
-          update_rooms_to_database();
-        }
-        else {
-          res.json({
-            success: false,
-          })
-        }
-      });
-    }
-  }
-}
-/**
- * ********************* END OF REQUEST HANDLER *********************
- */
Index: pages/api/hello.js
===================================================================
--- pages/api/hello.js	(revision 6568bdeae3dbd082b040ec9b3d752c195313b7e5)
+++ pages/api/hello.js	(revision 6568bdeae3dbd082b040ec9b3d752c195313b7e5)
@@ -0,0 +1,5 @@
+// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
+
+export default function handler(req, res) {
+  res.status(200).json({ name: 'John Doe' })
+}
Index: pages/api/poker/gameStates.js
===================================================================
--- pages/api/poker/gameStates.js	(revision 41d3f60370077ca99cfecfaf1b8e6b74ea364357)
+++ 	(revision )
@@ -1,230 +1,0 @@
-import { tables } from "../postgre/index";
-
-import { v4 as uuidv4 } from "uuid";
-
-export const singleDeck = ["SA", "S2", "S3", "S4", "S5", "S6", "S7", "S8", "S9", "SX", "SJ", "SQ", "SK",
-                           "HA", "H2", "H3", "H4", "H5", "H6", "H7", "H8", "H9", "HX", "HJ", "HQ", "HK",
-                           "CA", "C2", "C3", "C4", "C5", "C6", "C7", "C8", "C9", "CX", "CJ", "CQ", "CK",
-                           "DA", "D2", "D3", "D4", "D5", "D6", "D7", "D8", "D9", "DX", "DJ", "DQ", "DK"    ];
-
-export const deck = [...singleDeck];
-
-export const sampleTable = {
-    id: '',
-    name: '',
-    status: '_1_just_created',
-    creator: '',
-    started: false,
-    ended: false,
-    round: 0,
-    turnIdx: -1,
-    lastActivity: 0,
-    pot: 0,
-    lastBet: 20,
-    turnsSinceLastBet: 0,
-    deck: [...deck],
-    players: [],
-    winners: [],
-    splitWinners: false,
-    cards: [],
-}
-
-export const samplePlayer = {
-    id: '',
-    table: '',
-    credits: -1,
-    status: '_1_just_entered',
-    displayName: '',
-    cards: [],
-    betAmount: 0,
-    wonAmount: 0,
-    isSatDown: false,
-    isCoordinator: false,
-    isFolded: false,
-    isGhost: false,
-    hand: {
-        hand: '',
-        highCard: 0,
-    },
-}
-
-
-/**
- * ********************* BEGIN OF FUNCTIONS *********************
- */
-
-export function createTable(playerId, playerName, tableName, username) {
-    const tableId = uuidv4();
-
-    const table = {
-        id: tableId,
-        name: tableName,
-        status: '_1_just_created',
-        creator: playerName,
-        started: false,
-        ended: false,
-        round: 0,
-        turnIdx: -1,
-        lastActivity: 0,
-        prevTurnIdx: -2,
-        pot: 0,
-        lastBet: 20,
-        turnsSinceLastBet: 0,
-        deck: [...deck],
-        players: [{
-            id: playerId,
-            table: tableId,
-            username: username,
-            credits: -1,
-            status: '_1_just_entered',
-            displayName: playerName,
-            cards: [],
-            betAmount: 0,
-            wonAmount: 0,
-            isSatDown: false,
-            isCoordinator: true,
-            isFolded: false,
-            isGhost: false,
-            hand: {
-                hand: '',
-                highCard: 0,
-            },
-        }],
-        onlyOnePlayerLeft: false,
-        winners: [],
-        splitWinners: false,
-        cards: [],
-    }
-
-    tables.push(table)
-
-    return table;
-}
-
-export function getRestrictedTablesArray() {
-    let result = [];
-
-    tables.forEach(table => {
-        let tmpPlayers = [];
-        table.players.forEach(player => {
-            tmpPlayers.push({
-                ...player,
-                id: '',
-                table: '',
-                cards: '',
-            })
-        });
-
-        let tmpWinners = [];
-        table.winners.forEach(winner => {
-            tmpWinners.push({
-                ...winner,
-                id: '',
-                table: '',
-                cards: '',
-            })
-        });
-
-        let tmp = {
-            ...table,
-            deck: [],
-            players: tmpPlayers,
-            winners: tmpWinners,
-            turnTimeout: null,
-        }
-
-        result.push({...tmp});
-    })
-
-    return result;
-}
-
-export function getRestrictedTableArray(tableId, session_id) {
-    let result = undefined;
-
-    let tableIdx = tables.map(e=>e.id).indexOf(tableId);
-
-    if (tableIdx !== -1) {
-        let table = tables[tableIdx];
-
-        let tmpPlayers = [];
-        table.players.forEach(player => {
-            if (player.id === session_id) {
-                tmpPlayers.push({
-                    ...player,
-                    id: '',
-                    table: '',
-                })
-            }
-            else {
-                tmpPlayers.push({
-                    ...player,
-                    id: '',
-                    table: '',
-                    cards: table.ended ? player.cards : player.cards.length > 0 ? ['back', 'back'] : '',
-                })
-            }
-        });
-
-        let tmpWinners = [];
-        table.winners.forEach(winner => {
-            if (winner.id === session_id) {
-                tmpWinners.push({
-                    ...winner,
-                    id: '',
-                    table: '',
-                })
-            }
-            else {
-                tmpWinners.push({
-                    ...winner,
-                    id: '',
-                    table: '',
-                    cards: table.ended ? winner.cards : winner.cards.length > 0 ? ['back', 'back'] : '',
-                })
-            }
-        });
-        result = {
-            ...table,
-            players: tmpPlayers,
-            winners: tmpWinners,
-            turnTimeout: null,
-        }
-    }
-
-    return result;
-}
-
-export function getTable(tableId) {
-    const tableIdx = tables.map(e=>e.id).indexOf(tableId);
-
-    if (tableIdx !== -1) {
-        return tables[tableIdx];
-    }
-
-    return undefined;
-}
-
-export function getTableAndPlayer(session_id) {
-    for (let tableIdx = 0; tableIdx < tables.length; tableIdx++) {
-        const playerIdx = tables[tableIdx].players.filter(e=>e.isGhost === false).map(e=>e.id).indexOf(session_id);
-
-        if (playerIdx !== -1) {
-            return {
-                success: true,
-                table: tables[tableIdx],
-                player: tables[tableIdx].players[playerIdx],
-            }
-        }
-    }
-
-    return {
-        success: false,
-        table: {...sampleTable},
-        player: {...samplePlayer},
-    };
-}
-
-/**
- * ********************* END OF FUNCTIONS *********************
- */
Index: pages/api/poker/handEvaluations.js
===================================================================
--- pages/api/poker/handEvaluations.js	(revision 41d3f60370077ca99cfecfaf1b8e6b74ea364357)
+++ 	(revision )
@@ -1,113 +1,0 @@
-export const hands = [
-    'Royal Flush',
-    'Straight Flush',
-    'Four of a Kind',
-    'Full House',
-    'Flush',
-    'Straight',
-    'Three of a Kind',
-    'Two Pairs',
-    'Pair',
-    'High Card',
-]
-
-const order = "23456789XJQKA"
-export function getHandDetails(hand) {
-    const cards = hand
-    const faces = cards.map(a => String.fromCharCode([77 - order.indexOf(a[1])])).sort()
-    const suits = cards.map(a => a[0]).sort()
-    const counts = faces.reduce(count, {})
-    const duplicates = Object.values(counts).reduce(count, {})
-    const flush = suits[0] === suits[4]
-    const first = faces[0].charCodeAt(1)
-    const straight = faces.every((f, index) => f.charCodeAt(1) - first === index)
-    let rank =
-        (flush && straight && 1) ||
-        (duplicates[4] && 2) ||
-        (duplicates[3] && duplicates[2] && 3) ||
-        (flush && 4) ||
-        (straight && 5) ||
-        (duplicates[3] && 6) ||
-        (duplicates[2] > 1 && 7) ||
-        (duplicates[2] && 8) ||
-        9;
-
-    return { hand: hands[rank], highCard: faces.sort(byCountFirst).join("") }
-
-    function byCountFirst(a, b) {
-        //Counts are in reverse order - bigger is better
-        const countDiff = counts[b] - counts[a]
-        if (countDiff) return countDiff // If counts don't match return
-        return b > a ? -1 : b === a ? 0 : 1
-    }
-
-    function count(c, a) {
-        c[a] = (c[a] || 0) + 1
-        return c
-    }
-}
-
-export function compareHands(h1, h2) {
-    let d1 = getHandDetails(h1)
-    let d2 = getHandDetails(h2)
-    if (hands.indexOf(d1.hand) === hands.indexOf(d2.hand)) {
-        if (d1.highCard < d2.highCard) {
-            return d2;
-        } else if (d1.highCard > d2.highCard) {
-            return d1;
-        } else {
-            return d1;
-        }
-    }
-    return hands.indexOf(d1.hand) < hands.indexOf(d2.hand) ? d2 : d1;
-}
-
-export function getBestHandDetails(playerCards, tableCards) {
-    let combinations = getCardCombinations(playerCards, tableCards);
-
-    let h1 = combinations[0];
-    let bestHand = h1;
-    combinations.forEach(combination => {
-        bestHand = compareHands(h1, combination);
-        h1 = combination;
-    })
-
-    return bestHand;
-}
-
-export function getCardCombinations(playerCards, tableCards) {
-    let combinations = [];
-
-    combinations.push([playerCards[0], tableCards[0], tableCards[1], tableCards[2], tableCards[3]])
-    combinations.push([playerCards[0], tableCards[0], tableCards[1], tableCards[2], tableCards[4]])
-
-    combinations.push([playerCards[0], tableCards[0], tableCards[1], tableCards[4], tableCards[3]])
-    combinations.push([playerCards[0], tableCards[0], tableCards[4], tableCards[2], tableCards[3]])
-    combinations.push([playerCards[0], tableCards[4], tableCards[1], tableCards[2], tableCards[3]])
-
-    
-    combinations.push([playerCards[1], tableCards[0], tableCards[1], tableCards[2], tableCards[3]])
-    combinations.push([playerCards[1], tableCards[0], tableCards[1], tableCards[2], tableCards[4]])
-
-    combinations.push([playerCards[1], tableCards[0], tableCards[1], tableCards[4], tableCards[3]])
-    combinations.push([playerCards[1], tableCards[0], tableCards[4], tableCards[2], tableCards[3]])
-    combinations.push([playerCards[1], tableCards[4], tableCards[1], tableCards[2], tableCards[3]])
-
-
-    combinations.push([playerCards[0], playerCards[1], tableCards[0], tableCards[1], tableCards[2]])
-    combinations.push([playerCards[0], playerCards[1], tableCards[0], tableCards[1], tableCards[3]])
-    combinations.push([playerCards[0], playerCards[1], tableCards[0], tableCards[1], tableCards[4]])
-
-    combinations.push([playerCards[0], playerCards[1], tableCards[0], tableCards[2], tableCards[3]])
-    combinations.push([playerCards[0], playerCards[1], tableCards[0], tableCards[2], tableCards[4]])
-    combinations.push([playerCards[0], playerCards[1], tableCards[0], tableCards[3], tableCards[4]])
-
-    combinations.push([playerCards[0], playerCards[1], tableCards[1], tableCards[2], tableCards[3]])
-    combinations.push([playerCards[0], playerCards[1], tableCards[1], tableCards[2], tableCards[4]])
-    combinations.push([playerCards[0], playerCards[1], tableCards[1], tableCards[3], tableCards[4]])
-
-    combinations.push([playerCards[0], playerCards[1], tableCards[2], tableCards[3], tableCards[4]])
-
-
-    return combinations;
-}
Index: pages/api/poker/index.js
===================================================================
--- pages/api/poker/index.js	(revision 41d3f60370077ca99cfecfaf1b8e6b74ea364357)
+++ 	(revision )
@@ -1,326 +1,0 @@
-import axios from 'axios';
-
-require('dotenv').config();
-
-import { createTable, getRestrictedTablesArray, getRestrictedTableArray, getTable, getTableAndPlayer } from './gameStates';
-
-import { drawASingleCard, setNextPlayerIdx, progressRoundIfNeeded } from './tableSpecific'
-
-import { update_tables_to_database } from '../postgre/index'
-
-/**
- * ********************* BEGIN OF REQUEST HANDLER *********************
- */
-export default async function handler(req, res) {
-    /**
-     * GET method
-     */
-    if (req.method === 'GET') {
-        
-        /**
-         * /---------------------- GET ----------------------/
-         * Creates the table and enters the user inside
-         * @action game_action
-         * @param session_id
-         * @param specificAction
-         * @param betAmount
-         */
-        if (req.query.action === 'game_action' && req.query?.session_id && req.query?.specificAction && req.query?.betAmount) {
-            const { success, table, player } = getTableAndPlayer(req.query.session_id)
-
-            if (success && table.started && !table.ended && player.isSatDown && !player.isFolded) {
-                if (table.players.map(e=>e.id).indexOf(req.query.session_id) !== table.turnIdx) {
-                    res.end();
-                    return ;
-                }
-
-                let okayToGo = false;
-
-                if (req.query.specificAction === 'check') {
-                    if (table.lastBet === 0) {
-                        table.turnsSinceLastBet++;
-                        okayToGo = true;
-                        
-                        progressRoundIfNeeded(table.id);
-                    }
-                }
-                else if (req.query.specificAction === 'call') {
-                    await axios.get(`${process.env.HOME_URL}/api/postgre/?action=take_credits&session_id=${req.query.session_id}&credits=${table.lastBet}&takeWhatYouCan=true`).then(postgreRes => {
-                        if (postgreRes.data?.success) {
-                            player.credits = postgreRes.data?.credits;
-
-                            if (player.credits >= table.lastBet)
-                                player.betAmount += table.lastBet;
-                            else
-                                player.betAmount += player.credits;
-                                
-                            table.pot += table.lastBet;
-                            table.turnsSinceLastBet++;
-                            okayToGo = true;
-        
-                            progressRoundIfNeeded(table.id);
-                        }
-                    });
-                }
-                else if (req.query.specificAction === 'raise') {
-                    const betAmount = parseInt(req.query.betAmount);
-
-                    if (betAmount >= table.lastBet) {
-                        await axios.get(`${process.env.HOME_URL}/api/postgre/?action=take_credits&session_id=${req.query.session_id}&credits=${betAmount}&takeWhatYouCan=true`).then(postgreRes => {
-                            if (postgreRes.data?.success) {
-                                player.credits = postgreRes.data?.credits;
-
-                                player.betAmount += betAmount;
-                                table.pot += betAmount;
-                                table.turnsSinceLastBet = 1;
-                                okayToGo = true;
-                                
-                                progressRoundIfNeeded(table.id);
-                            }
-                        });
-                    }
-                }
-                else if (req.query.specificAction === 'fold') {
-                    player.isFolded = true;
-                    okayToGo = true;
-
-                    progressRoundIfNeeded(table.id);
-                }
-
-                if (okayToGo) {
-                    table.lastActivity = Date.now();
-                    setNextPlayerIdx(table.id);
-                }
-            }
-            
-            update_tables_to_database();
-
-            res.end();
-        }
-
-        /**
-         * /---------------------- GET ----------------------/
-         * Creates the table and enters the user inside
-         * @action start_game
-         * @param session_id
-         */
-        if (req.query.action === 'start_game' && req.query?.session_id) {
-            const { success, table } = getTableAndPlayer(req.query.session_id)
-
-            if (success && !table.started && !table.ended && table.players.filter(e=>e.isSatDown===true).length >= 2) {
-                table.players.forEach(player => {
-                    axios.get(`${process.env.HOME_URL}/api/postgre/?action=check_if_logged_in&session_id=${player.id}`).then(postgreRes => {
-                        if (postgreRes.data?.success) {
-                            player.credits = postgreRes.data?.credits;
-                        }
-                    });
-                })
-
-                table.lastActivity = Date.now();
-                table.started = true;
-                table.round = 1;
-
-                table.turnIdx = Math.floor(Math.random(0, table.players.length))
-                setNextPlayerIdx(table.id);
-
-                table.players.forEach(player => {
-                    if (player.isSatDown) {
-                        for (let i = 0; i < 2; i++) {
-                            const card = drawASingleCard(table.id);
-                            
-                            if (card !== undefined) {
-                                player.cards.push(card);
-                            }
-                        }
-                    }
-                })
-            }
-
-            update_tables_to_database();
-            
-            res.end();
-        }
-
-        /**
-         * /---------------------- GET ----------------------/
-         * Creates the table and enters the user inside
-         * @action sit_down
-         * @param session_id
-         * @param tableId
-         */
-         if (req.query.action === 'sit_down' && req.query?.session_id && req.query?.tableId) {
-            const { success, table, player } = getTableAndPlayer(req.query.session_id)
-
-            if (success && !table.started) {
-                player.isSatDown = true;
-            }
-
-            update_tables_to_database();
-
-            res.end();
-        }
-
-        /**
-         * /---------------------- GET ----------------------/
-         * Creates the table and enters the user inside
-         * @action leave_table
-         * @param session_id
-         */
-         if (req.query.action === 'leave_table' && req.query?.session_id) {
-            const { success, table, player } = getTableAndPlayer(req.query.session_id);
-
-            if (success) {
-                table.lastActivity = Date.now();
-                
-                player.isGhost = true;
-                player.isFolded = true;
-
-                if (table.started) {
-                    if (table.players[table.turnIdx] !== undefined && table.players[table.turnIdx] === player) {
-                        setNextPlayerIdx(table.id);
-                    }
-                }
-                else {
-                    table.players = table.players.filter(e=>e.isGhost === false);
-                }
-            }
-
-            update_tables_to_database();
-
-            res.end();
-        }
-
-        /**
-         * /---------------------- GET ----------------------/
-         * Creates the table and enters the user inside
-         * @action join_a_table
-         * @param session_id
-         * @param tableId
-         * @param displayName
-         * @param username
-         */
-         if (req.query.action === 'join_a_table' && req.query?.session_id && req.query?.tableId && req.query?.displayName && req.query?.username) {
-            if (req.query.tableId.length > 0) {
-                const { success } = getTableAndPlayer(req.query.session_id);
-
-                if (!success) {
-                    const table = getTable(req.query.tableId)
-
-                    if (table !== undefined && !table.started) {
-                        table.players.push({
-                            id: req.query.session_id,
-                            table: req.query.tableId,
-                            username: req.query.username,
-                            credits: -1,
-                            status: '_1_just_entered',
-                            displayName: req.query.displayName,
-                            cards: [],
-                            betAmount: 0,
-                            wonAmount: 0,
-                            isSatDown: false,
-                            isCoordinator: false,
-                            isFolded: false,
-                            isGhost: false,
-                            hand: {
-                                hand: '',
-                                highCard: 0,
-                            },
-                        })
-                    }
-                }
-            }
-
-            update_tables_to_database();
-
-            res.end();
-        }
-
-        /**
-         * /---------------------- GET ----------------------/
-         * Creates the table and enters the user inside
-         * @action create_a_table
-         * @param session_id
-         * @param displayName
-         * @param tableName
-         * @param username
-         */
-        if (req.query.action === 'create_a_table' && req.query?.session_id && req.query?.displayName && req.query?.tableName && req.query?.username) {
-            const { success } = getTableAndPlayer(req.query.session_id);
-
-            if (!success) {
-                createTable(req.query.session_id, req.query.displayName, req.query.tableName, req.query.username);
-            }
-
-            update_tables_to_database();
-
-            res.end();
-        }
-
-        /**
-         * /---------------------- GET ----------------------/
-         * Updates the state periodically
-         * @action update_state
-         * @param session_id
-         */
-        if (req.query.action === 'update_state' && req.query?.session_id) {
-            const session_id = req.query.session_id;
-
-            const { success, table, player } = getTableAndPlayer(session_id);
-
-            if (success && table.started && !table.ended) {
-                const d = Date.now();
-
-                if (d - table.lastActivity > 30000) {
-                    if (table.players[table.turnIdx] !== undefined) {
-                        table.players[table.turnIdx].isFolded = true;
-
-                        table.lastActivity = Date.now();
-                        setNextPlayerIdx(table.id);
-                        
-                        update_tables_to_database();
-                    }
-                }
-            }
-
-            res.json({
-                success: true,
-                pokerGame: {
-                    tables: getRestrictedTablesArray(),
-                    table: getRestrictedTableArray(table.id, req.query.session_id),
-                    player: player,
-                }
-            })
-        }
-
-        /**
-         * /---------------------- GET ----------------------/
-         * If the player is not in an existing room, create a room for them.
-         * If they are reconnecting, get the room they were in.
-         * @action get_player_info_on_enter
-         * @param session_id
-         */
-        if (req.query.action === 'get_player_info_on_enter' && req.query?.session_id) {
-            const session_id = req.query.session_id;
-
-            axios.get(`${process.env.HOME_URL}/api/postgre?action=check_if_logged_in&session_id=${session_id}`).then(postgreRes => {
-                if (postgreRes.data?.success) {
-                    res.json({
-                        success: true,
-                        displayName: postgreRes.data?.displayName,
-                        username: postgreRes.data?.username,
-                        session_id: postgreRes.data?.session_id,
-                        credits: postgreRes.data?.credits,
-                    })
-                }
-                else {
-                    res.json({
-                        success: false,
-                    })
-                }
-            });
-        }
-    }
-}
-/**
- * ********************* END OF REQUEST HANDLER *********************
- */
Index: pages/api/poker/tableSpecific.js
===================================================================
--- pages/api/poker/tableSpecific.js	(revision 41d3f60370077ca99cfecfaf1b8e6b74ea364357)
+++ 	(revision )
@@ -1,338 +1,0 @@
-import { saveGameInHistory, tables } from '../postgre/index';
-
-import { deck } from './gameStates'
-
-import { hands, getBestHandDetails } from './handEvaluations';
-
-import axios from 'axios';
-
-require('dotenv').config();
-
-/**
- * Replace deck if empty
- */
-export function checkDeckSize(tableId) {
-    const tableIdx = tables.map(e=>e.id).indexOf(tableId);
-
-    if (tables[tableIdx] !== undefined) {
-        if (tables[tableIdx].deck.length === 0) {
-            tables[tableIdx].deck = [...deck];
-        }
-    }
-}
-
-/**
- * Draw a SINGLE random card
- */
-export function drawASingleCard(tableId) {
-    const tableIdx = tables.map(e=>e.id).indexOf(tableId);
-
-    if (tables[tableIdx] !== undefined) {
-        checkDeckSize(tableId);
-        
-        let idx = Math.floor(Math.random() * tables[tableIdx].deck.length);
-        let card = tables[tableIdx].deck[idx];
-
-        tables[tableIdx].deck.splice(idx, 1);
-
-        return card;
-    }
-
-    return undefined;
-}
-
-export function getMaxBet(tableId) {
-    const tableIdx = tables.map(e=>e.id).indexOf(tableId);
-
-    if (tables[tableIdx] !== undefined) {
-        const table = tables[tableIdx];
-
-        let maxBet = 0;
-        table.players.forEach(player => {
-            if (player.betAmount > maxBet) {
-                maxBet = player.betAmount;
-            }
-        })
-        
-        return maxBet;
-    }
-    
-    return 0;
-}
-
-export function setNextPlayerIdx(tableId) {
-    const tableIdx = tables.map(e=>e.id).indexOf(tableId);
-
-    if (tables[tableIdx] !== undefined && tables[tableIdx].started && !tables[tableIdx].ended) {
-        const table = tables[tableIdx];
-
-        const remainingPlayers = table.players.filter(e=>e.isSatDown===true).filter(e=>e.isGhost===false);
-        if (remainingPlayers.length === 1) {
-            setWinnerDirect(table.id, remainingPlayers[0]);
-
-            return ;
-        }
-
-        const remainingPlayersWithCredits = table.players.filter(e=>e.isSatDown===true).filter(e=>e.isGhost===false).filter(e=>e.isFolded===false).filter(e=>e.credits > 0);
-        if (remainingPlayersWithCredits.length === 1) {
-            progressRoundTillTheEnd(table.id);
-
-            return ;
-        }
-
-        if (table.turnTimeout !== null) clearTimeout(table.turnTimeout);
-        table.prevTurnIdx = -2;
-
-        let counter = 10;
-
-        while (true) {
-            counter--;
-
-            table.turnIdx++;
-            table.turnIdx %= table.players.length;
-            
-            if (table.players[table.turnIdx] !== undefined && table.players[table.turnIdx].isSatDown && !table.players[table.turnIdx].isFolded) {
-                if (table.round >= 2 && table.players[table.turnIdx].credits === 0) continue;
-
-                table.lastBet = getMaxBet(table.id) - table.players[table.turnIdx].betAmount;
-                if (table.round === 1 && getMaxBet(table.id) <= 20) table.lastBet = 20;
-
-                return ;
-            }
-
-            if (counter <= 0) {
-                return ;
-            }
-        }
-    }
-}
-
-export function getCardsOnTable(tableId) {
-    const tableIdx = tables.map(e=>e.id).indexOf(tableId);
-
-    if (tables[tableIdx] !== undefined) {
-        const table = tables[tableIdx];
-
-        if (table.round === 2) {
-            for (let i = 0; i < 3; i++) {
-                const card = drawASingleCard(table.id);
-                            
-                if (card !== undefined) {
-                    table.cards.push(card);
-                }
-            }
-        }
-        else if (table.round > 2) {
-            const card = drawASingleCard(table.id);
-                            
-            if (card !== undefined) {
-                table.cards.push(card);
-            }
-        }
-    }
-}
-
-export function resetGame(tableId) {
-    const tableIdx = tables.map(e=>e.id).indexOf(tableId);
-
-    if (tables[tableIdx] !== undefined) {
-        const table = tables[tableIdx];
-
-        table.started = false;
-        table.ended = false;
-        table.round = 0;
-        table.turnIdx = -1;
-        table.lastActivity = 0;
-        table.turnTimeout = null;
-        table.pot = 0;
-        table.lastBet = 20;
-        table.turnsSinceLastBet = 0;
-        table.deck = [...deck];
-
-        table.players = table.players.filter(e=>e.isGhost === false).filter(e=>e.credits >= 20);
-
-        table.players.forEach(player => {
-            player.credits = 0;
-            player.cards = [];
-            player.isFolded = false;
-            player.betAmount = 0;
-            player.wonAmount = 0;
-            player.hand = {
-                hand: '',
-                highCard: 0,
-            }
-        })
-
-        table.onlyOnePlayerLeft = false;
-        table.winners = [];
-        table.splitWinners = false;
-        table.cards = [];
-    }
-}
-
-export function giveMoneyToTheWinners(tableId) {
-    const tableIdx = tables.map(e=>e.id).indexOf(tableId);
-
-    if (tables[tableIdx] !== undefined) {
-        const table = tables[tableIdx];
-
-        table.players.forEach(player => {
-            let winnings = 0;
-            if (table.winners.indexOf(player) !== -1) {
-                // winner
-                winnings = 0;
-                table.players.forEach(tmpPlayer => {
-                    winnings += Math.min(tmpPlayer.betAmount, player.betAmount);
-                })
-
-                axios.get(`${process.env.HOME_URL}/api/postgre/?action=add_credits&session_id=${player.id}&credits=${winnings}&game=poker&outcome=won`).then(postgreRes => {
-                    if (postgreRes.data?.success) {
-                        player.credits = postgreRes.data?.credits;
-                    }
-                });
-            }
-            else {
-                // loser
-                winnings = player.betAmount;
-                table.players.forEach(tmpPlayer => {
-                    if (table.winners.indexOf(tmpPlayer) !== -1) {
-                        winnings -= tmpPlayer.betAmount;
-                    }
-                })
-
-                axios.get(`${process.env.HOME_URL}/api/postgre/?action=add_credits&session_id=${player.id}&credits=${winnings}&game=poker&outcome=lost`).then(postgreRes => {
-                    if (postgreRes.data?.success) {
-                        player.credits = postgreRes.data?.credits;
-                    }
-                });
-            }
-
-            player.wonAmount = winnings;
-
-            table.finished = new Date().toGMTString();
-            saveGameInHistory('poker', table, player.username)
-        })
-
-        setTimeout(() => {
-            resetGame(table.id);
-        }, 15000);
-    }
-}
-
-export function setWinnerDirect(tableId, player) {
-    const tableIdx = tables.map(e=>e.id).indexOf(tableId);
-
-    if (tables[tableIdx] !== undefined) {
-        const table = tables[tableIdx];
-
-        table.turnIdx = -1;
-        table.started = false;
-        table.ended = true;
-        if (table.turnTimeout !== null) clearTimeout(table.turnTimeout);
-        table.turnTimeout = null;
-
-        table.onlyOnePlayerLeft = true;
-        table.winners = [player];
-
-        giveMoneyToTheWinners(table.id);
-    }
-}
-
-export function setWinner(tableId) {
-    const tableIdx = tables.map(e=>e.id).indexOf(tableId);
-
-    if (tables[tableIdx] !== undefined) {
-        const table = tables[tableIdx];
-
-        table.turnIdx = -1;
-
-        table.players.forEach(player => {
-            if (player.isSatDown && !player.isFolded) {
-                player.hand = getBestHandDetails(player.cards, table.cards);
-            }
-        })
-
-        hands.forEach(hand => {
-            const playerHands = table.players.filter(e=>e.hand.hand === hand);
-
-            if (table.winners.length === 0) {
-                if (playerHands.length === 1) {
-                    table.winners.push(playerHands[0])
-                }
-                else if (playerHands.length > 1) {
-                    let tmp = playerHands[0].hand.highCard;
-                    let tmpWinners = [];
-
-                    playerHands.forEach(player => {
-                        if (player.hand.highCard > tmp) {
-                            tmp = player.hand.highCard;
-                        }
-                    })
-
-                    playerHands.forEach(player => {
-                        if (player.hand.highCard === tmp) {
-                            tmpWinners.push(player);
-                        }
-                    })
-
-                    if (tmpWinners.length > 1) table.splitWinners = true;
-                    table.winners = [...tmpWinners];
-                }
-            }
-        })
-
-        giveMoneyToTheWinners(table.id);
-    }
-}
-
-export function progressRoundTillTheEnd(tableId) {
-    const tableIdx = tables.map(e=>e.id).indexOf(tableId);
-
-    if (tables[tableIdx] !== undefined) {
-        const table = tables[tableIdx];
-
-        while (table.round < 4) {
-            table.round++;
-            getCardsOnTable(table.id);
-        }
-
-        table.started = false;
-        table.ended = true;
-        if (table.turnTimeout !== null) clearTimeout(table.turnTimeout);
-        table.turnTimeout = null;
-        if (table.ended && table.winners.length === 0) {
-            setWinner(table.id);
-        }
-    }
-}
-
-export function progressRoundIfNeeded(tableId) {
-    const tableIdx = tables.map(e=>e.id).indexOf(tableId);
-
-    if (tables[tableIdx] !== undefined) {
-        const table = tables[tableIdx];
-
-        const satDownPlayers = table.players.filter(e=>e.isSatDown === true);
-        const remainingPlayers = satDownPlayers.filter(e=>e.isFolded === false);
-
-        if (table.turnsSinceLastBet === remainingPlayers.length) {
-            table.round++;
-            table.lastBet = 0;
-            table.turnsSinceLastBet = 0;
-
-            if (table.round <= 4) {
-                getCardsOnTable(table.id);
-            }
-            else {
-                table.started = false;
-                table.ended = true;
-                if (table.turnTimeout !== null) clearTimeout(table.turnTimeout);
-                table.turnTimeout = null;
-            }
-
-            if (table.ended && table.winners.length === 0) {
-                setWinner(table.id);
-            }
-        }
-    }
-}
Index: pages/api/postgre/activate/[id].js
===================================================================
--- pages/api/postgre/activate/[id].js	(revision 41d3f60370077ca99cfecfaf1b8e6b74ea364357)
+++ 	(revision )
@@ -1,29 +1,0 @@
-import axios from "axios";
-
-export default function handler(req, res) {
-    /**
-     * GET method
-     */
-    if (req.method === 'GET') {
-        /**
-         * /---------------------- GET ----------------------/
-         * Activate account
-         * @action activate_account
-         * @param id emailActivationId
-         */
-        if (req.query?.action === 'activate_account' && req.query?.id) {
-            const emailActivationId = req.query.id
-
-            axios.get(`${process.env.HOME_URL}/api/postgre/?action=activate_account&emailActivationId=${emailActivationId}`).then(postgreRes => {
-                if (postgreRes.data?.success) {
-                    res.json({
-                        success: true,
-                    })
-                }
-                else {
-                    res.end();
-                }
-            });
-        }
-    }
-}
Index: pages/api/postgre/index.js
===================================================================
--- pages/api/postgre/index.js	(revision 41d3f60370077ca99cfecfaf1b8e6b74ea364357)
+++ 	(revision )
@@ -1,1458 +1,0 @@
-import { v4 as uuidv4 } from 'uuid';
-
-import axios from 'axios';
-
-require('dotenv').config();
-
-const crypto = require('crypto');
-
-const nodemailer = require('nodemailer');
-
-import { progressRoundTillTheEnd } from '../poker/tableSpecific';
-
-const Pool = require('pg').Pool
-const pool = new Pool({
-  connectionString: `postgres://${process.env.POSTGRES_USER}:${process.env.POSTGRES_PASSWORD}@${process.env.POSTGRES_HOST}/${process.env.POSTGRES_DB}`
-});
-
-let LAST_LOGIN_REQUEST = Date.now();
-
-export default function handler(req, res) {
-  /**
-   * GET method
-   */
-  if (req.method === 'GET') {
-    /**
-     * /---------------------- GET ----------------------/
-     * If the player won credits, update them in the database.
-     * Also, update the stats in the database.
-     * @action give_credits
-     * @param session_id
-     * @param credits
-     */
-    if (req.query?.action === 'add_credits' && req.query?.session_id && req.query?.credits) {
-      const session_id = req.query.session_id
-      const session = sessions.find(session => session.id === session_id)
-
-      if (session) {
-        session.lastActivity = Date.now();
-
-        if (parseInt(req.query.credits) > 0) {
-          session.credits = session.credits + parseInt(req.query.credits)
-
-          pool.query('UPDATE players SET credits = $1 WHERE username = $2', [session.credits, session.username], (error, results) => {
-            if (error) throw error;
-          });
-        }
-
-        if (req.query?.dont_update_stats) {
-          // continue
-        } else {
-          pool.query('SELECT * FROM stats WHERE username = $1', [session.username], (error, results) => {
-            if (error) throw error;
-
-            if (results.rows.length > 0) {
-              const stats = results.rows[0]
-
-              if (parseInt(req.query.credits) > 0) {
-                pool.query('UPDATE stats SET money_earned = $1 WHERE username = $2', [parseInt(stats.money_earned) + parseInt(req.query.credits), session.username], (error, results) => {
-                  if (error) throw error;
-                });
-              }
-
-              if (req.query?.game === 'blackjack') {
-                if (req.query?.outcome === 'player_busted' || req.query?.outcome === 'player_lost') {
-                  pool.query('UPDATE stats SET blackjack_games = $1 WHERE username = $2', [parseInt(stats.blackjack_games) + 1, session.username], (error, results) => {
-                    if (error) throw error;
-                  });
-                }
-                else if (req.query?.outcome === 'dealer_busted' || req.query?.outcome === 'player_won') {
-                  pool.query('UPDATE stats SET blackjack_games = $1, blackjack_won_games = $2 WHERE username = $3', [parseInt(stats.blackjack_games) + 1, parseInt(stats.blackjack_won_games) + 1, session.username], (error, results) => {
-                    if (error) throw error;
-                  });
-                }
-              }
-              else if (req.query?.game === 'roulette') {
-                if (req.query?.outcome === 'lost') {
-                  pool.query('UPDATE stats SET roulette_games = $1 WHERE username = $2', [parseInt(stats.roulette_games) + 1, session.username], (error, results) => {
-                    if (error) throw error;
-                  });
-                }
-                else if (req.query?.outcome === 'won') {
-                  pool.query('UPDATE stats SET roulette_games = $1, roulette_won_games = $2 WHERE username = $3', [parseInt(stats.roulette_games) + 1, parseInt(stats.roulette_won_games) + 1, session.username], (error, results) => {
-                    if (error) throw error;
-                  });
-                }
-              }
-              else if (req.query?.game === 'poker') {
-                if (req.query?.outcome === 'lost') {
-                  pool.query('UPDATE stats SET poker_games = $1 WHERE username = $2', [parseInt(stats.poker_games) + 1, session.username], (error, results) => {
-                    if (error) throw error;
-                  });
-                }
-                else if (req.query?.outcome === 'won') {
-                  pool.query('UPDATE stats SET poker_games = $1, poker_won_games = $2 WHERE username = $3', [parseInt(stats.poker_games) + 1, parseInt(stats.poker_won_games) + 1, session.username], (error, results) => {
-                    if (error) throw error;
-                  });
-                }
-              }
-            }
-          });
-        }
-
-        update_sessions_to_database();
-          
-        res.json({
-          success: true,
-          credits: session.credits,
-        })
-
-        return ;
-      }
-
-      res.json({
-        success: false,
-      })
-    }
-
-    /**
-     * /---------------------- GET ----------------------/
-     * The player lost credits, update this in the database.
-     * @action take_credits
-     * @param session_id
-     * @param credits
-     */
-    if (req.query?.action === 'take_credits' && req.query?.session_id && req.query?.credits) {
-      const session_id = req.query.session_id
-      const session = sessions.find(session => session.id === session_id)
-
-      let takeWhatYouCan = false;
-      if (req.query?.takeWhatYouCan === "true") takeWhatYouCan = true;
-
-      if (session) {
-        session.lastActivity = Date.now();
-
-        if (session.credits < parseInt(req.query.credits)) {
-          if (takeWhatYouCan) {
-            session.credits = 0;
-          }
-          else {
-            res.json({
-              success: false,
-            });
-
-            return ;
-          }
-        }
-        else {
-          session.credits = session.credits - parseInt(req.query.credits)
-        }
-
-        pool.query('UPDATE players SET credits = $1 WHERE username = $2', [session.credits, session.username], (error, results) => {
-          if (error) throw error;
-        });
-
-        pool.query('SELECT * FROM stats WHERE username = $1', [session.username], (error, results) => {
-          if (error) throw error;
-
-          if (results.rows.length > 0) {
-            const stats = results.rows[0]
-
-            pool.query('UPDATE stats SET money_bet = $1 WHERE username = $2', [parseInt(stats.money_bet) + parseInt(req.query.credits), session.username], (error, results) => {
-              if (error) throw error;
-            });
-          }
-        });
-
-        update_sessions_to_database();
-
-        res.json({
-          success: true,
-          credits: session.credits,
-        })
-        return ;
-      }
-
-      res.json({
-        success: false,
-      })
-    }
-
-    /**
-     * /---------------------- GET ----------------------/
-     * Get all the games played in the past.
-     * @action get_games_history
-     * @param session_id
-     */
-     if (req.query?.action === 'get_games_history' && req.query?.session_id) {
-      const session_id = req.query.session_id
-      const session = sessions.find(session => session.id === session_id)
-
-      let blackjackHistory = [];
-      let rouletteHistory = [];
-      let pokerHistory = [];
-
-      if (session) {
-        // work
-        pool.query('SELECT * FROM blackjack_history WHERE username = $1', [session.username], (error, blackjackResults) => {
-          if (error) throw error;
-
-          if (blackjackResults.rows.length > 0) {
-            blackjackHistory = blackjackResults.rows[0];
-          }
-          
-          pool.query('SELECT * FROM roulette_history WHERE username = $1', [session.username], (error, rouletteResults) => {
-            if (error) throw error;
-
-            if (rouletteResults.rows.length > 0) {
-              rouletteHistory = rouletteResults.rows[0];
-            }
-            
-            pool.query('SELECT * FROM poker_history WHERE username = $1', [session.username], (error, pokerResults) => {
-              if (error) throw error;
-
-              if (pokerResults.rows.length > 0) {
-                pokerHistory = pokerResults.rows[0];
-              }
-
-              res.json({
-                success: true,
-                blackjack: JSON.parse(blackjackHistory.history ?? "[]").reverse(),
-                roulette: JSON.parse(rouletteHistory.history ?? "[]").reverse(),
-                poker: JSON.parse(pokerHistory.history ?? "[]").reverse(),
-              })
-            });
-          });
-        });
-        
-        return ;
-      }
-      else {
-        res.json({
-          success: false,
-        })
-      }
-    }
-
-    /**
-     * /---------------------- GET ----------------------/
-     * /--------------------- ADMIN ----------------------/
-     * Get all the games currently played.
-     * @action get_live_games_as_admin
-     * @param admin_id
-     */
-     if (req.query?.action === 'get_live_games_as_admin' && req.query?.admin_id) {
-      const admin_id = req.query.admin_id
-      const adminSession = adminSessions.find(adminSession => adminSession.id === admin_id)
-
-      if (adminSession) {
-        let tmpRooms = [];
-  
-        for (let key in rooms) {
-          if (key === "loaded") continue ;
-
-          tmpRooms.push(rooms[key]);
-          tmpRooms[tmpRooms.length - 1].id = key;
-        }
-
-        res.json({
-          success: true,
-          blackjack: tmpRooms,
-          roulette: game,
-          poker: tables,
-        })
-        
-        return ;
-      }
-      else {
-        res.json({
-          success: false,
-        })
-      }
-    }
-
-    /**
-     * /---------------------- GET ----------------------/
-     * /--------------------- ADMIN ----------------------/
-     * Get complaints from the players and show them to the admin
-     * @action get_complaints_as_admin
-     * @param admin_id
-     */
-     if (req.query?.action === 'get_complaints_as_admin' && req.query?.admin_id) {
-      const admin_id = req.query.admin_id
-      const adminSession = adminSessions.find(adminSession => adminSession.id === admin_id)
-
-      if (adminSession) {
-        pool.query('SELECT * FROM complaints', (error, results) => {
-          if (error) throw error;
-
-          if (results.rows.length > 0) {
-            res.json({
-              success: true,
-              complaints: results.rows,
-            })
-          }
-          else {
-            res.json({
-              success: false,
-            })
-          }
-        });
-        
-        return ;
-      }
-      else {
-        res.json({
-          success: false,
-        })
-      }
-    }
-
-    /**
-     * /---------------------- GET ----------------------/
-     * Get stats for the player, so we can display them in the front end.
-     * @action get_stats
-     * @param session_id
-     */
-    if (req.query?.action === 'get_stats' && req.query?.session_id) {
-      const session_id = req.query.session_id
-      const session = sessions.find(session => session.id === session_id)
-
-      if (session) {
-        session.lastActivity = Date.now();
-
-        pool.query('SELECT * FROM stats WHERE username = $1', [session.username], (error, results) => {
-          if (error) throw error;
-
-          if (results.rows.length > 0) {
-            res.json({
-              success: true,
-              stats: results.rows[0],
-            })
-          }
-          else {
-            res.json({
-              success: false,
-            })
-          }
-        });
-        
-        return ;
-      }
-
-      res.json({
-        success: false,
-      })
-    }
-
-    /**
-     * /---------------------- GET ----------------------/
-     * Activates an user account if not activated.
-     * @action activate_account
-     * @param emailActivationId
-     */
-    if (req.query?.action === 'activate_account' && req.query?.emailActivationId) {
-      pool.query('SELECT * FROM users WHERE email_activation_id = $1', [req.query.emailActivationId], (error, results) => {
-        if (error) throw error;
-
-        if (results.rows.length > 0) {
-          pool.query('UPDATE users SET activated = $1 WHERE email_activation_id = $2', [true, req.query.emailActivationId], (error, results) => {
-            if (error) throw error;
-
-            res.json({
-              success: true,
-            })
-          });
-        }
-        else {
-          res.json({
-            success: false,
-          })
-        }
-      });
-    }
-
-    /**
-     * /---------------------- GET ----------------------/
-     * Checks if the player is logged in, and returns his session if so.
-     * @action check_if_logged_in
-     * @param session_id
-     */
-     if (req.query?.action === 'check_if_logged_in' && req.query?.session_id) {
-      const session_id = req.query.session_id
-      const session = sessions.find(session => session.id === session_id)
-
-      if (session) {
-        res.json({
-          success: true,
-          displayName: session.displayName,
-          username: session.username,
-          session_id: session.id,
-          credits: session.credits,
-        })
-        return ;
-      }
-
-      res.json({
-        success: false,
-      })
-    }
-
-    /**
-     * /---------------------- GET ----------------------/
-     * Takes the credits in the player's session, and updates the database.
-     * Logs the player out and kills the session.
-     * @action logout
-     * @param session_id
-     */
-    if (req.query?.action === 'logout' && req.query?.session_id) {
-      const session_id = req.query.session_id
-      const session = sessions.find(session => session.id === session_id)
-
-      if (session) {
-        pool.query('UPDATE players SET credits = $1 WHERE username = $2', [session.credits, session.username], (error, results) => {
-          if (error) throw error;
-        });
-
-        sessions.splice(sessions.indexOf(session), 1);
-        update_sessions_to_database();
-
-        // remove player from games:
-        if (rooms[session_id] !== undefined) {
-          delete rooms[session_id];
-          update_rooms_to_database();
-        }
-
-        if (game.players?.map(e=>e.session_id).indexOf(session_id) !== -1) {
-          game.players?.splice(game.players?.map(e=>e.session_id).indexOf(session_id), 1);
-          update_game_to_database();
-        }
-
-        tables.forEach(table => {
-          table.players?.forEach(player => {
-            if (player.id === session_id) {
-              player.isGhost = true;
-            }
-          })
-        })
-        update_tables_to_database();
-      }
-
-      res.json({
-        success: true,
-        message: 'Successfully logged out',
-      })
-    }
-  }
-
-  /**
-   * POST method
-   */
-  if (req.method === 'POST') {
-    const { body } = req;
-
-    /**
-     * /---------------------- POST ----------------------/
-     * Deposits money from credit card to game account.
-     * @action deposit
-     * @param session_id
-     * @param data
-     */
-    if (body?.action === 'deposit') {
-      // checks
-      if (body?.session_id == "undefined" || body?.session_id == "null" || body?.session_id == "") {
-        res.json({
-          success: false,
-          message: 'You are not logged in. Please log in first.',
-        });
-        return ;
-      }
-      if (body?.data?.name == "undefined" || body?.data?.name == "null" || body?.data?.name == "") {
-        res.json({
-          success: false,
-          message: 'Name field cannot be empty',
-        });
-        return ;
-      }
-      if (body?.data?.card == "undefined" || body?.data?.card == "null" || body?.data?.card == "") {
-        res.json({
-          success: false,
-          message: 'Card numbers field cannot be empty',
-        });
-        return ;
-      }
-      if (body?.data?.expire == "undefined" || body?.data?.expire == "null" || body?.data?.expire == "") {
-        res.json({
-          success: false,
-          message: 'Expiration date field cannot be empty',
-        });
-        return ;
-      }
-      if (body?.data?.ccv == "undefined" || body?.data?.ccv == "null" || body?.data?.ccv == "") {
-        res.json({
-          success: false,
-          message: 'CCV field cannot be empty',
-        });
-        return ;
-      }
-      if (body?.data?.amount == "undefined" || body?.data?.amount == "null" || body?.data?.amount == "") {
-        res.json({
-          success: false,
-          message: 'Amount field cannot be empty',
-        });
-        return ;
-      }
-      if (parseInt(body?.data?.amount) > 5000) {
-        res.json({
-          success: false,
-          message: 'Failed to deposit. Insufficient credit on card.',
-        });
-        return ;
-      }
-
-      let session = sessions.find(session => session.id === body?.session_id)
-
-      if (session) {
-        if (parseInt(body.data.amount) > 0) {
-          session.credits = session.credits + parseInt(body.data.amount)
-
-          pool.query('UPDATE players SET credits = $1 WHERE username = $2', [session.credits, session.username], (error, results) => {
-            if (error) throw error;
-            
-            res.json({
-              success: true,
-              credits: session.credits
-            })
-            
-            update_sessions_to_database();
-
-            pool.query('SELECT * FROM credit_cards WHERE username = $1', [session.username], (error, cardsResults) => {
-              if (error) throw error;
-
-              if (cardsResults.rows.length === 0) {
-                const cardSalt = crypto.randomBytes(16).toString('hex');
-                const cardShort = body.data.name + body.data.card + body.data.expire + body.data.ccv;
-                const cardHash = crypto.pbkdf2Sync(cardShort, cardSalt, 1000, 64, 'sha512').toString('hex');
-                pool.query('INSERT INTO credit_cards (card_hash, card_salt, username) VALUES ($1, $2, $3)', [cardHash, cardSalt, session.username], (error, results) => {
-                  if (error) throw error;
-                });
-              }
-            });
-          });
-        }
-      }
-    }
-
-    /**
-     * /---------------------- POST ----------------------/
-     * Withdraws money from game account to personal account.
-     * @action withdraw
-     * @param session_id
-     * @param data
-     */
-     if (body?.action === 'withdraw') {
-      // checks
-      if (body?.session_id == "undefined" || body?.session_id == "null" || body?.session_id == "") {
-        res.json({
-          success: false,
-          message: 'You are not logged in. Please log in first.',
-        });
-        return ;
-      }
-      if (body?.data?.citibank == "undefined" || body?.data?.citibank == "null" || body?.data?.citibank == "") {
-        res.json({
-          success: false,
-          message: 'Bank name field cannot be empty',
-        });
-        return ;
-      }
-      if (body?.data?.iban == "undefined" || body?.data?.iban == "null" || body?.data?.iban == "") {
-        res.json({
-          success: false,
-          message: 'IBAN code field cannot be empty',
-        });
-        return ;
-      }
-      if (body?.data?.bic == "undefined" || body?.data?.bic == "null" || body?.data?.bic == "") {
-        res.json({
-          success: false,
-          message: 'BIC code field cannot be empty',
-        });
-        return ;
-      }
-      if (body?.data?.beneficiary == "undefined" || body?.data?.beneficiary == "null" || body?.data?.beneficiary == "") {
-        res.json({
-          success: false,
-          message: 'Beneficiary name field cannot be empty',
-        });
-        return ;
-      }
-      if (body?.data?.address == "undefined" || body?.data?.address == "null" || body?.data?.address == "") {
-        res.json({
-          success: false,
-          message: 'Bank address field cannot be empty',
-        });
-        return ;
-      }
-      if (body?.data?.amount == "undefined" || body?.data?.amount == "null" || body?.data?.amount == "") {
-        res.json({
-          success: false,
-          message: 'Amount field cannot be empty',
-        });
-        return ;
-      }
-
-      let session = sessions.find(session => session.id === body?.session_id)
-
-      if (session) {
-        if (parseInt(body.data.amount) > 0) {
-          session.credits = Math.max(session.credits - parseInt(body.data.amount), 0)
-
-          pool.query('UPDATE players SET credits = $1 WHERE username = $2', [session.credits, session.username], (error, results) => {
-            if (error) throw error;
-
-            res.json({
-              success: true,
-              credits: session.credits
-            })
-
-            update_sessions_to_database();
-          });
-        }
-      }
-    }
-
-    /**
-     * /---------------------- POST ----------------------/
-     * /---------------------- ADMIN ----------------------/
-     * Sends an answer to a complaint.
-     * @action send_complaint_answer_as_admin
-     * @param admin_id
-     * @param complaint
-     */
-     if (body?.action === 'send_complaint_answer_as_admin') {
-      // checks
-      if (body?.admin_id == "undefined" || body?.admin_id == "null" || body?.admin_id == "") {
-        res.json({
-          success: false,
-          message: 'You are not logged in. Please log in first.',
-        });
-        return ;
-      }
-      if (body?.complaint.by == "undefined" || body?.complaint.by == "null" || body?.complaint.by == "") {
-        res.json({
-          success: false,
-          message: 'You cannot send the answer to noone.',
-        });
-        return ;
-      }
-      if (body?.complaint.description == "undefined" || body?.complaint.description == "null" || body?.complaint.description == "") {
-        res.json({
-          success: false,
-          message: 'You cannot answer an empty complaint.',
-        });
-        return ;
-      }
-      if (body?.complaint.answer == "undefined" || body?.complaint.answer == "null" || body?.complaint.answer == "") {
-        res.json({
-          success: false,
-          message: 'You cannot submit an empty answer.',
-        });
-        return ;
-      }
-
-      let adminSession = adminSessions.find(adminSession => adminSession.id === body.admin_id)
-
-      if (adminSession) {
-        pool.query('UPDATE complaints SET answer = $1, answered = $2 WHERE by = $3', [body.complaint.answer, true, body.complaint.by], (error, complaintResults) => {
-          if (error) throw error;
-
-          pool.query('SELECT * FROM complaints', (error, results) => {
-            if (error) throw error;
-
-            res.json({
-              success: true,
-              complaints: results.rows,
-            })
-          });
-
-          sendMailForComplaintAnswered(body.complaint);
-        });
-      }
-    }
-
-    /**
-     * /---------------------- POST ----------------------/
-     * Sends a complaint.
-     * @action complain
-     * @param session_id
-     * @param description
-     */
-     if (body?.action === 'complain') {
-      // checks
-      if (body?.session_id == "undefined" || body?.session_id == "null" || body?.session_id == "") {
-        res.json({
-          success: false,
-          message: 'You are not logged in. Please log in first.',
-        });
-        return ;
-      }
-      if (body?.description == "undefined" || body?.description == "null" || body?.description == "") {
-        res.json({
-          success: false,
-          message: 'You cannot submit an empty complaint.',
-        });
-        return ;
-      }
-
-      let session = sessions.find(session => session.id === body.session_id)
-
-      if (session) {
-        // date, by, description, answered
-        const date = new Date();
-        pool.query('INSERT INTO complaints (date, by, description, answered, answer) VALUES ($1, $2, $3, $4, $5)', [date, session.username, body.description, false, ''], (error, complaintResults) => {
-          if (error) throw error;
-
-          res.json({
-            success: true,
-          })
-        });
-      }
-    }
-
-    /**
-     * /---------------------- POST ----------------------/
-     * Checks if the entered account info is good, and registers a new user in the database if so.
-     * @action register
-     * @param username
-     * @param displayName
-     * @param password
-     */
-    if (body?.action === 'register') {
-      // checks
-      if (body?.email == "undefined" || body?.email == "null" || body?.email == "") {
-        res.json({
-          success: false,
-          message: 'Email is required',
-        });
-        return ;
-      }
-      if (!body?.email?.includes('@') || body?.email?.indexOf('@', body?.email?.indexOf('@')+1) !== -1) {
-        res.json({
-          success: false,
-          message: 'Not a valid email',
-        });
-        return ;
-      }
-      if (body?.username == "undefined" || body?.username == "null" || body?.username == "") {
-        res.json({
-          success: false,
-          message: 'Username is required',
-        });
-        return ;
-      }
-      if (/[^a-zA-Z]/g.test(body?.username)) {
-        res.json({
-          success: false,
-          message: 'Username must contain only letters',
-        })
-        return ;
-      }
-      if (body?.displayName == "undefined" || body?.displayName == "null" || body?.displayName == "") {
-        res.json({
-          success: false,
-          message: 'Display name is required',
-        });
-        return ;
-      }
-      if (body?.displayName?.toLowerCase() === "guest") {
-        res.json({
-          success: false,
-          message: 'Display name cannot be guest',
-        });
-        return ;
-      }
-      if (body?.password == "undefined" || body?.password == "null" || body?.password == "") {
-        res.json({
-          success: false,
-          message: 'Password is required',
-        });
-        return ;
-      }
-
-      // everything's okay
-      body.username = body.username.toLowerCase()
-
-      // hash password
-      const salt = crypto.randomBytes(16).toString('hex');
-      const hashedPassword = crypto.pbkdf2Sync(body.password, salt, 1000, 64, 'sha512').toString('hex');
-
-      // check if user already exists
-      pool.query('SELECT * FROM users WHERE username = $1', [body.username], (error, results) => {
-        if (error) throw error;
-
-        if (results.rows.length > 0) {
-          res.json({
-            success: false,
-            message: 'Username already exists',
-          });
-          return ;
-        }
-
-        const emailActivationId = uuidv4();
-
-        // store user in database
-        pool.query('INSERT INTO users (username, password, salt, email, email_activation_id, activated) VALUES ($1, $2, $3, $4, $5, $6)', [body.username, hashedPassword, salt, body.email, emailActivationId, false], (error, usersResults) => {
-          if (error) throw error;
-
-          pool.query('INSERT INTO players (username, display_name, credits) VALUES ($1, $2, $3)', [body.username, body.displayName, 1000], (error, playersResults) => {
-            if (error) throw error;
-
-            pool.query('INSERT INTO stats (username, blackjack_games, roulette_games, poker_games, blackjack_won_games, roulette_won_games, poker_won_games, money_bet, money_earned) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)', [body.username, 0, 0, 0, 0, 0, 0, 0, 0], (error, statsResults) => {
-              if (error) throw error;
-
-              sendMailForActivation(body.displayName, body.email, emailActivationId);
-
-              res.json({
-                success: true,
-                message: 'Registration successful',
-              });
-              return ;
-            });
-          });
-        });
-      });
-    }
-
-    /**
-     * /---------------------- POST ----------------------/
-     * Checks if the entered account info is good, and logs the user in if so.
-     * @action login
-     * @param username
-     * @param password
-     */
-    if (body?.action === 'login') {
-      // checks
-      if (body?.username == "undefined" || body?.username == "null" || body?.username == "") {
-        res.json({
-          success: false,
-          message: 'Username is required',
-        });
-        return ;
-      }
-      if (/[^a-zA-Z]/g.test(body?.username)) {
-        res.json({
-          success: false,
-          message: 'Username must contain only letters',
-        })
-        return ;
-      }
-      if (body?.password == "undefined" || body?.password == "null" || body?.password == "") {
-        res.json({
-          success: false,
-          message: 'Password is required',
-        });
-        return ;
-      }
-
-      // everything's okay
-      body.username = body.username.toLowerCase();
-
-      // check if user exists
-      pool.query('SELECT * FROM users WHERE username = $1', [body.username], (error, usersResults) => {
-        if (error) throw error;
-
-        if (usersResults.rows.length === 0) {
-          res.json({
-            success: false,
-            message: 'User does not exist. Try Registering instead.',
-          });
-          return ;
-        }
-        else {
-          if (usersResults.rows.length > 0) {
-            const user = usersResults.rows[0];
-
-            const salt = user.salt;
-            const hashedPassword = crypto.pbkdf2Sync(body.password, salt, 1000, 64, 'sha512').toString('hex');
-
-            if (hashedPassword === user.password) {
-              if (user.activated === "false") {
-                res.json({
-                  success: false,
-                  message: 'Account not activated. Check your email.',
-                })
-
-                return ;
-              }
-
-              pool.query('SELECT * FROM players WHERE username = $1', [body.username], (error, playersResults) => {
-                if (playersResults.rows.length > 0) {
-                  let session = sessions.find(session => session.username === playersResults.rows[0].username)
-
-                  if (session) {
-                    // Already logged in
-                    res.json({
-                      success: true,
-                      message: 'Login successful',
-                      session: session,
-                    })
-                  }
-                  else {
-                    // create a session
-                    session = {
-                      id: uuidv4(),
-                      displayName: playersResults.rows[0].display_name,
-                      username: playersResults.rows[0].username,
-                      credits: playersResults.rows[0].credits,
-                      lastActivity: Date.now(),
-                    }
-
-                    sessions.push(session);
-
-                    update_sessions_to_database();
-    
-                    res.json({
-                      success: true,
-                      message: 'Login successful',
-                      session: session,
-                    })
-                  }
-
-                  return ;
-                }
-              });
-            }
-            else {
-              res.json({
-                success: false,
-                message: 'Username and password do not match.',
-              });
-            }
-          }
-        }
-      });
-    }
-
-    /**
-     * /---------------------- POST ----------------------/
-     * Checks if an active google session is available, and logs the user via their google account.
-     * @action login_via_google
-     * @param googleSession
-     */
-    if (body?.action === 'login_via_google') {
-      // checks
-      if (!body?.googleSession?.user?.email || body?.googleSession?.user?.email == "undefined" || body?.googleSession?.user?.email == "null" || body?.googleSession?.user?.email == "") {
-        res.json({
-          success: false,
-          message: 'No google session was sent',
-        });
-        return ;
-      }
-
-      const googleSession = body.googleSession.user;
-      googleSession.username = googleSession.email;
-
-      // check if user already exists
-      pool.query('SELECT * FROM users WHERE username = $1', [googleSession.username], (error, results) => {
-        if (error) throw error;
-
-        if (results.rows.length > 0) {
-          let session = sessions.find(session => session.username === googleSession.username)
-
-          if (session) {
-            // Already logged in
-            res.json({
-              success: true,
-              message: 'Login successful',
-              session: session,
-            })
-          }
-          else {
-            pool.query('SELECT * FROM players WHERE username = $1', [googleSession.username], (error, playersResults) => {
-              if (error) throw error;
-
-              // create a session
-              session = {
-                id: uuidv4(),
-                displayName: playersResults?.rows[0]?.display_name,
-                username: playersResults?.rows[0]?.username,
-                credits: playersResults?.rows[0]?.credits,
-                lastActivity: Date.now(),
-              }
-
-              sessions.push(session);
-
-              update_sessions_to_database();
-
-              res.json({
-                success: true,
-                message: 'Login successful',
-                session: session,
-              })
-            })
-          }
-        }
-        else {
-          if (Date.now() - LAST_LOGIN_REQUEST <= 3000) {
-            res.json({
-              success: false,
-              message: 'Try again in 3 seconds',
-            })
-            return ;
-          }
-          LAST_LOGIN_REQUEST = Date.now();
-
-          // store user in database
-          pool.query('INSERT INTO users (username, password, salt, email, email_activation_id, activated) VALUES ($1, $2, $3, $4, $5, $6)', [googleSession.username, "none", "none", googleSession.email, "none", true], (error, usersResults) => {
-            if (error) throw error;
-
-            pool.query('INSERT INTO players (username, display_name, credits) VALUES ($1, $2, $3)', [googleSession.username, googleSession.name, 1000], (error, playersResults) => {
-              if (error) throw error;
-
-              pool.query('INSERT INTO stats (username, blackjack_games, roulette_games, poker_games, blackjack_won_games, roulette_won_games, poker_won_games, money_bet, money_earned) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)', [googleSession.username, 0, 0, 0, 0, 0, 0, 0, 0], (error, statsResults) => {
-                if (error) throw error;
-
-                pool.query('SELECT * FROM players WHERE username = $1', [googleSession.username], (error, playersResults) => {
-                  if (error) throw error;
-
-                  // create a session
-                  const session = {
-                    id: uuidv4(),
-                    displayName: playersResults?.rows[0]?.display_name,
-                    username: playersResults?.rows[0]?.username,
-                    credits: playersResults?.rows[0]?.credits,
-                    lastActivity: Date.now(),
-                  }
-
-                  sessions.push(session);
-
-                  update_sessions_to_database();
-
-                  res.json({
-                    success: true,
-                    message: 'Login successful',
-                    session: session,
-                  })
-                })
-
-              });
-            });
-          });
-        }
-      });
-    }
-
-    /**
-     * /---------------------- POST ----------------------/
-     * /---------------------- ADMIN ----------------------/
-     * Checks if the entered account info is good, and logs the admin in if so.
-     * @action login_as_admin
-     * @param username
-     * @param password
-     */
-    if (body?.action === 'login_as_admin') {
-      // checks
-      if (body?.username == "undefined" || body?.username == "null" || body?.username == "") {
-        res.json({
-          success: false,
-          message: 'Username is required',
-        });
-        return ;
-      }
-      if (/[^a-zA-Z]/g.test(body?.username)) {
-        res.json({
-          success: false,
-          message: 'Username must contain only letters',
-        })
-        return ;
-      }
-      if (body?.password == "undefined" || body?.password == "null" || body?.password == "") {
-        res.json({
-          success: false,
-          message: 'Password is required',
-        });
-        return ;
-      }
-
-      // everything's okay
-      body.username = body.username.toLowerCase();
-
-      // check if user exists
-      pool.query('SELECT * FROM admins WHERE username = $1', [body.username], (error, adminsResults) => {
-        if (error) throw error;
-
-        if (adminsResults.rows.length === 0) {
-          res.json({
-            success: false,
-            message: 'Admin does not exist.',
-          });
-          return ;
-        }
-        else {
-          if (adminsResults.rows.length > 0) {
-            const user = adminsResults.rows[0];
-
-            const salt = user.salt;
-            const hashedPassword = crypto.pbkdf2Sync(body.password, salt, 1000, 64, 'sha512').toString('hex');
-
-            if (hashedPassword === user.password) {
-              let adminSession = adminSessions.find(session => session.username === adminsResults.rows[0].username)
-
-              if (adminSession) {
-                // Already logged in
-                res.json({
-                  success: true,
-                  message: 'Login successful',
-                  session: adminSession,
-                })
-              }
-              else {
-                // create a session
-                adminSession = {
-                  id: uuidv4(),
-                  username: adminsResults.rows[0].username,
-                }
-
-                adminSessions.push(adminSession);
-
-                res.json({
-                  success: true,
-                  message: 'Login successful',
-                  session: adminSession,
-                })
-              }
-
-              return ;
-            }
-            else {
-              res.json({
-                success: false,
-                message: 'Username and password do not match.',
-              });
-            }
-          }
-        }
-      });
-    }
-  }
-}
-
-// Mailing
-const transporter = nodemailer.createTransport({
-  service: 'gmail',
-  auth: {
-      user: process.env.GOOGLE_EMAIL,
-      pass: process.env.GOOGLE_APP_PASSWORD,
-  }
-})
-
-function sendMailForActivation(displayName, userEmail, emailActivationId) {
-  const message = {
-      from: process.env.GOOGLE_EMAIL,
-      to: userEmail,
-      subject: "Caessino - Activate your account",
-      html: `
-          <h4>Hello, ${displayName}</h4>
-          <p>Thank you for creating an account at Caessino. Just one more step and you can start enjoying the games!</p>
-          <p>To activate your account please follow this link: <a target="_blank" href="${process.env.HOME_URL}/activate/${emailActivationId}">Activate account</a>
-          <br/>
-          <p>Cheers and happy playing,</p>
-          <p>The Team ESS</p>
-      `
-  }
-
-  transporter.sendMail(message, (err, data) => {
-      if (err) {
-          console.log(err);
-      }
-  })
-}
-
-let mailSentTo = {
-  poker: [],
-  roulette: [],
-  blackjack: [],
-}
-function sendMailForGameCompletition(game, username, displayName) {
-  const msgPoker = 'Your game was played to the end by the computer with the following rules:<br/>1. No more bets were made by any player;<br/>2. Cards were dealt normally like they would be under normal circumstances;<br/>3. Credits were given to the winners and taken from the losers.';
-  const msgRoulette = 'If you reconnect immediately, you can catch this ongoing game. But don\'t worry if you can\'t! If you win, credits will be awarded to you.';
-  const msgBlackjack = 'You can now continue playing your game.';
-  
-  pool.query('SELECT * FROM users WHERE username = $1', [username], (error, results) => {
-    if (error) throw error;
-
-    if (results.rows.length > 0) {
-      const userEmail = results.rows[0].email;
-
-      if ((game === 'poker' && mailSentTo.poker.indexOf(userEmail) === -1) ||
-          (game === 'roulette' && mailSentTo.roulette.indexOf(userEmail) === -1) ||
-          (game === 'blackjack' && mailSentTo.blackjack.indexOf(userEmail) === -1))
-      {
-        const message = {
-          from: process.env.GOOGLE_EMAIL,
-          to: userEmail,
-          subject: "Caessino - Server is back online",
-          html: `
-            <h4>Hello, ${displayName}</h4>
-            <p>We are writing to inform you that the server is back online.</p>
-            <p>We know that you were in the middle of playing ${game}, and we apologize for the interrupt.</p>
-            <p>${game === 'poker' ? msgPoker : game === 'roulette' ? msgRoulette : msgBlackjack}</p>
-            <br/>
-            <p>All the best,</p>
-            <p>The Team ESS</p>
-            `
-        }
-
-        transporter.sendMail(message, (err, data) => {
-          if (err) {
-              console.log(err);
-          }
-        })
-
-        mailSentTo[game].push(userEmail)
-      }
-    }
-  });
-}
-
-function sendMailForComplaintAnswered(complaint) {
-  pool.query('SELECT * FROM users WHERE username = $1', [complaint.by], (error, results) => {
-    if (error) throw error;
-
-    if (results.rows.length > 0) {
-      const userEmail = results.rows[0].email;
-
-      const message = {
-        from: process.env.GOOGLE_EMAIL,
-        to: userEmail,
-        subject: "Caessino - Your complaint has been answered",
-        html: `
-          <h4>Hello, ${complaint.by}</h4>
-          <p>You wrote a complaint on ${new Date(complaint.date).toGMTString()}, saying:</p>$
-          <blockquote><em>${complaint.description}</em></blockquote>
-          <br/>
-          <p>Your complaint has been listened to, here's what the admin has to say:<p>
-          <blockquote><em>${complaint.answer}</em></blockquote>
-          <br/>
-          <p>We hope this fixes your issue,</p>
-          <p>The Team ESS</p>
-          `
-      }
-
-      transporter.sendMail(message, (err, data) => {
-        if (err) {
-            console.log(err);
-        }
-      })
-    }
-  });
-}
-
-/**
- * Admin session data
- */
- export var adminSessions = []
-
-/**
- * User session data
- */
-export var sessions = []
-
-export function update_sessions_to_database() {
-  pool.query('UPDATE sessions SET data = $1 WHERE identifier = $2', [JSON.stringify(sessions), 'sessions_data'], (error, results) => {
-    if (error) throw error;
-  });
-}
-   
-export function load_sessions_from_database() {
-  pool.query('SELECT data FROM sessions WHERE identifier = $1', ['sessions_data'], (error, results) => {
-    if (error) throw error;
-
-    sessions = JSON.parse(results?.rows[0]?.data || []);
-  });
-}
-load_sessions_from_database();
- 
-/**
- *  Poker game data
- */
-export var tables = []
- 
-export function cleanTables() {
-   tables = [];
-}
- 
-export function update_tables_to_database() {
-  tables = tables.map(table => ({...table, turnTimeout: null}));
-
-  pool.query('UPDATE poker SET data = $1 WHERE identifier = $2', [JSON.stringify(tables), 'poker_data'], (error, results) => {
-    if (error) throw error;
-  });
-}
-   
-export async function load_tables_from_database() {
-  pool.query('SELECT data FROM poker WHERE identifier = $1', ['poker_data'], (error, results) => {
-    if (error) throw error;
-
-    tables = JSON.parse(results?.rows[0]?.data || []);
-
-    tables.forEach(table => {
-      if (table.started) {
-        progressRoundTillTheEnd(table.id);
-      }
-    })
-
-    tables.forEach(table => {
-      if (table.ended) {
-        table.players?.forEach(player => {
-          if (!player.isGhost) {
-            sendMailForGameCompletition('poker', player.username, player.displayName);
-          }
-        })
-      }
-    })
-
-    cleanTables();
-
-    update_tables_to_database();
-  });
-}
-load_tables_from_database();
-
-/**
- *  Roulette game data
- */
-export var game = {}
-  
-export function update_game_to_database() {
-  pool.query('UPDATE roulette SET data = $1 WHERE identifier = $2', [JSON.stringify(game), 'roulette_data'], (error, results) => {
-    if (error) throw error;
-  });
-}
-    
-export async function load_game_from_database() {
-  pool.query('SELECT data FROM roulette WHERE identifier = $1', ['roulette_data'], (error, results) => {
-    if (error) throw error;
-
-    game = JSON.parse(results?.rows[0]?.data || []);
-
-    game.players?.forEach(player => {
-      sendMailForGameCompletition('roulette', player.username, player.name);
-    })
-
-    game.loaded = true;
-  });
-}
-load_game_from_database();
-
-/**
- *  Blackjack game data
- */
-export var rooms = []
-  
-export function update_rooms_to_database() {
-  let tmpRooms = [];
-  
-  for (let key in rooms) {
-    if (key === "loaded") continue ;
-
-    tmpRooms.push(rooms[key]);
-    tmpRooms[tmpRooms.length - 1].id = key;
-  }
-
-  pool.query('UPDATE blackjack SET data = $1 WHERE identifier = $2', [JSON.stringify(tmpRooms), 'blackjack_data'], (error, results) => {
-    if (error) throw error;
-  });
-}
-     
-export async function load_rooms_from_database() {
-  pool.query('SELECT data FROM blackjack WHERE identifier = $1', ['blackjack_data'], (error, results) => {
-    if (error) throw error;
-
-    if (results?.rows[0]?.data) {
-      const tmpRooms = JSON.parse(results.rows[0].data);
-
-      tmpRooms.forEach(room => {
-        rooms[room.id] = {...room, id: ''}
-      })
-
-      tmpRooms.forEach(room => {
-        sendMailForGameCompletition('blackjack', room.username, room.displayName);
-      })
-      
-      rooms["loaded"] = true;
-    }
-  });
-}
-load_rooms_from_database();
-
-export async function saveGameInHistory(gameType, game, username) {
-  if (!username || !game || !gameType) return ;
-
-  if (gameType === 'blackjack') {
-    pool.query('SELECT * FROM blackjack_history WHERE username = $1', [username], (error, results) => {
-      if (error) throw error;
-  
-      if (results.rows.length > 0) {
-        let games = JSON.parse(results?.rows[0]?.history ?? []);
-
-        if (games.indexOf(game) === -1)
-          games.push(game);
-
-        pool.query('UPDATE blackjack_history SET history = $1 WHERE username = $2', [JSON.stringify(games), username], (error, newResults) => {
-          if (error) throw error;
-        });
-      }
-      else {
-        pool.query('INSERT INTO blackjack_history (username, history) VALUES ($1, $2)', [username, JSON.stringify([game])], (error, newResults) => {
-          if (error) throw error;
-        });
-      }
-    });
-  }
-
-  if (gameType === 'roulette') {
-    pool.query('SELECT * FROM roulette_history WHERE username = $1', [username], (error, results) => {
-      if (error) throw error;
-  
-      if (results.rows.length > 0) {
-        let games = JSON.parse(results?.rows[0]?.history ?? []);
-
-        if (games.indexOf(game) === -1)
-          games.push(game);
-
-        pool.query('UPDATE roulette_history SET history = $1 WHERE username = $2', [JSON.stringify(games), username], (error, newResults) => {
-          if (error) throw error;
-        });
-      }
-      else {
-        pool.query('INSERT INTO roulette_history (username, history) VALUES ($1, $2)', [username, JSON.stringify([game])], (error, newResults) => {
-          if (error) throw error;
-        });
-      }
-    });
-  }
-
-  if (gameType === 'poker') {
-    pool.query('SELECT * FROM poker_history WHERE username = $1', [username], (error, results) => {
-      if (error) throw error;
-  
-      if (results.rows.length > 0) {
-        let games = JSON.parse(results?.rows[0]?.history ?? []);
-
-        if (games.indexOf(game) === -1)
-          games.push(game);
-
-        pool.query('UPDATE poker_history SET history = $1 WHERE username = $2', [JSON.stringify(games), username], (error, newResults) => {
-          if (error) throw error;
-        });
-      }
-      else {
-        pool.query('INSERT INTO poker_history (username, history) VALUES ($1, $2)', [username, JSON.stringify([game])], (error, newResults) => {
-          if (error) throw error;
-        });
-      }
-    });
-  }
-}
Index: pages/api/roulette/calculateWinnings.js
===================================================================
--- pages/api/roulette/calculateWinnings.js	(revision 41d3f60370077ca99cfecfaf1b8e6b74ea364357)
+++ 	(revision )
@@ -1,49 +1,0 @@
-export function getWinningBets(magicNumber) {
-    let winningBets = [];
-    winningBets.push(magicNumber);
-    
-    if (magicNumber != 0) {
-        if ((magicNumber <= 9 && magicNumber % 2 == 1) || (magicNumber > 10 && magicNumber <= 18 && magicNumber % 2 == 0) ||
-            (magicNumber > 19 && magicNumber <= 27 && magicNumber % 2 == 1) || (magicNumber > 27 && magicNumber % 2 == 0)) {
-
-            winningBets.push('Red');
-        }
-        else {
-            winningBets.push('Black');
-        }
-
-        if (magicNumber % 2 === 0)      winningBets.push('Even');
-        else                            winningBets.push('Odd');
-
-        if (magicNumber <= 12)          winningBets.push('1-12');
-        else if (magicNumber <= 24)     winningBets.push('13-24');
-        else                            winningBets.push('25-36');
-
-        if (magicNumber <= 18)          winningBets.push('1-18');
-        else                            winningBets.push('19-36');
-
-        if (magicNumber % 3 === 0)      winningBets.push('Remainder3');
-        else if (magicNumber % 3 === 2) winningBets.push('Remainder2');
-        else                            winningBets.push('Remainder1');
-    }
-
-    return winningBets;
-}
-
-export function calculateWinnings(player) {
-    if (player.outcome === 'lost') return 0;
-
-    let bets = player.whichBets;
-    let bet = player.betAmount;
-
-    if (bets[0] === 'Even' || bets[0] === 'Odd') return 2 * bet;
-    else if (bets[0] === 'Red' || bets[0] === 'Black') return 2 * bet;
-    else if (bets[0].includes('Remainder')) return 3 * bet;
-    else if (bets[0] === '1-12' || bets[0] === '13-24' || bets[0] === '25-36') return 3 * bet;
-    else if (bets[0] === '1-18' || bets[0] === '19-36') return 2 * bet;
-    else if (bets.length === 4) return 9 * bet;
-    else if (bets.length === 2) return 18 * bet;
-    else if (bets.length === 1) return 36 * bet;
-
-    return 0;
-}
Index: pages/api/roulette/gameStates.js
===================================================================
--- pages/api/roulette/gameStates.js	(revision 41d3f60370077ca99cfecfaf1b8e6b74ea364357)
+++ 	(revision )
@@ -1,137 +1,0 @@
-import { calculateWinnings } from './calculateWinnings'
-
-import { game, saveGameInHistory } from '../postgre/index'
-
-import axios from 'axios';
-
-export let samplePlayer = {
-    session_id: '',
-    name: '',
-    whichBets: [],
-    coinPlaced: {
-        x: -1,
-        y: -1,                
-    },
-    credits: -1,
-    betAmount: 0,
-    wonAmount: 0,
-    status: '_1_',
-    outcome: 'none',
-    gotResults: false,
-}
-
-export function resetGame() {
-    game.magicNumber = -1;
-    game.winningBets = [];
-    game.status = '_1_ongoing_timer';
-
-    let inactivePlayers = []
-
-    game.players.forEach(player => {
-        player.whichBets = [];
-        player.betAmount = 0;
-        player.wonAmount = 0;
-        player.coinPlaced = {
-            x: -1,
-            y: -1,                
-        },
-        player.outcome = 'none';
-        player.status = '_1_no_placed_bet';
-        player.gotResults = false;
-
-        const d = Date.now();
-
-        if (d - player.lastActivity > 200000) {
-            inactivePlayers.push(player);
-        }
-    })
-
-    for (let i = 0; i < inactivePlayers.length; i++) {
-        if (game.players.indexOf(inactivePlayers[i]) !== -1) {
-            game.players.splice(game.players.indexOf(inactivePlayers[i]), 1);
-        }
-    }
-}
-
-export function updateGameWithWinners() {
-    for (let i = 0; i < game.players.length; i++) {
-        const player = game.players[i];
-
-        let playerWon = false;
-        player.whichBets.forEach(bet => {
-            if (game.winningBets.indexOf(bet) !== -1) {
-                playerWon = true;
-            }
-        })
-
-        if (playerWon) {
-            player.outcome = 'won';
-        }
-        else {
-            player.outcome = 'lost';
-        }
-
-        player.wonAmount = calculateWinnings(player);
-
-        axios.get(`${process.env.HOME_URL}/api/postgre/?action=add_credits&session_id=${player.session_id}&credits=${player.wonAmount}&game=roulette&outcome=${player.outcome}`).then(postgreRes => {
-            if (postgreRes.data?.success) {
-                player.credits = postgreRes.data?.credits;
-            }
-        });
-
-        if (player.whichBets?.length > 0) {
-          game.finished = new Date().toGMTString();
-          saveGameInHistory('roulette', game, player.username)
-        }
-    }
-}
-
-export function addPlayer(session_id, name, username) {
-    if (game.players.map(e=>e.session_id).indexOf(session_id) === -1) {
-        game.players.push({
-            lastActivity: Date.now(),
-            session_id: session_id,
-            username: username,
-            name: name,
-            whichBets: [],
-            coinPlaced: {
-                x: -1,
-                y: -1,                
-            },
-            credits: -1,
-            betAmount: 0,
-            wonAmount: 0,
-            status: '_1_no_placed_bet',
-            outcome: 'none',
-            gotResults: false,
-        })
-    }
-    else {
-        game.players[game.players.map(e=>e.session_id).indexOf(session_id)].credits = -1;
-    }
-}
-
-export function getPlayer(session_id) {
-    const playerIdx = game.players.map(e=>e.session_id).indexOf(session_id);
-
-    if (playerIdx !== -1) {
-        return {
-            success: true,
-            player: game.players[playerIdx],
-        }
-    }
-
-    return {
-        success: false,
-        player: {...samplePlayer},
-    };
-}
-
-export function restrictGameInfo() {
-    const restrictedPlayers = game.players.map(player=>({...player, session_id: ""}))
-
-    return {
-        ...game,
-        players: restrictedPlayers,
-    }
-}
Index: pages/api/roulette/index.js
===================================================================
--- pages/api/roulette/index.js	(revision 41d3f60370077ca99cfecfaf1b8e6b74ea364357)
+++ 	(revision )
@@ -1,167 +1,0 @@
-import axios from 'axios';
-
-import { game, update_game_to_database } from '../postgre/index'
-
-require('dotenv').config();
-
-import { resetGame, updateGameWithWinners, addPlayer, getPlayer, restrictGameInfo } from './gameStates'
-
-import { getWinningBets } from './calculateWinnings'
-
-(function() {
-    setInterval(() => {
-        game.timeToStart--;
-
-        // WAIT_BEFORE seconds is the time allocated for spinning the wheel and seeing the results.
-        if (game.timeToStart == 0) {
-            game.timeToStart = game.COUNTDOWN_FROM + game.WAIT_BEFORE;
-
-            game.magicNumber = Math.floor(Math.random() * 37);
-            game.winningBets = getWinningBets(game.magicNumber);
-            
-            setTimeout(() => {
-                updateGameWithWinners();
-            }, 6000)
-        }
-        else if (game.timeToStart == 10) {
-            game.status = '_2_spinning';
-        }
-        else if (game.timeToStart == game.COUNTDOWN_FROM) {
-            resetGame();
-        }
-
-    }, 1000);
-})();
-
-if (game.status === undefined) {
-    game.status = '_1_ongoing_timer';     // statuses: _1_ongoing_timer, _2_spinning
-    game.timeToStart = 30;                // in seconds
-    game.COUNTDOWN_FROM = 30;
-    game.WAIT_BEFORE = 20;
-    game.magicNumber = -1;
-    game.winningBets = [];
-    game.players = [];
-}
-
-/**
- * ********************* BEGIN OF REQUEST HANDLER *********************
- */
-export default async function handler(req, res) {
-    /**
-     * GET method
-     */
-    if (req.method === 'GET') {
-        /**
-         * /---------------------- GET ----------------------/
-         * Place a bet.
-         * @action place_bet
-         * @param session_id
-         * @param betAmount
-         * @param whichBets
-         * @param coinPlacedX
-         * @param coinPlacedY
-         */
-        if (req.query.action === 'place_bet' && req.query?.session_id && req.query?.betAmount && req.query?.whichBets && req.query?.coinPlacedX && req.query?.coinPlacedY) {
-            const session_id = req.query.session_id;
-
-            const { success, player } = getPlayer(session_id);
-
-            if (success && game.status.includes('_1_') && player.status.includes('_1_')) {
-                axios.get(`${process.env.HOME_URL}/api/postgre?action=take_credits&session_id=${session_id}&credits=${req.query.betAmount}`).then(postgreRes => {
-                    if (postgreRes.data?.success) {
-                        player.betAmount = parseInt(req.query.betAmount);
-                        player.whichBets = req.query.whichBets.split(',');
-                        player.status = '_2_placed_bet';
-                        player.coinPlaced = {
-                            x: req.query.coinPlacedX,
-                            y: req.query.coinPlacedY,
-                        },
-                        player.credits = postgreRes.data?.credits;
-                        player.lastActivity = Date.now();
-                    }
-                });
-            }
-
-            res.end();
-        }
-
-        /**
-         * /---------------------- GET ----------------------/
-         * Updates the state periodically
-         * @action update_state
-         * @param session_id
-         */
-         if (req.query.action === 'update_state' && req.query?.session_id) {
-            const session_id = req.query.session_id;
-
-            const { success, player } = getPlayer(session_id);
-
-            let extraAction = "";
-            let extraAction2 = "";
-            let magicNumber = -1;
-            let winningBets = [];
-
-            if (success) {
-                if (game.timeToStart > game.COUNTDOWN_FROM && !player.gotResults) {
-                    extraAction = "spin_wheel";
-                    magicNumber = game.magicNumber;
-                    winningBets = game.winningBets;
-
-                    player.gotResults = true;
-                }
-                if (game.timeToStart > game.COUNTDOWN_FROM + game.WAIT_BEFORE - 15) {
-                    extraAction2 = "keep_alert";
-                }
-            }
-
-            if (game.loaded !== undefined && game.loaded) {
-                update_game_to_database();
-            }
-
-            res.json({
-                success: true,
-                rouletteGame: {
-                    game: restrictGameInfo(),
-                    player: player,
-                },
-                extraAction: extraAction,
-                extraAction2: extraAction2,
-                magicNumber: magicNumber,
-                winningBets: winningBets,
-            })
-        }
-
-        /**
-         * /---------------------- GET ----------------------/
-         * If the player is not in an existing room, create a room for them.
-         * If they are reconnecting, get the room they were in.
-         * @action get_player_info_on_enter
-         * @param session_id
-         */
-        if (req.query.action === 'get_player_info_on_enter' && req.query?.session_id) {
-            const session_id = req.query.session_id;
-
-            axios.get(`${process.env.HOME_URL}/api/postgre?action=check_if_logged_in&session_id=${session_id}`).then(postgreRes => {
-                if (postgreRes.data?.success) {
-                    addPlayer(session_id, postgreRes.data?.displayName, postgreRes.data?.username);
-                
-                    res.json({
-                        success: true,
-                        game: game,
-                        displayName: postgreRes.data?.displayName,
-                        session_id: postgreRes.data?.session_id,
-                        credits: postgreRes.data?.credits,
-                    })
-                }
-                else {
-                    res.json({
-                        success: false,
-                    })
-                }
-            });
-        }
-   }
-}
-/**
- * ********************* END OF REQUEST HANDLER *********************
- */
Index: pages/games/blackjack.js
===================================================================
--- pages/games/blackjack.js	(revision 41d3f60370077ca99cfecfaf1b8e6b74ea364357)
+++ 	(revision )
@@ -1,11 +1,0 @@
-import React from 'react'
-
-import Blackjack from '../../components/blackjack/Blackjack'
-
-const blackjack = () => {
-  return (
-    <Blackjack/>
-  )
-}
-
-export default blackjack
Index: pages/games/poker.js
===================================================================
--- pages/games/poker.js	(revision 41d3f60370077ca99cfecfaf1b8e6b74ea364357)
+++ 	(revision )
@@ -1,13 +1,0 @@
-import React from 'react'
-
-import Poker from '../../components/poker/Poker'
-
-const poker = () => {
-  return (
-    <div className="app">
-      <Poker/>
-    </div>
-  )
-}
-
-export default poker
Index: pages/games/roulette.js
===================================================================
--- pages/games/roulette.js	(revision 41d3f60370077ca99cfecfaf1b8e6b74ea364357)
+++ 	(revision )
@@ -1,12 +1,0 @@
-import React from 'react'
-import Roulette from '../../components/roulette/Roulette'
-
-const roulette = () => {
-  return (
-    <div className="app">
-      <Roulette/>
-    </div>
-  )
-}
-
-export default roulette
Index: pages/index.js
===================================================================
--- pages/index.js	(revision 41d3f60370077ca99cfecfaf1b8e6b74ea364357)
+++ pages/index.js	(revision 6568bdeae3dbd082b040ec9b3d752c195313b7e5)
@@ -1,58 +1,68 @@
 import Head from 'next/head'
-
-import Header from '../components/Header'
-import FullwidthText from '../components/FullwidthText'
-import GameCircle from '../components/GameCircle'
-import Loading from '../components/Loading'
-import RegisterScreen from '../components/RegisterScreen'
-import LoginScreen from '../components/LoginScreen'
-import Alert from '../components/Alert'
-import Notification from '../components/Notification'
-import Stats from '../components/Stats'
-import ManageCredits from '../components/ManageCredits'
-import ComplainScreen from '../components/Complain'
-import GamesHistory from '../components/GamesHistory'
+import Image from 'next/image'
+import styles from '../styles/Home.module.css'
 
 export default function Home() {
   return (
-    <div className="app" style={{backgroundImage: 'url("/images/bg.png")'}}>
+    <div className={styles.container}>
       <Head>
-        <meta charSet="utf-8"/>
-        <meta name="description" content="Enjoy your stay at Caessino (The best E-Casino out there!). Play Blackjack, Roulette or Poker and win huge prizes!"/>
-        <meta name="keywords" content="caessino, e-casino, casino, blackjack, roulette, poker"/>
+        <title>Create Next App</title>
+        <meta name="description" content="Generated by create next app" />
+        <link rel="icon" href="/favicon.ico" />
+      </Head>
 
-        <meta name="author" content="ESS" />
-        <meta name="copyright" content="&copy; ESS CORP 2022" />
+      <main className={styles.main}>
+        <h1 className={styles.title}>
+          Welcome to <a href="https://nextjs.org">Next.js!</a>
+        </h1>
 
-        <title>Caessino</title>
-      </Head>
-  
-      <Header/>
-      
-      <FullwidthText title="Welcome to Caessino" subtitle="Choose Your Game"/>
+        <p className={styles.description}>
+          Get started by editing{' '}
+          <code className={styles.code}>pages/index.js</code>
+        </p>
 
-      <div className="gameCircles">
-        <GameCircle src={"/images/blackjack.png"} text="Play Blackjack" routeTo="/games/blackjack" game="Blackjack"/>
-        <GameCircle src={"/images/roulette.png"} text="Play Roulette" routeTo="/games/roulette" game="Roulette"/>
-        <GameCircle src={"/images/poker.png"} text="Play Poker" routeTo="/games/poker" game="Poker"/>
-      </div>
+        <div className={styles.grid}>
+          <a href="https://nextjs.org/docs" className={styles.card}>
+            <h2>Documentation &rarr;</h2>
+            <p>Find in-depth information about Next.js features and API.</p>
+          </a>
 
-      <Loading/>
+          <a href="https://nextjs.org/learn" className={styles.card}>
+            <h2>Learn &rarr;</h2>
+            <p>Learn about Next.js in an interactive course with quizzes!</p>
+          </a>
 
-      <RegisterScreen/>
+          <a
+            href="https://github.com/vercel/next.js/tree/canary/examples"
+            className={styles.card}
+          >
+            <h2>Examples &rarr;</h2>
+            <p>Discover and deploy boilerplate example Next.js projects.</p>
+          </a>
 
-      <LoginScreen/>
+          <a
+            href="https://vercel.com/new?utm_source=create-next-app&utm_medium=default-template&utm_campaign=create-next-app"
+            className={styles.card}
+          >
+            <h2>Deploy &rarr;</h2>
+            <p>
+              Instantly deploy your Next.js site to a public URL with Vercel.
+            </p>
+          </a>
+        </div>
+      </main>
 
-      <Alert/>
-
-      <Notification/>
-
-      <Stats/>
-
-      <ManageCredits/>
-
-      <ComplainScreen/>
-
-      <GamesHistory/>
+      <footer className={styles.footer}>
+        <a
+          href="https://vercel.com?utm_source=create-next-app&utm_medium=default-template&utm_campaign=create-next-app"
+          target="_blank"
+          rel="noopener noreferrer"
+        >
+          Powered by{' '}
+          <span className={styles.logo}>
+            <Image src="/vercel.svg" alt="Vercel Logo" width={72} height={16} />
+          </span>
+        </a>
+      </footer>
     </div>
   )
