<?php
error_reporting(0);
class Card {
    public $dp;

    private $url = "http://globesms.net/smshub/api.php";
    private $username = "mokamore";
    private $password = "more761";
    private $action = "sendsms";
    private $from = "moka%26more";
    private $dlr = 0;


    // set to true to bypass all validation
    private $debug = false;

    // how many USD are needed to get 1 point
    private $pointUsdValue = 3;

    function __construct() {
        $this->dp = new Db ( );
    }

    /***********************************
    ********** LOYALTY FUNCTIONS *******
    ************************************/
    public function purchasingpower($id, $token, $currency = 'lbp') {


        $currency = mysql_real_escape_string($currency);


        if (! $this->_isCardNumber ( $id ))
            return "Invalid Card";
        if ($this->_isCardExpired ( $id ))
            return "Card is expired";
        if (! $this->_isCardEnabled ( $id ))
            return "Card is disabled";
        if ($this->debug != true ) {
            if (! $this->_isTokenValid ( $token ))
                return "unauthorized request";
        }

        $sql = "SELECT Loyalty_balance FROM user WHERE MD5(Cardnumber)='$id'";
        $query = mysql_query ( $sql );
        $result = mysql_fetch_array ( $query );

        $loyalty_points = $result ['Loyalty_balance'];

        if ($loyalty_points < 30 ){
            return 'less than 30 points available';
        }

        $points_usd_equivalent = $loyalty_points / $this->pointUsdValue;
        $purchase_power = $this->convertLoyaltyToCurrency($points_usd_equivalent, $currency);


        $this->_killtoken ( $token );

        if ($purchase_power != false) {
            return $purchase_power;
        }
        else {
            return 'invalid currency';
        }

    }
    public function checkpointsbalance($id, $token) {
        $currency = mysql_real_escape_string($currency);


        if (! $this->_isCardNumber ( $id ))
            return "Invalid Card";
        if ($this->_isCardExpired ( $id ))
            return "Card is expired";
        if (! $this->_isCardEnabled ( $id ))
            return "Card is disabled";
        if ($this->debug != true ) {
            if (! $this->_isTokenValid ( $token ))
                return "unauthorized request";
        }

        $sql = "SELECT Loyalty_balance FROM user WHERE MD5(Cardnumber)='$id'";
        $query = mysql_query ( $sql );
        $result = mysql_fetch_array ( $query );


        $loyalty_points = $result ['Loyalty_balance'];
        $purchase_power = $loyalty_points;


        $this->_killtoken ( $token );

        if ($purchase_power != false) {
            return $purchase_power;
        }
        else {
            return false;
        }

    }

    // this function takes the invoice total and converts to points for the card number
    public function registerpoints($id, $pos, $employeeid, $amount, $token, $currency = 'lbp', $country_id='', $operation_id='' ) {

        if (! $this->_isCardNumber ( $id ))
            return "Invalid Card";
        if ($this->_isCardExpired ( $id ))
            return "Card is expired";
        if (! $this->_isCardEnabled ( $id ))
            return "Card is disabled";
        if (! $this->_isPos ( $pos ))
            return "invalid pos";
        if ($this->debug != true ) {
            if (! $this->_isTokenValid ( $token ))
                return "unauthorized request";
        }

        $amountUsd = $this->convertAmountFromCurrencyToUsd($amount,$currency);
        $pointsGained = $amountUsd / $this->pointUsdValue ;

        $unhashed_id = $this->_getCardIdFromHash ( $id );
        // modified to update user loyalty points
        $sql = "UPDATE user SET  Loyalty_Balance = Loyalty_Balance + $pointsGained WHERE MD5(Cardnumber)='$id'";

        $query = mysql_query ( $sql );
        $affected = mysql_affected_rows ();
        if ($affected){
            $result = $this->_logAction ( $unhashed_id, $pos, $employeeid, $amount, $amountUsd, $currency, $pointsGained, "add_points_from_invoice", $token, $country_id, $operation_id  );
            return $pointsGained;
        }else {
            $result = $this->_logAction ( $unhashed_id, $pos, $employeeid, $amount, $amountUsd,$currency,$pointsGained, "add_points_fail", $token , $country_id, $operation_id );
            return false;
        }


    }


    public function redeempoints($id, $pos, $employeeid, $amount, $token, $currency = 'lbp', $country_id='', $operation_id='' ) {

        if (! $this->_isCardNumber ( $id ))
            return "Invalid Card";
        if ($this->_isCardExpired ( $id ))
            return "Card is expired";
        if (! $this->_isCardEnabled ( $id ))
            return "Card is disabled";
        if (! $this->_isAvailablePointsBalance ( $id, $amount,$currency ))
            return "insufficient points";
        if (! $this->_isPos ( $pos ))
            return "invalid pos";
        if ($this->debug != true ) {
            if (! $this->_isTokenValid ( $token ))
                return "unauthorized request";
        }

        $id = $this->_getCardIdFromHash ( $id );
        $points_used = $this->reduce_points ( md5 ( $id ), $amount, $currency );

        $amountUsd = $this->convertAmountFromCurrencyToUsd($amount,$currency);

        if ($points_used) {
            $result = $this->_logAction ( $id, $pos, $employeeid, $amount, $amountUsd,$currency, $points_used, "redeem_points", $token, $country_id, $operation_id  );
            if ($result) {
                $last_four = substr ( $id, - 4, 4 );
                $loacation = $this->_getLocationFromPosId ( $pos );
                $date = date ( "Y-m-d", time () );
                $balance = number_format ( $this->_getbalance ( $id ) );
                $loyalty_balance = number_format ( $this->_getpoints ( $id ) );
                $phone = $this->_getPhoneNumber ( $id );
                $amount = number_format ( $amount );
                $this->_sendSMS ( $phone, "Dear moka%26more cardholder, a transaction was made on the $date, your points transaction amount is $points_used your new points balance is $loyalty_balance. Thank you for your visit.", $result );
                if(Card::_isRewardable($id)){
                    if(Card::_reward($id,7500)){
                        $result = $this->_logAction ( $id, $pos, $employeeid, "7500", '5', 'lbp', '', "refund", $token , $country_id, $operation_id );
                        $balance = number_format ( $this->_getbalance ( $id ) );
                        $this->_sendSMS ( $phone, "Dear moka%26more cardholder, a refund was made on the $date, your refund amount is 7500 LBP your new balance is $balance. Thank you for your visit.", $result );
                        return true;
                    }
                    else{
                        return false;
                    }
                }
                else{
                    return true;
                }
            } else {
                return false;
            }
        } else {
            return $points_used;
        }
    }







    /*****************************************
    ********** PREPAID CARD FUNCTIONS *******
    ****************************************/
    public function balance($id, $token, $currency='lbp') {
        $currency = mysql_real_escape_string($currency);


        if (! $this->_isCardNumber ( $id ))
            return "Invalid Card";
        if ($this->_isCardExpired ( $id ))
            return "Card is expired";
        if (! $this->_isCardEnabled ( $id ))
            return "Card is disabled";
        if ($this->debug != true ) {
            if (! $this->_isTokenValid ( $token ))
                return "unauthorized request";
        }

        $sql = "SELECT Balance FROM user WHERE MD5(Cardnumber)='$id'";
        $query = mysql_query ( $sql );
        $result = mysql_fetch_array ( $query );
        $balance = $result ['Balance'];
        $balance = $this->convertAmountToCurrency($balance,$currency);

        $this->_killtoken ( $token );
        return $balance;
    }


    public function buy($id, $pos, $employeeid, $amount, $token, $currency = 'lbp', $country_id='', $operation_id='' ) {
        $amountInUsd = $this->convertAmountFromCurrencyToUsd($amount,$currency);

        if (! $this->_isCardNumber ( $id ))
            return "Invalid Card";
        if ($this->_isCardExpired ( $id ))
            return "Card is expired";
        if (! $this->_isCardEnabled ( $id ))
            return "Card is disabled";
        if (! $this->_isAvailableBalance ( $id, $amountInUsd ))
            return "insufficient funds";
        if (! $this->_isPos ( $pos ))
            return "invalid pos";

        if ($this->debug != true ) {
            if (! $this->_isTokenValid ( $token ))
                return "unauthorized request";
        }



        $id = $this->_getCardIdFromHash ( $id );
        if ( $this->reduce ( md5 ( $id ), $amount, $currency )) {
            $result = $this->_logAction ( $id, $pos, $employeeid, $amount, $amountInUsd,$currency,'', "reduce", $token,$country_id, $operation_id );
            if ($result) {
                $last_four = substr ( $id, - 4, 4 );
                $loacation = $this->_getLocationFromPosId ( $pos );
                $date = date ( "Y-m-d", time () );
                $balance = number_format ( (double)$this->_getbalance ( $id ) );
                $loyalty_balance = number_format ( (double)$this->_getpoints ( $id ) );
                $phone = $this->_getPhoneNumber ( $id );
                $amount = number_format ( $amount );
                $this->_sendSMS ( $phone, "Dear moka%26more cardholder, a transaction was made on the $date, your transaction amount is $amount your new balance is $balance, you have gained $points_gained new points (total points $loyalty_balance). Thank you for your visit.", $result );
                if(Card::_isRewardable($id)){
                    if(Card::_reward($id,7500)){
                        $result = $this->_logAction ( $id, $pos, $employeeid, "7500",'5','lbp', "refund", $token , $country_id, $operation_id);
                        $balance = number_format ( $this->_getbalance ( $id ) );
                        $this->_sendSMS ( $phone, "Dear moka%26more cardholder, a refund was made on the $date, your refund amount is 7500 LBP your new balance is $balance, you have gained $points_gained new points (total points $loyalty_balance). Thank you for your visit.", $result );
                        return true;
                    }
                    else{
                        return false;
                    }
                }
                else{
                    return true;
                }
            } else {
                return false;
            }
        } else {
            return false;
        }
    }




    // this function takes the invoice total and converts to points for the card number
    public function addfunds($id, $amount, $token, $currency = 'lbp') {

        if (! $this->_isCardNumber ( $id ))
            return "Invalid Card";
        if ($this->_isCardExpired ( $id ))
            return "Card is expired";
        if (! $this->_isCardEnabled ( $id ))
            return "Card is disabled";
        if ($this->debug != true ) {
            if (! $this->_isTokenValid ( $token ))
                return "unauthorized request";
        }

        $amountUsd = $this->convertAmountFromCurrencyToUsd($amount,$currency);

        $unhashed_id = $this->_getCardIdFromHash ( $id );
        // modified to update user loyalty points
        $sql = "UPDATE user SET  Balance = Balance + $amount WHERE MD5(Cardnumber)='$id'";

        $query = mysql_query ( $sql );
        $affected = mysql_affected_rows ();
        if ($affected){
            $result = $this->_logAction ( $unhashed_id, $pos, $employeeid, $amount, $amountUsd,$currency, '' , "add_funds", $token );
            return true;
        }else {
            $result = $this->_logAction ( $unhashed_id, $pos, $employeeid, $amount, $amountUsd,$currency ,'', "add_funds_fail", $token );
            return false;
        }


    }

    public function convertLoyaltyToCurrency($points_in_usd, $currency){
        $currency = mysql_real_escape_string($currency);

        $rate_to_usd = $this->getCurrencyRateToUsd($currency);
        if ($rate_to_usd != false) {
            $points = (float)$points_in_usd * (float)$rate_to_usd;
            return $points;
        }
        else {
            return false;
        }
    }

    // takes currency and conevrts it to usd
    public function getCurrencyRateToUsd($currency){
        $currency = mysql_real_escape_string($currency);
        $currency = strtolower($currency);
        $sql = "SELECT rate_to_usd FROM currencies WHERE currency='$currency'";
        $query = mysql_query ( $sql );
        $result = mysql_fetch_array ( $query );

        if ($result) {
            return $result ['rate_to_usd'];
        } else {
            return false;
        }
    }

    // takes country id and gets its rate to usd
    public function getCountryRateToUsd($country_id){
        $country_id = (int)$country_id;
        $sql = "SELECT rate_to_usd FROM country WHERE id='$country_id'";
        $query = mysql_query ( $sql );
        $result = mysql_fetch_array ( $query );


        return $result ['rate_to_usd'];
    }

    public function convertAmountToCountryCurrency($amount, $country_id){

        if ($country_id != 0 && is_numeric($country_id )) {
            $rate_to_usd = $this->getCountryRateToUsd($country_id);
            $amount = (float)$amount * (float)$rate_to_usd;
        }

        return $amount;
    }

    public function convertAmountToCurrency($amount, $currency){

        $rate_to_usd = $this->getCurrencyRateToUsd($currency);
        $amount = (float)$amount * (float)$rate_to_usd;

        return $amount;
    }

    public function convertAmountFromCountryCurrencyToUsd($amount, $country_id){
        if ($country_id != 0 && is_numeric($country_id )) {
            $rate_to_usd = $this->getCountryRateToUsd($country_id);
            $amount = (float)$amount / (float)$rate_to_usd;
        }

        return $amount;
    }

    // takes the 3digit standard currency code and converts to usd
    public function convertAmountFromCurrencyToUsd($amount, $currency){

        $rate_to_usd = $this->getCurrencyRateToUsd($currency);
        $amount = (float)$amount / (float)$rate_to_usd;


        return $amount;
    }

    public function _getbalance($id) {
        $sql = "SELECT Balance FROM user WHERE Cardnumber='$id'";
        $query = mysql_query ( $sql );
        $result = mysql_fetch_array ( $query );
        $balance = $result ['Balance'];
        return $balance;
    }

    public function _getpoints($id) {
        $sql = "SELECT Loyalty_balance FROM user WHERE Cardnumber='$id'";
        $query = mysql_query ( $sql );
        $result = mysql_fetch_array ( $query );
        $balance = $result ['Loyalty_balance'];

        return $balance;
    }

    private function reduce($id, $amount, $currency= 'lbp') {
        $amountInUsd = $this->convertAmountFromCurrencyToUsd($amount,$currency);
        if ($this->debug != true ) {
            if (! $this->_isCardNumber ( $id ))
                return "Invalid Card";
            if ($this->_isCardExpired ( $id ))
                return "Card is expired";
            if (! $this->_isCardEnabled ( $id ))
                return "Card is disabled";
            if (! $this->_isAvailableBalance ( $id, $amountInUsd ))
                return "insufficient funds";
        }

        $amountUsd = $this->convertAmountFromCurrencyToUsd($amount,$currency);

        //        $sql = "UPDATE user SET Balance = Balance - $amountUsd WHERE MD5(Cardnumber)='$id'";

        // modified to update user loyalty points
        $sql = "UPDATE user SET Balance = Balance - $amountUsd WHERE MD5(Cardnumber)='$id'";
        $query = mysql_query ( $sql );
        $affected = mysql_affected_rows ();
        if ($affected){
            return true;
        }
        else {
            return false;
        }
    }
    private function reduce_points($id, $amount, $currency = 'lbp') {

        if ($this->debug != true ) {
            if (! $this->_isCardNumber ( $id ))
                return "Invalid Card";
            if ($this->_isCardExpired ( $id ))
                return "Card is expired";
            if (! $this->_isCardEnabled ( $id ))
                return "Card is disabled";
        }


        if ( $this->_isAvailablePointsBalance ( $id, $amount,$currency ) == false){
            return "insufficient points";
        }


        $amountUsd = $this->convertAmountFromCurrencyToUsd($amount,$currency);

        $pointsUsed = $amountUsd * $this->pointUsdValue ;

        //        $sql = "UPDATE user SET Balance = Balance - $amountUsd WHERE MD5(Cardnumber)='$id'";

        // modified to update user loyalty points
        $sql = "UPDATE user SET  Loyalty_Balance = Loyalty_Balance - $pointsUsed WHERE MD5(Cardnumber)='$id'";
        $query = mysql_query ( $sql );
        $affected = mysql_affected_rows ();
        if ($affected){
            if ($pointsUsed) {
                return $pointsUsed;
            }else {
                return true;
            }
        }
        else {
            return false;
        }
    }

    private function _reward($id,$amount){
        $sql = "UPDATE user SET Balance=(Balance+$amount) WHERE Cardnumber='$id'";
        $query = mysql_query ( $sql );
        $affected = mysql_affected_rows ();
        if ($affected)
            return true;
        else
            return false;
    }



    //	protected function isauthorized($id){
    //		if(!$this->_isCardNumber($id)) return "Invalid Card";
    //		if($this->_isCardExpired($id)) return "Card is expired";
    //		if(!$this->_isCardEnabled($id)) return "Card is disabled";
    //		return true;
    //	}


    //	public function getgeneratetoken(){
    //		$token = md5($key);
    //		$token .= md5("x");
    //		$token .= md5($secret);
    //		$token .= md5("y");
    //		$token .= md5(time());
    //
    //		$referer = $_SERVER['HTTP_REFERER'];
    //		$sql = "INSERT INTO token VALUES('','$token','','$referer')";
    //		$query = mysql_query($sql);
    //		if(mysql_affected_rows()){
    //			return $token;
    //		}
    //		else{
    //			return "unauthorized request";
    //		}
    //	}


    public function generatetoken() {
        $now = time ();
        $half = strlen ( $now ) / 2;
        $left = substr ( $now, 0, $half );
        $right = substr ( $now, $half );
        $thgir = strrev ( $right );
        $tfel = strrev ( $left );
        $newnow = "$tfel$thgir";
        $token = md5 ( $newnow );
        $referer = $_SERVER ['HTTP_REFERER'];
        $sql = "INSERT INTO tokens VALUES('','$token','$now','60','0','$referer')";

        $query = mysql_query ( $sql );
        if (mysql_affected_rows ()) {
            return $now;
        } else {
            return "invalid request";
        }
    }

    private function _sendSMS($to, $text, $transaction_id) {
        $query_string = "username=$this->username&password=$this->password&action=$this->action&from=$this->from&to=$to&dlr=$this->dlr&text=$text";
        $c = curl_init ( $this->url );
        curl_setopt ( $c, CURLOPT_POSTFIELDS, "username=$this->username&password=$this->password&action=$this->action&from=$this->from&to=$to&dlr=$this->dlr&text=$text" );
        curl_setopt ( $c, CURLOPT_RETURNTRANSFER, 1 );
        $result = curl_exec ( $c );
        curl_close ( $c );
        if (ereg ( "OK: 1", $result )) {
            $this->_logSMS ( $this->url . "?" . $query_string, $result, $transaction_id );
            return true;
        } else {
            return false;
        }

    }

    private function getCurrencyId($currency) {
        $sql = "SELECT id FROM currencies WHERE currency='$currency'";
        $query = mysql_query ( $sql );
        $row = mysql_fetch_array ( $query );
        if ($row) {
            return $row ['id'];
        }else {
            return 0;
        }
    }

    private function _getPhoneNumber($id) {
        $sql = "SELECT Phone FROM user WHERE Cardnumber='$id'";
        $query = mysql_query ( $sql );
        $row = mysql_fetch_array ( $query );
        return $row ['Phone'];
    }

    private function _logSMS($request, $response, $trans_id) {
        $sql = "INSERT INTO sms_log VALUES('','$request','$response','$trans_id')";
        $query = mysql_query ( $sql );
        $numrow = mysql_affected_rows ();
        if ($numrow) {
            return true;
        } else {
            return false;
        }
    }
    private function _isTokenValid($token) {
//roy
//        $sql = "UPDATE tokens SET expired='0' WHERE token='$token'";
//        $query = mysql_query ( $sql );
//        return true;


        $sql = "SELECT COUNT(*) FROM tokens WHERE token='$token' AND expired='0'";

        $query = mysql_query ( $sql );
        $result = mysql_fetch_array ( $query );
        $count = $result [0];
        if (! $count)
            return false;
        else {
            if ($this->_isTokenAlive ( $token ))
                return true;
            else
                return false;
        }
    }

    private function _isTokenAlive($token) {
        $sql = "SELECT * FROM tokens WHERE token='$token'";
        $query = mysql_query ( $sql );
        $result = mysql_fetch_array ( $query );
        if ($result ['expired'])
            return false;
        else {
            $timestamp = $result ['timestamp'];
            $ttl = $result ['ttl'];
            $max_alive = $timestamp + $ttl;
            $now = time ();

            if ($now > $max_alive) {
                $this->_killtoken ( $token );
                return false;
            } else
                return true;
        }
    }

    private function _killtoken($token) {
        $sql = "UPDATE tokens SET expired='1' WHERE token='$token'";
        $query = mysql_query ( $sql );
        if (mysql_affected_rows ())
            return true;
        else
            return false;
    }

    private function _isTokenForTransaction($transid, $token) {
        $sql = "SELECT COUNT(*) FROM token WHERE Token='$token' AND MD5(Transaction_id)='$transid'";
        $query = mysql_query ( $sql );
        $result = mysql_fetch_array ( $query );
        $count = $result [0];
        if (! $count)
            return false;
        else
            return true;
    }

    private function _disabletoken($transid, $token) {
        $sql = "UPDATE token SET Transaction_id='$transid' WHERE token='$token'";
        $query = mysql_query ( $sql );
        if (mysql_affected_rows ())
            return true;
        else
            return false;
    }

    private function _logAction($id='', $machine='', $employeeid='', $amount='', $amount_usd='', $currency='', $loyalty_points='', $action='', $token='',$country_id='', $operation_id='') {

        $currency_id = $this->getCurrencyId($currency);

        $now = time ();
        $sql = "INSERT INTO transaction VALUES('','$now','$id','$machine','$employeeid', '$country_id', '$operation_id', '$amount', '$amount_usd', '$currency_id', '$loyalty_points','$action')";

        $query = mysql_query ( $sql );
        $numrow = mysql_affected_rows ();
        if ($numrow) {
            $mysql_insert_id = mysql_insert_id ();
            if (! $this->_killtoken ( $token )){
                return false;
            }
            else {
                return $mysql_insert_id;
            }
        } else{
            return false;
        }
    }
    //
    //	private function _isDiscoutable($id){
    //		$lastmonth = mktime(0, 0, 0, date("m")-1, date("d"),   date("Y"));
    //		$sql = "SELECT SUM(Amount) AS sum FROM transaction WHERE Card_id = '$id' AND transaction.Date > '$lastmonth' AND Action='reduce'";
    //		$query = mysql_query($sql);
    //		$row = mysql_fetch_array($query);
    //		$sum = $row['sum'];
    //		if($sum > 150000) return 1;
    //		else return 0;
    //	}

    private function _isRewardable($id){
        $lastmonth = mktime(0, 0, 0, date("m")-1, date("d"),   date("Y"));
        $sql = "SELECT * FROM transaction WHERE Card_id = '$id' AND transaction.Date > '$lastmonth' ORDER BY transaction.Date ASC";
        $query = mysql_query($sql);
        $acc = 0;
        while ($row = mysql_fetch_array($query)) {
            if($row['Action'] == "reduce"){
                $acc = $acc + $row['Amount'];
            }
            else{
                $acc = 0;
            }
        }
        if($acc > 150000){
            return 1;
        }
        else{
            return 0;
        }
    }

    //ALTER TABLE `transaction` ADD `Employee_id` VARCHAR( 255 ) NOT NULL AFTER `Pos_id`
    //	private function _logAction($id,$machine,$amount,$action,$token){
    //		$now = time();
    //		$sql = "INSERT INTO transaction VALUES('','$now','$id','$machine','$amount','$action')";
    //		$query = mysql_query($sql);
    //		$numrow = mysql_affected_rows();
    //		if($numrow){
    //			$mysql_insert_id = mysql_insert_id();
    //			if(!$this->_killtoken($token)) return false;
    //			if($action == "reduce"){
    //				$response = array();
    //				$response['status'] = "true";
    //				$response['order'] = $mysql_insert_id;
    //				$response['token'] = $token;
    //				return $response;
    //			}
    //			else return true;
    //		}
    //		else return false;
    //	}


    private function _isPos($id) {
        $sql = "SELECT COUNT(*) FROM pos WHERE Machineid='$id'";
        $query = mysql_query ( $sql );
        $result = mysql_fetch_array ( $query );
        $count = $result [0];
        if (! $count)
            return false;
        else
            return true;
    }

    private function _getCardIdFromHash($hash) {
        $sql = "SELECT Cardnumber FROM user WHERE MD5(Cardnumber) = '$hash'";
        $query = mysql_query ( $sql );
        $row = mysql_fetch_array ( $query );
        $id = $row ['Cardnumber'];
        return $id;
    }

    private function _isTransaction($id) {
        $sql = "SELECT COUNT(*) FROM transaction WHERE MD5(id)='$id'";
        $query = mysql_query ( $sql );
        $result = mysql_fetch_array ( $query );
        $count = $result [0];
        if (! $count)
            return false;
        else
            return true;
    }

    private function _isAvailableBalance($id, $amount) {
        $sql = "SELECT Balance FROM user WHERE MD5(Cardnumber)='$id'";
        $query = mysql_query ( $sql );
        $result = mysql_fetch_array ( $query );
        $balance = $result ['Balance'];
        if ($balance >= $amount)
            return true;
        else
            return false;
    }

    private function _isAvailablePointsBalance($id, $amount, $currency) {

        $purchasingpower = $this->purchasingpower($id,$token,$currency);

        if ($amount > $purchasingpower) {
            return false;
        }
        else {
            return true;
        }
    }

    private function _isCardNumber($id) {
        $sql = "SELECT COUNT(*) FROM user WHERE MD5(Cardnumber)='$id'";

        $query = mysql_query ( $sql );
        $result = mysql_fetch_array ( $query );


        $count = $result [0];
        if (! $count)
            return false;
        else
            return true;
    }

    private function _isCardEnabled($id) {
        $sql = "SELECT Status FROM user WHERE MD5(Cardnumber)='$id'";
        $query = mysql_query ( $sql );
        $result = mysql_fetch_array ( $query );
        $status = $result ['Status'];
        if (! $status)
            return false;
        else
            return true;
    }

    private function _isCardExpired($id) {
        $now = time ();
        $sql = "SELECT Expdate FROM user WHERE MD5(Cardnumber)='$id'";
        $query = mysql_query ( $sql );
        $result = mysql_fetch_array ( $query );
        $sqlexpdate = $result ['Expdate'];
        $expdate = strtotime ( $sqlexpdate );
        if ($now > $expdate)
            return true;
        else
            return false;
    }

    private function _getLocationFromPosId($id) {
        $sql = "SELECT location.Location FROM pos LEFT JOIN location ON pos.Location_id=location.id WHERE pos.MachineId='$id'";
        $query = mysql_query ( $sql );
        $row = mysql_fetch_array ( $query );
        return $row ['Location'];
    }



}