<?php
include_once('config.php');

//instantiate system class
$sys		= new System();

//select user accounts for suspension checking
$userAccountsArray = array();
$userAccountsArray = $sys -> accessSelect('SELECT_ACTIVE_USERS_FOR_SUSPENSION_CHECKING', array());

//report filename
$deductListFileName = "Deducted List_" . date("Y-m-d") . ".csv"; //deduction report filename
$suspendListFileName = "Suspended List_" . date("Y-m-d") . ".csv"; //suspension report filename

//array container for report data
$reportArray = array();
$reportArray['data_deduct'] = NO_STRING; //deduction
$reportArray['data_suspend'] = NO_STRING; //suspension

/*********************************************START********************************************************/

//check for transaction
foreach($userAccountsArray as $userAccount){
    //select transactions per user account
    $transactionList = array();
    $transactionList = $sys -> accessSelect('LIST_USER_TRANSACTION_FOR_SUSPENSION_CHECKING', array($userAccount['user_account'],''));

    //if there is no transaction, suspend
    if(count($transactionList) < 1){
        //check if there is a last lift date and
        if($userAccount['last_lift_date'] != null && !isWithinPeriod(date("Y-m-d H:i:s"), $userAccount['last_lift_date'], 180)){
            //suspend
            $suspensionStatus = ($userAccount['status'] == '3') ? '7' : '6';
            suspendAccount($userAccount, $suspensionStatus);

            //put report data
            $reportArray['data_suspend'] .= $userAccount['user_account'] . "," . $userAccount['first_name'] . " " . $userAccount['last_name'] . "," . $userAccount['mail']  . ","
            . $userAccount['status'] . "," . $suspensionStatus . "," . date('Y-m-d') . "\n";
        } elseif($userAccount['last_lift_date'] == null){
            //suspend
            $suspensionStatus = ($userAccount['status'] == '3') ? '7' : '6';
            suspendAccount($userAccount, $suspensionStatus);

            //put report data
            $reportArray['data_suspend'] .= $userAccount['user_account'] . "," . $userAccount['first_name'] . " " . $userAccount['last_name'] . "," . $userAccount['mail']  . ","
            . $userAccount['status'] . "," . $suspensionStatus . "," . date('Y-m-d') . "\n";
        }
    } else {
        //boolean flag if there is a transaction within 180 days and now. initially set to false
        $hasTransaction = false;

        //check if there is a valid transaction
        $hasTransaction = isTransactionWithinPeriod($transactionList, $userAccount);

        //if there is no transaction
        if(!$hasTransaction){
            //deduct or suspend
            processAccountBalance($userAccount);
        }
    }
}

//generate csv files
//check if there is deduction data
if(strlen($reportArray['data_deduct']) > 0){
    generateReport($deductListFileName, $reportArray['data_deduct']);
}

//check if there is suspension data
if(strlen($reportArray['data_suspend']) > 0){
    generateReport($suspendListFileName, $reportArray['data_suspend']);
}

/*********************************************END********************************************************/


/*-------------------------------------------------------------------------
* @function_name: isWithinPeriod
* @parameter	: $later, $ealier; $period - period to compare with (in days)
* @return		: boolean true if within period in days else false
-------------------------------------------------------------------------*/
function isWithinPeriod($later, $earlier, $period){
    $dateDiff = computeDateDiff($later, $earlier);

    //if dateDiff is <= $period days
    if($dateDiff <= $period){
        return true;
    } else{
        return false;
    }
}

/*-------------------------------------------------------------------------
* @function_name: computeDateDiff
* @parameter	: $subtrahend, $subtractor
* @return		: boolean true if within period in days else false
-------------------------------------------------------------------------*/
function computeDateDiff($subtrahend, $subtractor){
    $dateDiff = strtotime($subtrahend) - strtotime($subtractor);
    $dateDiff = floor($dateDiff/86400); //divide to get the number of days

    return $dateDiff;
}

/*-------------------------------------------------------------------------
* @function_name: isTransactionWithinPeriod
* @parameter	: $transactionList, $userAccount
* @return		: boolean true if there is a within period of 180 days else false
-------------------------------------------------------------------------*/
function isTransactionWithinPeriod($transactionList, $userAccount){
    //check if there is last lift date
    if($userAccount['last_lift_date'] != null){
        $hasTransactionWithin180 = false;
        $hasTransactionAfterLift = false;

        //if there is last lift date, check if it not is between now and now-180
        if(!isWithinPeriod(date("Y-m-d H:i:s"), $userAccount['last_lift_date'], 180)){
            //check for any transactions within now and now - 180
            foreach($transactionList as $transaction){
                if(isWithinPeriod(date("Y-m-d H:i:s"), $transaction['transaction_time'], 180)){
                    $hasTransactionWithin180 = true;
                    break;
                }
            }

            //check for any transactions within 180 days after last lift date
            foreach($transactionList as $transaction){
                if(isWithinPeriod($transaction['transaction_time'], $userAccount['last_lift_date'], 180)){
                    $hasTransactionAfterLift = true;
                    break;
                }
            }
            //check if both has passed
            if($hasTransactionWithin180 && $hasTransactionAfterLift){
                return true;
            }
        } else{
            return true;
        }
    } else{
        //check for any transactions within now and now - 180
        foreach($transactionList as $transaction){
            if(isWithinPeriod(date("Y-m-d H:i:s"), $transaction['transaction_time'], 180)){
                return true;
            }
        }
    }

    return false;
}

/*-------------------------------------------------------------------------
* @function_name: processAccountBalance
* @parameter	: $userAccount
* @return		:
-------------------------------------------------------------------------*/
function processAccountBalance($userAccount){
    //define $sys and $reportArray as global variables
    global $sys, $reportArray;

    //set arameters for email
    $params = array();
    $params[] = $userAccount['user_account'];
    $params[] = $userAccount['first_name'] . " " . $userAccount['last_name'];
    $params[] = date("Y-m-d H:i:s");

    //set email language
    $language = ($userAccount['use_language'] != "") ? $userAccount['use_language'] : 'en';

    //deduction details string for email
    $deductionDetails = NO_STRING;

    //temporary string holder
    $tempString = NO_STRING;

    //get all balances
    $balances = array();
    $balances = $sys -> getBalanceListCommon($userAccount['user_account']);

    //fee
    $fee = 20;
    $feeInt = $sys -> currencyToInt($fee, USD);

    //check if there is a balance in USD
    if(isset($balances['USD'])){
        //check if USD is enough
        if(($balances['USD'] - $feeInt) >= 0){
            //deduct
            $tempString = deductInactiveFee($userAccount, 'USD', $feeInt);
            $deductionDetails .= $tempString;

            //parse $deductionDetails to get the transaction number
            $transactionNumber = getTransactionNumber($tempString);

            //put report data
            $reportArray['data_deduct'] .= $userAccount['user_account'] . "," . $userAccount['first_name'] . " " . $userAccount['last_name'] . "," . $userAccount['mail']
             . "," . $transactionNumber . ",USD," . $sys -> intToCurrency($feeInt, 'USD') . "," . date('Y-m-d') . "\n";

            //set deduction details for email
            $params[] = $deductionDetails;

            //send deduction email
            $sys -> sendMailByTmp($language.DIRECTORY_SEPARATOR.'inactive_deduction.xml'
                     , $params
                     , $userAccount['mail']
                     , VAR_CS_MAIL_ADDRESS);

            return;
        }
    }

    //define converted (to USD) currency array
    $convertedCurrencyBalances = array();

    //convert other currencies
    foreach ($balances as $key => $value) {
        if($key != 'USD'){
            $exchange	= $sys -> getExchangeCommon($value, $key, 'USD', true, false);
			$zeroDecimalCurrencies = $sys -> getZeroDecimalCurrenciesCommon();

            if(in_array($key,$zeroDecimalCurrencies)){
                $convertedCurrencyBalances[$key] = floor($sys -> getColumnData($exchange, PARAM_ORIGINAL_AMOUNT) * 100);
            } else {
                $convertedCurrencyBalances[$key] = floor($sys -> getColumnData($exchange, PARAM_ORIGINAL_AMOUNT));
            }
        } else{
            $convertedCurrencyBalances[$key] = $value;
        }
    }

    //check if all the converted amount is >= $feeInt
    if(array_sum($convertedCurrencyBalances) >= $feeInt){
        //check if there is USD currency in the balance
        if(isset($convertedCurrencyBalances['USD'])){
            //check first if there is remaining USD
            if($convertedCurrencyBalances['USD'] > 0){
                //deduct from remaining USD
                $feeInt -= $balances['USD'];

                $tempString = deductInactiveFee($userAccount, 'USD', $balances['USD']);
                $deductionDetails .= $tempString;

                //parse $deductionDetails to get the transaction number
                $transactionNumber = getTransactionNumber($tempString);

                //put report data
                $reportArray['data_deduct'] .= $userAccount['user_account'] . "," . $userAccount['first_name'] . " " . $userAccount['last_name'] . "," . $userAccount['mail']
                 . "," . $transactionNumber . ",USD," . $sys -> intToCurrency($balances['USD'], 'USD') . "," . date('Y-m-d') . "\n";
            }

            //unset USD
            unset($convertedCurrencyBalances['USD']);
        }

        //sort $convertedCurrencyBalances in desc order
        arsort($convertedCurrencyBalances);

        //after sorting deduct
        foreach($convertedCurrencyBalances as $key => $value){
            //check if there is still remaining fee
            if($feeInt > 0){
                if(($value - $feeInt) >= 0){
                    //convert fee currency
                    $exchange	= $sys -> getExchangeCommon($feeInt, 'USD', $key, true, false);
					$zeroDecimalCurrencies = $sys -> getZeroDecimalCurrenciesCommon();

                    if(in_array($key,$zeroDecimalCurrencies)){
                        $deductAmount = floor($sys -> getColumnData($exchange, PARAM_ORIGINAL_AMOUNT) / 100);
                    } else {
                        $deductAmount = floor($sys -> getColumnData($exchange, PARAM_ORIGINAL_AMOUNT));
                    }

                    //deduct
                    $tempString = deductInactiveFee($userAccount, $key, $deductAmount);
                    $deductionDetails .= $tempString;

                    //parse $deductionDetails to get the transaction number
                    $transactionNumber = getTransactionNumber($tempString);

                    //put report data
                    $reportArray['data_deduct'] .= $userAccount['user_account'] . "," . $userAccount['first_name'] . " " . $userAccount['last_name'] . "," . $userAccount['mail'] . ","
                    . $transactionNumber . "," .$key. "," . $sys -> intToCurrency($deductAmount, $key) . "," . date('Y-m-d') . "\n";
                    break;
                } else{
                    //get remaining fee
                    $feeInt -= $value;
                    //deduct
                    $tempString = deductInactiveFee($userAccount, $key, $balances[$key]);
                    $deductionDetails .= $tempString;

                    //parse $deductionDetails to get the transaction number
                    $transactionNumber = getTransactionNumber($tempString);

                    //put report data
                    $reportArray['data_deduct'] .= $userAccount['user_account'] . "," . $userAccount['first_name'] . " " . $userAccount['last_name'] . "," . $userAccount['mail'] . ","
                    . $transactionNumber . "," .$key. "," . $sys -> intToCurrency($balances[$key], $key) . "," . date('Y-m-d') . "\n";
                }
            } else{
                break;
            }
        }

        //set deduction details for email
        $params[] = $deductionDetails;

        //send deduction email
        $sys -> sendMailByTmp($language.DIRECTORY_SEPARATOR.'inactive_deduction.xml'
                 , $params
                 , $userAccount['mail']
                 , VAR_CS_MAIL_ADDRESS);

    } else{
        //suspend
        $suspensionStatus = ($userAccount['status'] == '3') ? '7' : '6';
        suspendAccount($userAccount, $suspensionStatus);

        //put report data
        $reportArray['data_suspend'] .= $userAccount['user_account'] . "," . $userAccount['first_name'] . " " . $userAccount['last_name'] . "," . $userAccount['mail'] . ","
        . $userAccount['status'] . "," . $suspensionStatus . "," . date('Y-m-d') . "\n";
    }
}

/*-------------------------------------------------------------------------
* @function_name: deductInactiveFee
* @parameter	: $userAccount
* @return		: $returnString
-------------------------------------------------------------------------*/
function deductInactiveFee($userAccount, $currency, $amount){
    //define $sys as global variable
    global $sys;

    //return string for deduction details
    $returnString = NO_STRING;

    $transactionNumber = $sys ->  registInactiveFeeCommon($userAccount['user_account']
                                    , $currency
                                    , $sys -> intToCurrency($amount, $currency)
                                    , VAR_TRANSACTION_DOMANT_FEE
                                    , 'Inactive Account Maintenance Fee'
                                    , VAL_INT_2
                                    );

    $amount = $sys -> intToCurrency($amount, $currency);

    //if JPY or PHP or IDR, remove decimal
    if(in_array($currency, $sys -> getZeroDecimalCurrenciesCommon())){
        $amount = floor($amount);
    }

    $returnString = "• " . $currency . " " . $amount . " (" . $transactionNumber . ") \n";

    return $returnString;
}

/*-------------------------------------------------------------------------
* @function_name: suspendAccount
* @parameter	: $userAccount
* @return		:
-------------------------------------------------------------------------*/
function suspendAccount($userAccount, $status){
    //define $sys as global variable
    global $sys;

    //set arameters for email
    $params = array();


    //set email language
    $language = (isset($userAccount['use_language']) && $userAccount['use_language'] != "") ? $userAccount['use_language'] : 'en';


    //check if user_account key exists
    if(isset($userAccount['user_account'])){
        //suspend account
        $sys -> accessModifyCommon('UPDATE_USER_STATUS_INACTIVE', array($userAccount['user_account'], $status));
    }

    //check if mail key exists
    if(isset($userAccount['mail'])){
        //send suspension email
        $sys -> sendMailByTmp($language.DIRECTORY_SEPARATOR.'inactive_suspension.xml'
                 , $params
                 , $userAccount['mail']
                 , VAR_CS_MAIL_ADDRESS);
    }
}

/*-------------------------------------------------------------------------
* @function_name: getTransactionNumber
* @parameter	: $string
* @return		:
-------------------------------------------------------------------------*/
function getTransactionNumber($string){
    $transactionNumber = NO_STRING;

    if(strlen($string) > 0) {
        $arrayContainer = explode("(", $string);
        $arrayContainer = explode(")", $arrayContainer[1]);
        $transactionNumber = $arrayContainer[0];
    }

    return $transactionNumber;
}

/*-------------------------------------------------------------------------
* @function_name: generateReport
* @parameter	: $fileName, $data
* @return		:
-------------------------------------------------------------------------*/
function generateReport($fileName, $data){
    $systemDocuments = SYSTEM_PATH.DIRECTORY_SEPARATOR.'documents';
    $deductionReportPath = $systemDocuments . DIRECTORY_SEPARATOR . 'deduction/';
    $suspensionReportPath = $systemDocuments . DIRECTORY_SEPARATOR . 'suspension/';

    //check if directory exists if not, create directory
    if(!file_exists($deductionReportPath)) {
        mkdir($deductionReportPath, 0777, true);
    }

    if(!file_exists($suspensionReportPath)) {
        mkdir($suspensionReportPath, 0777, true);
    }

    //check if filename submitted is for deduction or suspension
    if(strpos(strtolower($fileName), 'deducted') !== false){
        //create header data
        $header = "IWL No,Name,E-mail Address,Transaction Number,Currency,Amount,Date of Deduction" . "\n";

        //backup
        error_log(date("[Y-m-d H:i:s]")."\r\n Data:\r\n" . $header . $data . "\r\n", 3, $deductionReportPath.DIRECTORY_SEPARATOR.'Deduction_Log_'.date("Y-m-d").'.log');
        chmod($deductionReportPath.DIRECTORY_SEPARATOR.'Deduction_Log_'.date("Y-m-d").'.log',511);

        //csv file creation
        $file1 = fopen($deductionReportPath . $fileName, 'w+');
        $fwriteResult = fwrite($file1, $header . $data);
        fclose($file1);
        chmod($deductionReportPath . $fileName, 511);
    } else{
        //create header data
        $header = "IWL No,Name,E-mail Address,Previous Status,Current Status,Date Suspended" . "\n";

        //backup
        error_log(date("[Y-m-d H:i:s]")."\r\n Data:\r\n" . $header . $data . "\r\n", 3, $suspensionReportPath.DIRECTORY_SEPARATOR.'Suspension_Log_'.date("Y-m-d").'.log');
        chmod($suspensionReportPath.DIRECTORY_SEPARATOR.'Suspension_Log_'.date("Y-m-d").'.log',511);

        //csv file creation
        $file2 = fopen($suspensionReportPath . $fileName, 'w+');
        $fwriteResult = fwrite($file2, $header . $data);
        fclose($file2);
        chmod($suspensionReportPath . $fileName, 511);
    }
}
?>