<?php

function dbconnect()
    {
        global $pdo;
		
            try {
                $pdo = new PDO('mysql:host='. DB_HOST .';dbname='. DB_NAME . ';charset=utf8', DB_USER, DB_PASS);
				$pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION ); //Error Handling
            } catch (PDOException $e) {
                die('MySQL connection failed! ' . $e->getMessage());
            }

    }
	
function is_user()
{
	if (isset($_SESSION['user_login']) && isset($_SESSION['user_acc']))
		return true;
}


function is_admin()
{
	if (isset($_SESSION['admin_login']))
		return true;
}


function user_attempt($username, $password, $status)
{
	global $pdo;
	
	$stmt = $pdo->prepare('SELECT * 
	FROM '.USERS_TABLE_NAME.' 
	WHERE user_name = :username AND user_pwd = :password AND user_status = :status LIMIT 1');

	$stmt->execute(array(':username' => $username, 'password' => md5($password), ':status' => $status));

	if ($data = $stmt->fetch( PDO::FETCH_OBJ )) {
		# set session
		$_SESSION['user_login'] = $data->user_name;
		
		return true;
	} else {
		return false;
	}
}


function user_photo($username)
{
	global $pdo;
	
	$stmt = $pdo->prepare('SELECT * 
	FROM '.USERS_TABLE_NAME.' 
	WHERE user_name = :username LIMIT 1');

	$stmt->execute(array(':username' => $username));

	if ($data = $stmt->fetch( PDO::FETCH_OBJ )) {
		# Return Photo
		$photo = $data->user_photo;
		$nophoto = "user.png";
		
		return $photo;
	if (empty($photo)) {
		return $nophoto;
	}
	}
}

function user_phone($username)
{
	global $pdo;
	
	$stmt = $pdo->prepare('SELECT * 
	FROM '.USERS_TABLE_NAME.' 
	WHERE user_name = :username LIMIT 1');

	$stmt->execute(array(':username' => $username));

	if ($data = $stmt->fetch( PDO::FETCH_OBJ )) {
		# Return phone
		$phone = $data->user_phone;
		
		return $phone;
	} 
}


function get_currency($acc)
{
	global $pdo;

	$stmt = $pdo->prepare('SELECT *
	FROM '.USERS_TABLE_NAME.'
	WHERE user_acc = :acc LIMIT 1');

	$stmt->execute(array(':acc' => $acc));

	if ($data = $stmt->fetch( PDO::FETCH_OBJ )) {
		# Return currency
		$currency = $data->currency;

		return $currency;
	}
}


function get_username($acc)
{
	global $pdo;
	
	$stmt = $pdo->prepare('SELECT * 
	FROM '.USERS_TABLE_NAME.' 
	WHERE user_acc = :acc LIMIT 1');

	$stmt->execute(array(':acc' => $acc));

	if ($data = $stmt->fetch( PDO::FETCH_OBJ )) {
		# Return username
		$username = $data->user_name;
		
		return $username;
	} 
}

function get_email($acc)
{
	global $pdo;
	
	$stmt = $pdo->prepare('SELECT * 
	FROM '.USERS_TABLE_NAME.' 
	WHERE user_acc = :acc LIMIT 1');

	$stmt->execute(array(':acc' => $acc));

	if ($data = $stmt->fetch( PDO::FETCH_OBJ )) {
		# Return email
		$email = $data->user_email;
		
		return $email;
	} 
}

function get_userid($userid)
{
	global $pdo;
	
	$stmt = $pdo->prepare('SELECT * 
	FROM '.USERS_TABLE_NAME.' 
	WHERE user_id = :userid LIMIT 1');

	$stmt->execute(array(':userid' => $userid));

	if ($data = $stmt->fetch( PDO::FETCH_OBJ )) {
		# Return username
		$first_name = $data->first_name;
		$last_name = $data->last_name;
		$user_name = $first_name.$last_name;
		
		return $user_name;
	}
}

function clean_phone($phone){    
    $phone = str_replace(" ","", trim($phone)); 
	$phone = str_replace("-","", trim($phone));	
    $phone = preg_replace("/[^a-zA-Z0-9-]/","", $phone);
	
    return $phone;
}

function get_pin($digits){
    //$digits = 4;
	$pin = str_pad(rand(0, pow(10, $digits)-1), $digits, '0', STR_PAD_LEFT);

    return $pin;
}

function admin_attempt($username, $password)
{
	global $pdo;
	
	$stmt = $pdo->prepare('SELECT * 
	FROM '.ADMIN_TABLE_NAME.' 
	WHERE admin_login = :username AND admin_pwd = :password 
	LIMIT 1');

	$stmt->execute(array(':username' => $username, 'password' => md5($password)));

	if ($data = $stmt->fetch( PDO::FETCH_OBJ )) {
		# set session
		$_SESSION['admin_login'] = $data->admin_login;
		
		return true;
	} else {
		return false;
	}
}

function pin_attempt($username, $pin)
{
	global $pdo;
	
	$stmt = $pdo->prepare('SELECT * 
	FROM '.USERS_TABLE_NAME.' 
	WHERE user_name = :username AND user_pin = :pin 
	LIMIT 1');

	$stmt->execute(array(':username' => $username, ':pin' => $pin));

	if ($data = $stmt->fetch( PDO::FETCH_OBJ )) {
		# set session
		$_SESSION['user_acc'] = $data->user_acc;
		$_SESSION['currency'] = $data->currency;
		
		return true;
	} else {
		return false;
	}
}

function redirect($url)
{
	header('Location: ' .$url);
	exit;
}

function user_exist($username, $password)
{
	global $pdo;
	
	$stmt = $pdo->prepare('SELECT * 
	FROM '.USERS_TABLE_NAME.' 
	WHERE user_name = :username AND user_pwd = :password 
	LIMIT 1');

	$stmt->execute(array(':username' => $username, ':password' => md5($password)));
	if ($data = $stmt->fetch( PDO::FETCH_OBJ )) {
		return true;
	} else {
		return false;
	}
}

function name_exist($username)
{
	global $pdo;
	
	$stmt = $pdo->prepare('SELECT * 
	FROM '.USERS_TABLE_NAME.' 
	WHERE user_name = :username 
	LIMIT 1');

	$stmt->execute(array(':username' => $username));
	if ($data = $stmt->fetch( PDO::FETCH_OBJ )) {
		return true;
	} else {
		return false;
	}
}

function acc_exist($acc)
{
	global $pdo;
	
	$stmt = $pdo->prepare('SELECT * 
	FROM '.USERS_TABLE_NAME.' 
	WHERE user_acc = :acc 
	LIMIT 1');

	$stmt->execute(array(':acc' => $acc));
	if ($data = $stmt->fetch( PDO::FETCH_OBJ )) {
		return true;
	} else {
		return false;
	}
}

function email_exist($email)
{
	global $pdo;
	
	$stmt = $pdo->prepare('SELECT * 
	FROM '.USERS_TABLE_NAME.' 
	WHERE user_email = :email 
	LIMIT 1');

	$stmt->execute(array(':email' => $email));
	if ($data = $stmt->fetch( PDO::FETCH_OBJ )) {
		return true;
	} else {
		return false;
	}
}

function admin_exist($username, $password)
{
	global $pdo;
	
	$stmt = $pdo->prepare('SELECT * 
	FROM '.ADMIN_TABLE_NAME.' 
	WHERE admin_login = :username AND admin_pwd = :password 
	LIMIT 1');

	$stmt->execute(array(':username' => $username, ':password' => md5($password)));
	if ($data = $stmt->fetch( PDO::FETCH_OBJ )) {
		return true;
	} else {
		return false;
	}
}

function token_exist($token, $password)
{
	global $pdo;
	
	$stmt = $pdo->prepare('SELECT * 
	FROM '.USERS_TABLE_NAME.' 
	WHERE user_name = :username AND user_pwd = :password 
	LIMIT 1');

	$stmt->execute(array(':username' => $username, ':password' => md5($password)));
	if ($data = $stmt->fetch( PDO::FETCH_OBJ )) {
		return true;
	} else {
		return false;
	}
}


function update_pass($username, $password)
{
	global $pdo;
	$stmt = $pdo->prepare('
		UPDATE '.USERS_TABLE_NAME.'
		SET user_pwd = :password, user_word = :word
		WHERE user_name = :username 
		LIMIT 1');

	$stmt->execute(array(':username' => $username, ':word' => $password, ':password' => md5($password)));
	return true;
}


function update_apass($username, $password)
{
	global $pdo;
	$stmt = $pdo->prepare('
		UPDATE '.ADMIN_TABLE_NAME.'
		SET admin_pwd = :password
		WHERE admin_login = :username 
		LIMIT 1');

	$stmt->execute(array(':username' => $username, ':password' => md5($password)));
	return true;
}



function pin_exist($username, $pin)
{
	global $pdo;
	
	$stmt = $pdo->prepare('SELECT * 
	FROM '.USERS_TABLE_NAME.' 
	WHERE user_name = :username AND user_pin = :pin 
	LIMIT 1');

	$stmt->execute(array(':username' => $username, ':pin' => $pin));
	if ($data = $stmt->fetch( PDO::FETCH_OBJ )) {
		return true;
	} else {
		return false;
	}
}


function update_pin($username, $pin)
{
	global $pdo;
	$stmt = $pdo->prepare('
		UPDATE '.USERS_TABLE_NAME.'
		SET user_pin = :pin
		WHERE user_name = :username 
		LIMIT 1');

	$stmt->execute(array(':username' => $username, ':pin' => $pin));
	return true;
}


function insert_last($last_ip, $username)
{
	global $pdo;
	
		# insert last login info
		$stmt = $pdo->prepare('
		UPDATE '.USERS_TABLE_NAME.'
		SET last_ip = :last_ip, last_ts = NOW()
		WHERE user_name = :username
		LIMIT 1');

	$stmt->execute(array(':last_ip' => $last_ip, ':username' => $username));
	if ($pdo->lastInsertId())
		return true;
}


function insert_alast($last_ip, $username)
{
	global $pdo;
	
		# insert last login info
		$stmt = $pdo->prepare('
		UPDATE '.ADMIN_TABLE_NAME.'
		SET last_ip = :last_ip, last_ts = NOW()
		WHERE admin_login = :username
		LIMIT 1');

	$stmt->execute(array(':last_ip' => $last_ip, ':username' => $username));
	if ($pdo->lastInsertId())
		return true;
}

function update_token($token, $email)
{
	global $pdo;
	$stmt = $pdo->prepare('
		UPDATE '.USERS_TABLE_NAME.'
		SET pwd_reset_hash = :token, pwd_reset_ts = NOW()
		WHERE user_email = :email 
		LIMIT 1');

	$stmt->execute(array(':token' => $token, ':email' => $email));
	return true;
}


function update_security($pass, $pin, $word, $username)
{
	global $pdo;
	$stmt = $pdo->prepare('
		UPDATE '.USERS_TABLE_NAME.'
		SET user_pwd = :pass, user_pin = :pin, user_word = :word WHERE user_name = :username LIMIT 1');

	$stmt->execute(array(':pass' => $pass, ':pin' => $pin, ':word' => $word, ':username' => $username));
	return true;
}


function log_info($ip, $username, $id, $log)
{
	# insert new log info
	global $pdo;
	$stmt = $pdo->prepare('
		INSERT INTO '.SITE_LOG_TABLE.'
		(ipaddr, user_name, log_id, log_details, log_date)
		VALUES (:ip, :user, :id, :log, NOW())');

	$stmt->execute( array(':ip' => $ip, ':user' => $username, ':id' => $id, ':log' => $log) );
	return true;
}

function msg_read($msgid, $read)
{
	global $pdo;
	
		# insert last login info
		$stmt = $pdo->prepare('
		UPDATE '.MSGS_TABLE_NAME.'
		SET msg_read = :read
		WHERE msg_id = :msgid LIMIT 1');

	$stmt->execute(array(':msgid' => $msgid, ':read' => $read));
	//if ($pdo->lastInsertId())
		return true;
}

function adm_read($msgid, $read)
{
	global $pdo;
	
		# insert last login info
		$stmt = $pdo->prepare('
		UPDATE '.MSGS_TABLE_NAME.'
		SET adm_read = :read
		WHERE msg_id = :msgid LIMIT 1');

	$stmt->execute(array(':msgid' => $msgid, ':read' => $read));
	//if ($pdo->lastInsertId())
		return true;
}


function alrt_read($read)
{
	global $pdo;
	
		# insert last login info
		$stmt = $pdo->prepare('
		UPDATE '.ALERT_TABLE_NAME.'
		SET alrt_read = :read');

	$stmt->execute(array(':read' => $read));
	if ($pdo->lastInsertId())
		return true;
}


function code1_check($code, $usercode)
{
	# insert new log info
	if ($usercode == $code) {
	return true;
}else {
		return false;
	}
}

function code2_check($code, $usercode)
{
	# insert new log info
	if ($usercode == $code) {
	return true;
}else {
		return false;
	}
}

function code3_check($code, $usercode)
{
	# insert new log info
	if ($usercode == $code) { 
	return true;
}else {
		return false;
	}
}

function complete_transfer($username, $status, $result, $account)
{
	global $pdo;
	$stmt = $pdo->prepare('
		UPDATE '.TRANF_TABLE_NAME.'
		SET status = :status,  result = :result
		WHERE user_name = :username AND user_acc = :account
		ORDER BY tranf_id DESC LIMIT 1');

	$stmt->execute(array(':username' => $username, ':status' => $status, ':result' => $result, ':account' => $account));
	return true;
}


function trans_credit($account, $username, $details, $amount)
{
	global $pdo;
	
		# insert transaction
		$stmt = $pdo->prepare('
		INSERT INTO '.TRANS_TABLE_NAME.'
		(user_acc, user_name, trans_date, trans_details, credit)
		VALUES (:account, :username, NOW(), :details, :amount)');

	$stmt->execute(array(':account' => $account, ':username' => $username, ':details' => $details, ':amount' => $amount));
	if ($pdo->lastInsertId())
		return true;
}


function trans_debit($account, $username, $details, $amount)
{
	global $pdo;
	
		# insert transaction
		$stmt = $pdo->prepare('
		INSERT INTO '.TRANS_TABLE_NAME.'
		(user_acc, user_name, trans_date, trans_details, debit)
		VALUES (:account, :username, NOW(), :details, :amount)');

	$stmt->execute(array(':account' => $account, ':username' => $username, ':details' => $details, ':amount' => $amount));
	if ($pdo->lastInsertId())
		return true;
}

function sum_credits($username)
{
	global $pdo;
	$stmt = $pdo->prepare('SELECT SUM(credit) FROM '.TRANS_TABLE_NAME.' WHERE user_acc = :username');
	$stmt->execute(array(':username' => $username));
	$credit = $stmt->fetchColumn();
	return $credit;
}

function sum_debits($username)
{
	global $pdo;
	$stmt = $pdo->prepare('SELECT SUM(debit) FROM '.TRANS_TABLE_NAME.' WHERE user_acc = :username');
	$stmt->execute(array(':username' => $username));
	$debit = $stmt->fetchColumn();
	return $debit;
}


function recent_msgs($username, $read)
{
	global $pdo;
	$stmt = $pdo->prepare('SELECT * FROM '.MSGS_TABLE_NAME.' WHERE msg_rcvr = :username AND msg_read = :read ORDER BY msg_date DESC LIMIT 3');
	$stmt->execute(array(':username' => $username, ':read' => $read));
	$recentmsgs = array();

	while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
	$recentmsgs[] = $row;
	}
	return $recentmsgs;
}


function recent_alrts($username, $read)
{
	global $pdo;
	$stmt = $pdo->prepare('SELECT * FROM '.ALERT_TABLE_NAME.' WHERE alrt_rcvr = :username AND alrt_read = :read ORDER BY alrt_date DESC LIMIT 5');
	$stmt->execute(array(':username' => $username, ':read' => $read));
	$recentalrts = array();

	while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
	$recentalrts[] = $row;
	}
	return $recentalrts;
}


function new_msgs($username, $read)
{
	global $pdo;
	
	$stmt = $pdo->prepare('SELECT COUNT(*) 
	FROM '.MSGS_TABLE_NAME.' 
	WHERE msg_rcvr = :username AND msg_read = :read');

	$stmt->execute(array(':username' => $username, ':read' => $read));
	$num = $stmt->fetchColumn();	
}


function new_alerts($username, $read)
{
	global $pdo;
	
	$stmt = $pdo->prepare('SELECT COUNT(*) 
	FROM '.ALERT_TABLE_NAME.' 
	WHERE alrt_rcvr = :username AND alrt_read = :read');

	$stmt->execute(array(':username' => $username, ':read' => $read));
	$num = $stmt->fetchColumn();	
}


function delete_user($userid)
{
	global $pdo;
	$stmt = $pdo->prepare('
		DELETE FROM '.USERS_TABLE_NAME.'
		WHERE user_id = :userid');

	$stmt->execute( array(':userid' => $userid) );
	return true;
}


function delete_trans($trans)
{
	global $pdo;
	$stmt = $pdo->prepare('
		DELETE FROM '.TRANS_TABLE_NAME.'
		WHERE trans_id = :trans');

	$stmt->execute( array(':trans' => $trans) );
	return true;
}

function delete_alert($alrtid)
{
	global $pdo;
	$stmt = $pdo->prepare('
		DELETE FROM '.ALERT_TABLE_NAME.'
		WHERE alrt_id = :alrtid');

	$stmt->execute( array(':alrtid' => $alrtid) );
	return true;
}

function delete_msg($msgid)
{
	global $pdo;
	$stmt = $pdo->prepare('
		DELETE FROM '.MSGS_TABLE_NAME.'
		WHERE msg_id = :msgid');

	$stmt->execute( array(':msgid' => $msgid) );
	return true;
}

function delete_rply($msgid)
{
	global $pdo;
	$stmt = $pdo->prepare('
		DELETE FROM '.RPLY_TABLE_NAME.'
		WHERE msg_id = :msgid');

	$stmt->execute( array(':msgid' => $msgid) );
	return true;
}

function rply_delete($rplyid)
{
	global $pdo;
	$stmt = $pdo->prepare('
		DELETE FROM '.RPLY_TABLE_NAME.'
		WHERE rply_id = :rplyid');

	$stmt->execute( array(':rplyid' => $rplyid) );
	return true;
}

function delete_sms($smsid)
{
	global $pdo;
	$stmt = $pdo->prepare('
		DELETE FROM '.SMS_TABLE_NAME.'
		WHERE sms_id = :smsid');

	$stmt->execute( array(':smsid' => $smsid) );
	return true;
}

function addOrdinalNumberSuffix($num) {
    if (!in_array(($num % 100),array(11,12,13))){
      switch ($num % 10) {
        // Handle 1st, 2nd, 3rd
        case 1:  return $num.'st';
        case 2:  return $num.'nd';
        case 3:  return $num.'rd';
      }
    }
    return $num.'th';
}


function ip2location($ip)
{
    # api url
    $api = 'http://freegeoip.net/json/' . $ip;

    # connect api with curl
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $api);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
    $data = curl_exec($ch);
    curl_close($ch);

    # return reposed data
    return json_decode($data);
}

function generateStrongPassword($length = 9, $add_dashes = false, $available_sets = 'luds')
{
$sets = array();
if(strpos($available_sets, 'l') !== false)
$sets[] = 'abcdefghjkmnpqrstuvwxyz';
if(strpos($available_sets, 'u') !== false)
$sets[] = 'ABCDEFGHJKMNPQRSTUVWXYZ';
if(strpos($available_sets, 'd') !== false)
$sets[] = '23456789';
if(strpos($available_sets, 's') !== false)
$sets[] = '!@#$%&*?';
 
$all = '';
$password = '';
foreach($sets as $set)
{
$password .= $set[array_rand(str_split($set))];
$all .= $set;
}
 
$all = str_split($all);
for($i = 0; $i < $length - count($sets); $i++)
$password .= $all[array_rand($all)];
 
$password = str_shuffle($password);
 
if(!$add_dashes)
return $password;
 
$dash_len = floor(sqrt($length));
$dash_str = '';
while(strlen($password) > $dash_len)
{
$dash_str .= substr($password, 0, $dash_len) . '-';
$password = substr($password, $dash_len);
}
$dash_str .= $password;
return $dash_str;
}

    
function getRandomString($length)
{
    $validCharacters = "ABCDEFGHIJKLMNPQRSTUXYVWZ123456789";
    $validCharNumber = strlen($validCharacters);
    $result = "";

    for ($i = 0; $i < $length; $i++)
    {
        $index = mt_rand(0, $validCharNumber - 1);
        $result .= $validCharacters[$index];
    }
    return $result;
}

function get_transcode($digits){
	$pin = str_pad(rand(0, pow(10, $digits)-1), $digits, '0', STR_PAD_LEFT);

    return $pin;
}

function get_code1($acc)
{
	global $pdo;

	$stmt = $pdo->prepare('SELECT * FROM '.USERS_TABLE_NAME.' WHERE user_acc = :acc LIMIT 1');
	$stmt->execute(array(':acc' => $acc));

	if ($data = $stmt->fetch( PDO::FETCH_OBJ )) {
		# Return code
		$code = $data->user_code1;
		return $code;
	}
}

function get_code2($acc)
{
	global $pdo;

	$stmt = $pdo->prepare('SELECT * FROM '.USERS_TABLE_NAME.' WHERE user_acc = :acc LIMIT 1');
	$stmt->execute(array(':acc' => $acc));

	if ($data = $stmt->fetch( PDO::FETCH_OBJ )) {
		# Return code
		$code = $data->user_code2;
		return $code;
	}
}

function get_code3($acc)
{
	global $pdo;

	$stmt = $pdo->prepare('SELECT * FROM '.USERS_TABLE_NAME.' WHERE user_acc = :acc LIMIT 1');
	$stmt->execute(array(':acc' => $acc));

	if ($data = $stmt->fetch( PDO::FETCH_OBJ )) {
		# Return code
		$code = $data->user_code3;
		return $code;
	}
}

?>