<?php
/**
 * Copyright (C) 2014 Sreeram Reddy Vanga <reddyvanga@gmail.com>
 * Author: Rishvi Chakka <rishvi@innopark.co.in>
 */

#ini_set('display_errors', 1);
#error_reporting(E_ALL);

require_once 'common_params_filter.php';
include_once 'system/config.php';
include_once 'system/platforms.conf.php';
include_once 'system/constants.conf.php';

require_once UTIL_ROOT . 'utils.lib.php';

require_once UNITY_ROOT . '/integration/server/cozy_service_provider.inc.php';
require_once UNITY_INC_ROOT . 'session.class.php';
require_once UNITY_CLASS_ROOT .'logger.class.php';
include_once 'sanitize_authenticate.php';

#if($_GET['game_name'] == "bingo") {
	echo '<script type="text/javascript" src="mobile_devie_orientation.js"></script>';
#}

function in_array2($needle, $haystacks) {
    foreach ($haystacks as $haystack) {
       if (strpos($needle, $haystack) != NULL) {
          return true;
       }
    }

    return false;
}

if($_GET['type'] == 16 or $_GET['type'] == '16'){
    PrintUtils::Notify(CRITICAL_ERROR, 'Demo mode is disabled');
}

//Start a logger with a class
$logger = Logger::getLogger("default");

$currency = (isset($_GET['currency']))?$_GET['currency']:DEFAULT_CURRENCY;

//Check if the whitelabel is configured
$wl_key = (isset($_GET['wl_key']))?$_GET['wl_key']:False;
if (!$wl_key){
    PrintUtils::Notify(CRITICAL_ERROR, 
                       'WL key cannot be empty. Please relaunch the game.');   
}

$db_conn = Database::GetInstance('main');
#var_dump($db_conn);
#$wl_key = mysqli_real_escape_string($db_conn, $wl_key);
$platform = $_GET['platform_type'];
$wl_key = $db_conn->real_escape_string($wl_key);
$wl_details = CozyService::GetIntegrationDetails($wl_key);
$logger->info("wl_details: " . var_export($wl_details, true));


if (!$wl_details){
    $logger->info("Games launched by WL not configured (Ref: $wl_key)");
    PrintUtils::Notify(CRITICAL_ERROR, 
                       'Games are not configured for this site.' .
                       'Please contact support for assistance.');    
}

///
// Setting the Whitelabel URLs in SESSION
///
$whitelabel_urls = CozyService::getWhitelabelUrls($wl_key);
/*echo "<!--";
print_r($whitelabel_urls);
echo "-->";*/
foreach($whitelabel_urls as $key => $url) {
	$_SESSION[$key] = $url;
}
unset($whitelabel_urls);

///
// Set site url in session which is not received in the above call
///
$domain = $wl_details['domain'];
$_SESSION['site_url']  = "https://{$domain}/";
$_SESSION['whitelabel_id'] = $wl_details['id'];

$HTTP_DOMAINS = Array('7bingo.com', 'guaubingo.com');
if (in_array2($domain, $HTTP_DOMAINS))
    $_SESSION['site_url']  = "http://{$domain}/";

///
// If origin is bingo redirect
// Temporary fix for game lobby in bingo
///
if ($_GET['origin'] == 'bingo'){
    $redirect_page = $_SESSION['site_url'].'/game/launch/'.filter_var($_GET['gameCategory'],FILTER_SANITIZE_STRING).'/'.filter_var($_GET['name'],FILTER_SANITIZE_STRING).'/'.filter_var($_GET['type'],FILTER_SANITIZE_STRING);
    $redirect_page = filter_var($redirect_page,FILTER_VALIDATE_URL);
    print "<meta http-equiv='refresh' content='0; url=$redirect_page'>";
    exit;
}

///
// Set the login, cashier and support url
///
$_SESSION['login_url'] = CozyService::getLoginUrl($wl_key);
$_SESSION['cashier_url'] = CozyService::getCashierUrl($wl_key);

///
// Required format in mobile: Mobile needs the Cashier URL to be a relative url
// of the site url
///
$_site_url = $_SESSION['site_url'];
$_cashier_url = $_SESSION['cashier_url'];

$third_slash_pos = strpos($_cashier_url, '/', 10);
$_SESSION['cashier_uri'] = substr($_cashier_url, $third_slash_pos+1);

$token = isset($_GET['token']) ? $_GET['token']: "";
$_SESSION['passwd'] = $_SESSION['site_sess_id'] = $token;
$_SESSION['wl_key'] = $wl_key;

require_once UNITY_CLASS_ROOT.'player.class.php';
$session_details = PlayerHelper::GetSessionDetails($token);

if ($session_details['error'] != 1){
    $_SESSION['login'] = $_SESSION['alias'] = $session_details['username'];
    $_SESSION['account_id'] = $session_details['account_id'];

    //set player currency
    $player_balances = PlayerHelper::GetBalances($token, 
                                                 $_SESSION['account_id']);

    $_SESSION['player_properties'] = $player_balances['properties'];
    $_SESSION['currency'] = $player_balances['currency'];
    $_SESSION['currency_iso'] = $player_balances['currency'];
    if($_REQUEST['gameType'] == 'bingo'){
        @include_once 'src/bingo/chat_status.php';
    }
    #CozySession::init_user_session($_SESSION['account_id'], session_id());
}
require_once 'game_launcher.php';
