<?php
if(isset($_SERVER["REMOTE_ADDR"])){
	$mode = $_SERVER["REMOTE_ADDR"];
} else {
	$mode = 'CLI';
	$grantaccess = 1;
}
if($mode != 'CLI'){
if(substr($_SERVER['SERVER_NAME'],0,4) != "www." && $_SERVER['SERVER_NAME'] != 'localhost')
header('Location: '.
       (@$_SERVER['HTTPS'] == 'on' ? 'https://' : 'http://').
       'www.'.$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI']);

$uriSegments = explode("/", parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));
   
// if(empty($_SERVER['HTTPS']) || $_SERVER['HTTPS'] == "off"){
// 	if($uriSegments[1] =='login')
// 	{
// 	$redirect = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
//     header('HTTP/1.1 301 Moved Permanently');
//     header('Location: ' . $redirect);
//     exit();
// 	}
// }
// else {
// 	if($uriSegments[1] !='login')
// 	{
// 	$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
//     header('HTTP/1.1 301 Moved Permanently');
//     header('Location: ' . $redirect);
//     exit();
// 	}
// }


if (isset($_SERVER["HTTP_CF_CONNECTING_IP"])) {
	$_SERVER['REMOTE_ADDR'] = $_SERVER["HTTP_CF_CONNECTING_IP"];
}

$grantaccess = 0;

if($_SERVER['REMOTE_ADDR'] == "103.225.64.67" ||$_SERVER['REMOTE_ADDR'] == "137.97.70.79"|| $_SERVER['REMOTE_ADDR'] == "103.225.64.68" || $_SERVER['REMOTE_ADDR'] == "107.6.124.17" || $_SERVER['REMOTE_ADDR'] == "107.6.124.39" || $_SERVER['REMOTE_ADDR'] == "107.6.124.4" || $_SERVER['REMOTE_ADDR'] == "107.6.124.42" || $_SERVER['REMOTE_ADDR'] == "107.6.124.43" || $_SERVER['REMOTE_ADDR'] == "60.49.114.167" || $_SERVER['REMOTE_ADDR'] == "210.195.85.9" || $_SERVER['REMOTE_ADDR'] == "161.202.120.157" || $_SERVER['REMOTE_ADDR'] == "209.234.248.247" || $_SERVER['REMOTE_ADDR'] == "202.184.154.182" || $_SERVER['REMOTE_ADDR'] == "103.225.64.171" || $_SERVER['REMOTE_ADDR'] == "180.75.251.44") {
	$grantaccess = 1;
}
}
//209.234.248.247 is kc
//202.184.154.182 is alex
//175.141.47.90 chin hei
// if($_SERVER['REMOTE_ADDR'] != "107.6.124.17" || $_SERVER['REMOTE_ADDR'] != "107.6.124.39" || $_SERVER['REMOTE_ADDR'] != "107.6.124.4" || $_SERVER['REMOTE_ADDR'] != "107.6.124.42" || $_SERVER['REMOTE_ADDR'] != "107.6.124.43") {
if ($grantaccess == 0){
	exit();
}

//run datalist query
$conn=mysqli_connect("database-1.cugxk69rtahe.ap-northeast-1.rds.amazonaws.com","sandbox_isac","YOEDFqUO#axFEW1aJR}8CTE28U==9t0","sandbox_isac");

// Check connection
if (mysqli_connect_errno($conn))
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  mysqli_close($conn);
  }
	$sql = "SELECT * FROM report_data WHERE report_type = 'user_category' AND report_start_date = DATE_ADD(CURDATE(), INTERVAL -1 DAY) LIMIT 1";
	$result = mysqli_query($conn,$sql);
	if($result->num_rows==0){
		$daynow = date('Y-m-d',strtotime("-1 days"));
		
		//vip1
		$sql = "SELECT COUNT(trans_target) AS count FROM (SELECT DISTINCT trans_target, trans_date FROM master_transaction WHERE (trans_target, trans_date) IN (SELECT trans_target, max(trans_date) FROM master_transaction WHERE trans_type = 'reload_manual' AND trans_date BETWEEN date_add('$daynow 23:59:59',interval -1 month) AND '$daynow 23:59:59' GROUP BY trans_target)) a
	LEFT JOIN (SELECT DISTINCT np_uid, np_amount FROM net_profit_trace WHERE (np_uid, np_datetime) IN (SELECT np_uid, max(np_datetime) FROM net_profit_trace WHERE np_datetime <= '$daynow 23:59:59' GROUP BY np_uid)) b ON a.trans_target = b.np_uid
	LEFT JOIN (SELECT DISTINCT id FROM users WHERE group_id=2) c ON a.trans_target = c.id
	LEFT JOIN (SELECT DISTINCT user_id, behaviour1 FROM meta) d ON a.trans_target = d.user_id
	WHERE np_uid IS NOT NULL AND id IS NOT NULL AND np_amount>=10000 AND behaviour1<>1";
		$result = mysqli_query($conn,$sql);
		while($row = mysqli_fetch_array($result))
		{
			$vip1 = $row['count'];
		}
		$datalist['vip1'] = $vip1;
		
		$unixnow = strtotime($daynow.' 23:59:59');
		$lastmonth = strtotime($daynow.' 23:59:59') - 28800 - 30*24*60*60;
		//active_register
		$sql = "SELECT COUNT(DISTINCT meta.id) AS total FROM users LEFT JOIN meta ON meta.user_id = users.id WHERE last_reload = '0000-00-00 00:00:00' AND last_login > $lastmonth AND group_id=2 AND behaviour1<>1";
		$result = mysqli_query($conn,$sql);
		while($row = mysqli_fetch_array($result))
		{
			$active_register = $row['total'];
		}
		$datalist['active_register'] = $active_register;
		
		//inactive_register
		$sql = "SELECT COUNT(DISTINCT meta.id) AS total FROM users LEFT JOIN meta ON meta.user_id = users.id WHERE last_reload = '0000-00-00 00:00:00' AND last_login <= $lastmonth AND group_id=2 AND behaviour1<>1";
		$result = mysqli_query($conn,$sql);
		while($row = mysqli_fetch_array($result))
		{
			$inactive_register = $row['total'];
		}
		$datalist['inactive_register'] = $inactive_register;
		
		//inactive_vip
		$sql = "SELECT COUNT(user_id) AS total FROM users LEFT JOIN meta ON meta.user_id = users.id LEFT JOIN net_profit_trace ON meta.user_id = net_profit_trace.np_uid WHERE (np_uid, np_datetime) IN (SELECT np_uid, max(np_datetime) FROM net_profit_trace WHERE np_datetime <= '$daynow 23:59:59' GROUP BY np_uid) AND last_reload <= date_add('$daynow 23:59:59',interval -1 month) AND last_reload <> '0000-00-00 00:00:00' AND group_id=2 AND behaviour1<>1";
		$result = mysqli_query($conn,$sql);
		while($row = mysqli_fetch_array($result))
		{
			$inactive_vip = $row['total'];
		}
		$datalist['inactive_vip'] = $inactive_vip;
		
		//total_vip
		$sql = "SELECT COUNT(user_id) AS total FROM users LEFT JOIN meta ON meta.user_id = users.id WHERE group_id=2 AND behaviour1<>1";
		$result = mysqli_query($conn,$sql);
		while($row = mysqli_fetch_array($result))
		{
			$total_vip = $row['total'];
		}
		$datalist['total_vip'] = $total_vip;
		
		//vip 0 less than 2 years
		$sql = "SELECT COUNT(np_uid) AS count_vip FROM (SELECT DISTINCT trans_target AS created FROM master_transaction LEFT JOIN users ON users.id=trans_target WHERE trans_type = 'reload_manual' AND trans_date BETWEEN date_add('$daynow 23:59:59',interval -1 month) AND '$daynow 23:59:59' AND created_on > $unixnow-63072000 ) p LEFT JOIN (SELECT np_uid, np_amount FROM net_profit_trace WHERE (np_uid, np_datetime) IN (SELECT np_uid, max(np_datetime) FROM net_profit_trace WHERE np_datetime <= '$daynow 23:59:59' GROUP BY np_uid)) l ON p.created = l.np_uid WHERE created IS NOT NULL AND np_uid IS NOT NULL AND np_amount<10000";
		$result = mysqli_query($conn,$sql);
		while($row = mysqli_fetch_array($result))
		{
			$vip0less2 = $row['count_vip'];
		}
		$datalist['vip0less2'] = $vip0less2;
		
		//vip 0 more than 2 years
		$sql = "SELECT COUNT(np_uid) AS count_vip FROM (SELECT DISTINCT trans_target AS created FROM master_transaction LEFT JOIN users ON users.id=trans_target WHERE trans_type = 'reload_manual' AND trans_date BETWEEN date_add('$daynow',interval -1 month) AND '$daynow' AND created_on <= $unixnow-63072000 ) p LEFT JOIN (SELECT np_uid, np_amount FROM net_profit_trace WHERE (np_uid, np_datetime) IN (SELECT np_uid, max(np_datetime) FROM net_profit_trace WHERE np_datetime <= '$daynow' GROUP BY np_uid)) l ON p.created = l.np_uid WHERE created IS NOT NULL AND np_uid IS NOT NULL AND np_amount<10000";
		$result = mysqli_query($conn,$sql);
		while($row = mysqli_fetch_array($result))
		{
			$vip0more2 = $row['count_vip'];
		}
		$datalist['vip0more2'] = $vip0more2;
				
		//parking
		$sql = "SELECT COUNT(user_id) AS total FROM users LEFT JOIN meta ON meta.user_id = users.id WHERE group_id=2 AND behaviour1=1";
		$result = mysqli_query($conn,$sql);
		while($row = mysqli_fetch_array($result))
		{
			$parking = $row['total'];
		}
		$datalist['parking'] = $parking;
		
		//frozen
		$sql = "SELECT COUNT(user_id) AS total FROM users LEFT JOIN meta ON meta.user_id = users.id WHERE group_id=3";
		$result = mysqli_query($conn,$sql);
		while($row = mysqli_fetch_array($result))
		{
			$frozen = $row['total'];
		}
		$datalist['frozen'] = $frozen;
		$datalist = json_encode($datalist);
		
		$sql = "SELECT * FROM report_data WHERE report_type = 'user_category' AND report_start_date = DATE_ADD(CURDATE(), INTERVAL -1 DAY) LIMIT 1";
		$result = mysqli_query($conn,$sql);
		if($result->num_rows==0){
			$sql = "INSERT INTO report_data (report_type, report_start_date, report_end_date, report_data) VALUES ('user_category', '$daynow', '$daynow', '$datalist')";
			mysqli_query($conn,$sql);
		}

		
	}
	mysqli_close($conn);
//end run datalist query

// //start doing geo location
// if ($_SERVER["HTTP_CF_IPCOUNTRY"]) {
	// $var_country_code = $_SERVER["HTTP_CF_IPCOUNTRY"];
// }
// else {
	// $var_country_code = 'MY';
// }

// // redirect based on country code:
// if ($var_country_code == "BN") {
// header('Location: http://www.isac365.com/');
// }
// else if ($var_country_code == "ID") {
// header('Location: http://www.isac88.com/');
// }
// else {
// }

/*
 *---------------------------------------------------------------
 * APPLICATION ENVIRONMENT
 *---------------------------------------------------------------
 *
 * You can load different configurations depending on your
 * current environment. Setting the environment also influences
 * things like logging and error reporting.
 *
 * This can be set to anything, but default usage is:
 *
 *     development
 *     testing
 *     production
 *
 * NOTE: If you change these, also change the error_reporting() code below
 *
 */
	define('ENVIRONMENT', 'development');
	//define('ENVIRONMENT', 'development');
/*
 *---------------------------------------------------------------
 * ERROR REPORTING
 *---------------------------------------------------------------
 *
 * Different environments will require different levels of error reporting.
 * By default development will show errors but testing and live will hide them.
 */

if (defined('ENVIRONMENT'))
{
	switch (ENVIRONMENT)
	{
		case 'development':
			error_reporting(E_ALL);
		break;

		case 'testing':
		case 'production':
			error_reporting(0);
		break;

		default:
			exit('The application environment is not set correctly.');
	}
}

/*
 *---------------------------------------------------------------
 * SYSTEM FOLDER NAME
 *---------------------------------------------------------------
 *
 * This variable must contain the name of your "system" folder.
 * Include the path if the folder is not in the same  directory
 * as this file.
 *
 */
	$system_path = 'system';

/*
 *---------------------------------------------------------------
 * APPLICATION FOLDER NAME
 *---------------------------------------------------------------
 *
 * If you want this front controller to use a different "application"
 * folder then the default one you can set its name here. The folder
 * can also be renamed or relocated anywhere on your server.  If
 * you do, use a full server path. For more info please see the user guide:
 * http://codeigniter.com/user_guide/general/managing_apps.html
 *
 * NO TRAILING SLASH!
 *
 */
	$application_folder = 'application';

/*
 * --------------------------------------------------------------------
 * DEFAULT CONTROLLER
 * --------------------------------------------------------------------
 *
 * Normally you will set your default controller in the routes.php file.
 * You can, however, force a custom routing by hard-coding a
 * specific controller class/function here.  For most applications, you
 * WILL NOT set your routing here, but it's an option for those
 * special instances where you might want to override the standard
 * routing in a specific front controller that shares a common CI installation.
 *
 * IMPORTANT:  If you set the routing here, NO OTHER controller will be
 * callable. In essence, this preference limits your application to ONE
 * specific controller.  Leave the function name blank if you need
 * to call functions dynamically via the URI.
 *
 * Un-comment the $routing array below to use this feature
 *
 */
	// The directory name, relative to the "controllers" folder.  Leave blank
	// if your controller is not in a sub-folder within the "controllers" folder
	// $routing['directory'] = '';

	// The controller class file name.  Example:  Mycontroller.php
	// $routing['controller'] = '';

	// The controller function you wish to be called.
	// $routing['function']	= '';


/*
 * -------------------------------------------------------------------
 *  CUSTOM CONFIG VALUES
 * -------------------------------------------------------------------
 *
 * The $assign_to_config array below will be passed dynamically to the
 * config class when initialized. This allows you to set custom config
 * items or override any default config values found in the config.php file.
 * This can be handy as it permits you to share one application between
 * multiple front controller files, with each file containing different
 * config values.
 *
 * Un-comment the $assign_to_config array below to use this feature
 *
 */
	// $assign_to_config['name_of_config_item'] = 'value of config item';



// --------------------------------------------------------------------
// END OF USER CONFIGURABLE SETTINGS.  DO NOT EDIT BELOW THIS LINE
// --------------------------------------------------------------------

/*
 * ---------------------------------------------------------------
 *  Resolve the system path for increased reliability
 * ---------------------------------------------------------------
 */

	// Set the current directory correctly for CLI requests
	if (defined('STDIN'))
	{
		chdir(dirname(__FILE__));
	}

	if (realpath($system_path) !== FALSE)
	{
		$system_path = realpath($system_path).'/';
	}

	// ensure there's a trailing slash
	$system_path = rtrim($system_path, '/').'/';

	// Is the system path correct?
	if ( ! is_dir($system_path))
	{
		exit("Your system folder path does not appear to be set correctly. Please open the following file and correct this: ".pathinfo(__FILE__, PATHINFO_BASENAME));
	}

/*
 * -------------------------------------------------------------------
 *  Now that we know the path, set the main path constants
 * -------------------------------------------------------------------
 */
	// The name of THIS file
	define('SELF', pathinfo(__FILE__, PATHINFO_BASENAME));

	// The PHP file extension
	define('EXT', '.php');

	// Path to the system folder
	define('BASEPATH', str_replace("\\", "/", $system_path));

	// Path to the front controller (this file)
	define('FCPATH', str_replace(SELF, '', __FILE__));

	// Name of the "system folder"
	define('SYSDIR', trim(strrchr(trim(BASEPATH, '/'), '/'), '/'));


	// The path to the "application" folder
	if (is_dir($application_folder))
	{
		define('APPPATH', $application_folder.'/');
	}
	else
	{
		if ( ! is_dir(BASEPATH.$application_folder.'/'))
		{
			exit("Your application folder path does not appear to be set correctly. Please open the following file and correct this: ".SELF);
		}

		define('APPPATH', BASEPATH.$application_folder.'/');
	}

/*
 * --------------------------------------------------------------------
 * LOAD THE BOOTSTRAP FILE
 * --------------------------------------------------------------------
 *
 * And away we go...
 *
 */
require_once BASEPATH.'core/CodeIgniter'.EXT;

/* End of file index.php */
/* Location: ./index.php */
