<?php
define('thisscript', 'deposit');

require_once 'global.php';
require_once 'class/Deposit.php';
$deposit = new Deposit();

if (empty($userid)){
    redirecting("home");
}

/* if (empty($useraccess['manage_account_bank'])){
    redirecting('index.php');
} */

/* sanitize post, get, request */
$_POST['replayedit'] = ((empty($_POST['replayedit'])) ? "" : $_POST['replayedit']);
$_GET['getlist'] = ((empty($_GET['getlist'])) ? "" : $_GET['getlist']);
$_GET['keyword'] = ((empty($_GET['keyword'])) ? array() : $_GET['keyword']);
$_GET['field'] = ((empty($_GET['field'])) ? array() : $_GET['field']);
$_POST['cek'] = ((empty($_POST['cek'])) ? array() : $_POST['cek']);
$_POST['do'] = ((empty($_POST['do'])) ? "" : $_POST['do']);
$_GET['error'] = ((empty($_GET['error'])) ? "" : $_GET['error']);
$_GET['actions'] = ((empty($_GET['actions'])) ? "" : $_GET['actions']);
$_GET['act'] = ((empty($_GET['act'])) ? "" : $_GET['act']);
$_GET['page'] = ((empty($_GET['page'])) ? "" : $_GET['page']);
$_REQUEST['id'] = ((empty($_REQUEST['id'])) ? "" : $_REQUEST['id']);

/* end sanitize */

//$_GET['act'] = 'addnew';

if ($_POST['do'] == 'get_rate'){
	$amount = ((empty($_POST['amount'])) ? 0 : $_POST['amount']);
	
	$response = file_get_contents('https://bitpay.com/api/rates/idr');
	$bitcoin_amount = 0;
	$idr_amount = $transactionsetting['idr_rate'] * $amount;
	if (!empty($response)){
		$r = json_decode($response);
		if (!empty($r->rate)){
			$bitcoin_amount = $idr_amount / $r->rate;
			$bitcoin_amount = number_format($bitcoin_amount, 3);
		}
	}
	
	echo json_encode(array('bitcoin_amount' => $bitcoin_amount, 'idr_rate' => number_format($transactionsetting['idr_rate'], 0), 'idr_amount' => number_format($idr_amount, 0)));
	exit;
}

$curstatus['amount'] = '';
$curstatus['date'] = '';
$curstatus['notes'] = '';
$curstatus['files'] = '';
$curstatus['type'] = '';
$curstatus['account_id'] = '';
$curstatus['deposit_id'] = '';

$listtr = '';

$supportedfile = array(IMAGETYPE_JPEG => 'jpg', IMAGETYPE_PNG => 'png', IMAGETYPE_GIF => 'gif');

if (empty($general['showperpageadmin'])) {
    $general['showperpageadmin'] = 20;
}

$user->setId($userid);
$userdtl = $user->getUserDetail();
$isDeposit = $userdtl['deposit_status'] == 1?true:false;
$name = $userdtl['firstname'].' '.$userdtl['lastname'];

$pagelink = '';
$listr = '';
$listaction = '';
$pagenavs = '';

$row = $db->fetch_one("SELECT * FROM deposit WHERE userid='$userid' AND `type`='registration' AND status = 1");

$registered = false;
if (count($row)) {
    $registered = true;
}

if (!empty($_POST)) {
    $do = $_POST['do'];
    if ($do == "addDeposit") {
		$txt = '';
		if($isDeposit){
			$type = (empty($_POST['deposit_type'])) ? "" : $_POST['deposit_type'];
			$txt = '_'.$type;
		}
		else{
			$type = 'registration';
		}
		
        $amount = (empty($_POST['amount'.$txt])) ? "" : togglenumber($_POST['amount'.$txt], 'calculate');
        $date = (empty($_POST['date'])) ? "" : $_POST['date'];
        $notes = (empty($_POST['notes'])) ? "" : $_POST['notes'];
        $payment = (empty($_POST['payment'])) ? "" : $_POST['payment'];
        $amount_topup_reg = (empty($_POST['amount_topup_reg'])) ? "" : togglenumber($_POST['amount_topup_reg'], 'calculate');
        $status = 1;

        $filesname = '';
        if ($_FILES['files']['size'] > 0) {
            $filesname = $_FILES['files']['name'];
            $fileloc = $_FILES['files']['tmp_name'];
            $info = getimagesize($fileloc);
            if ($info) {
                if (!empty($supportedfile[$info[2]])) {
                    $extension = substr($filesname, strrpos($filesname, '.') + 1);
                    $k = 1;
                    while (file_exists("images/deposit/" . $filesname)) {
                        if (strrpos($filesname, "_")) {
                            $filesname = substr($filesname, 0, strrpos($filesname, "_")) . '.' . $extension;
                        }
                        $filesname = substr($filesname, 0, strrpos($filesname, ".")) . "_" . $k . '.' . $extension;
                        $k++;
                    }
                    $path = "images/deposit/" . $filesname;
                    copy($_FILES['files']['tmp_name'], $path);
                }
            }
        }
        /* print_r($_FILES['files']);exit; */
		
		$payment_detail = '';
		$user_bitcoin_account = '';
		if(!empty($payment)){
			$pay_db = $db->fetch_one("SELECT a.account_id, a.bank_id, b.bankname, a.rek_no, a.rek_name FROM account_bank a INNER JOIN bank b ON b.bank_id = a.bank_id WHERE account_id = '".$db->clean($payment)."'");
			$payment_from = 0;
			if(!empty($pay_db['account_id'])){
				$payment_detail = $pay_db['bankname'].' - '.$pay_db['rek_no'].(!empty($pay_db['rek_name'])?' a/n '.$pay_db['rek_name']:'');
				$payment_from = $pay_db['bank_id'];
			}
			
			if ($payment_from == 27){
				$user_bitcoin_account = empty($userdetail['bitcoin_acc']) ? '' : $userdetail['bitcoin_acc'];
			}
			else{
				if (!empty($userdetail['bank_id'])){
					$user_db = $db->fetch_one("SELECT bankname FROM bank WHERE bank_id = '".$db->clean($userdetail['bank_id'])."'");
					if (!empty($user_db['bankname'])){
						$user_bitcoin_account = $user_db['bankname'].(!empty($userdetail['bank_account'])?' - '.$userdetail['bank_account']:'').(!empty($userdetail['bank_account_name'])?' a/n '.$userdetail['bank_account_name']:'');
					}
				}
			}
		}
		
        $depositId  = $deposit->saveDeposit($amount, $date, $filesname, $notes, $status, $user_bitcoin_account, $payment_detail);
        $deposit->setType($depositId, $type);
         
		//===============Topup when registration package================
        if ($amount_topup_reg != 0){
        	$type = 'topup';
        	$amount = $amount_topup_reg;
			$depositId  = $deposit->saveDeposit($amount, $date, $filesname, $notes, $status, $user_bitcoin_account, $payment_detail);
			$deposit->setType($depositId, $type);
		}
		//============END Topup when registration package===============

        /* if ($userdetail['deposit_status'] == 0) { */
            //$deposit->saveDepositToUser();
        /* } */
		
		$mailcontent = "<div align=\"left\"><img src=\"".$general['siteurl']."images/logo.png\" border=\"0\"></div><br />"
						."There is a new deposit transaction. The details are as below : <br><br>"
						."<table width=\"100%\" cellpadding=\"0\" cellspacing=\"0\" border=\"0\">"
						."<tr><td width=\"20%\">Deposit Type</td><td width=\"1%\" align=\"center\">:</td><td width=\"79%\">".$deposit_type[$type]."</td></tr>"
						."<tr><td width=\"20%\">Amount</td><td width=\"1%\" align=\"center\">:</td><td width=\"79%\">$".number_format($amount, 2, $decimalseparator, $thousandseparator)."</td></tr>"
						."<tr><td width=\"20%\">Customer Name</td><td width=\"1%\" align=\"center\">:</td><td width=\"79%\">".$name."</td></tr>"
						."<tr><td width=\"20%\">Customer Email</td><td width=\"1%\" align=\"center\">:</td><td width=\"79%\">".$thisuseremail."</td></tr>"
						."<tr><td width=\"20%\">Deposit Date</td><td width=\"1%\" align=\"center\">:</td><td width=\"79%\">".$date."</td></tr>"
						."<tr><td width=\"20%\" valign=\"top\">Note</td><td width=\"1%\" align=\"center\" valign=\"top\">:</td><td width=\"79%\" valign=\"top\">".nl2br($notes)."</td></tr>"
						."</table>"
						.'<br />You can view and confirm this deposit transaction detail in <a href="'.$general['siteurl'].'managecp/admindepositdetail.php?deposit_id='.$depositId.'" target="_blank">'.$general['siteurl'].'managecp/admindepositdetail.php?deposit_id='.$depositId.'</a>';
						
		
		$headers = "Content-type: text/html; charset=iso-8859-1\r\n";
		$headers .= "From: ".$general['sitename']." <".$general['siteemail'].">";

		$subject = $general['sitename'] . ' - New Deposit Transaction';
		
		if ($emailsetting['enablesendmail']){
			mail($emailsetting['adminemail'], $subject, $mailcontent, $headers);
		}

        redirecting('deposit?act=addnew&msg=success');
    }
}

$amount = '';

$depositid = trim($_REQUEST['id']);
if (!empty($depositid)) {
    $deposit->setId($depositid);
    $curstatus = $deposit->getDepositDetail();
	if (empty($curstatus['deposit_id']) || $curstatus['userid'] != $userid){
		redirecting('home');
	}
	
	$amount = $curstatus['amount'];
    $curstatus['amount'] = empty($curstatus['amount']) ? 0 : number_format($curstatus['amount'], 2, $decimalseparator, $thousandseparator);
    $curstatus['date'] = empty($curstatus['date']) ? '-' : date('d-m-Y', strtotime($curstatus['date']));
    switch ($curstatus['status']) {
        case '1' :
            $status = 'Pending';
            break;
        case '2' :
            $status = 'Success';
            break;
        case '3' :
            $status = 'Reject';
            break;
    }

} else {

    $keywords = $_GET['keyword'];
    $fields = $_GET['field'];
    $alls = $deposit->searchDeposit($keywords, $fields, '', '', 'data', -1, 'member');
    $totalrows = sizeof($alls);
    $totalpgs = ceil($totalrows / $general['showperpage']);
    $pgs = handlepage($_GET['page'], $totalpgs);
    $dblast = $deposit->searchDeposit($keywords, $fields, '', '', 'data', $pgs, 'member');

    $pagenavs = generatepagelinkgeneral($pgs, $totalrows, $general['showperpage'], 'deposit', '', '');

    if (sizeof($dblast) > 0) {
        foreach ($dblast as $result) {
            $cstatus = '';
            switch ($result['status']) {
                case '1' :
                    $cstatus = 'Pending';
                    break;
                case '2' :
                    $cstatus = 'Success';
                    break;
                case '3' :
                    $cstatus = 'Reject';
                    break;
            }

            $listr .= '
					<tr>
						<td height="25" align="left">
						<a href="deposit?id=' . $result['deposit_id'] . '">' . $result['transaction_number'] . '</a></td>
						<td height="25" align="center">' . date('d M Y', strtotime($result['date'])) . '</td>
						<td height="25" align="right">
						' . number_format($result['amount'], 2, $decimalseparator, $thousandseparator) . '</td>
						<td height="25" align="center">
						' . htmlspecialchars($cstatus) . '</td>		
						<td height="25" align="center">
						<a href="deposit?id=' . $result['deposit_id'] . '"><i class="fa fa-search"></i></a></td>							
					</tr>
				';
        }
    } else {
        $listr = '<tr><td colspan="5" align="center">NO DATA</td></tr>';
    }
}

if ($userdetail['deposit_status'] == 0) {
    $curstatus['amount'] = number_format(300, 2, $decimalseparator, $thousandseparator);
}

$bitcoin_account = empty($userdetail['bitcoin_acc']) ? '' : $userdetail['bitcoin_acc'];

$now = date('d-m-Y');

$deposit_type_list = '';
if(sizeof($deposit_type) > 0){
	foreach($deposit_type as $key => $value){
		if($key != 'registration'){
			$deposit_type_list .= '<option value="'.$key.'"'.($curstatus['type'] == $key ? ' selected' : '').'>'.$value.'</option>';
		}
	}
}

$payment_list = '';
if (!empty($curstatus['deposit_id'])){
	$payment_list = $curstatus['bitcoin_account'];
}
else{
	$pay_db = $db->fetch_all("SELECT a.account_id, a.bankname, a.rek_no, a.rek_name, b.logo FROM account_bank a INNER JOIN bank b ON b.bank_id = a.bank_id WHERE a.status = 1 ORDER BY a.default_acc DESC, a.bankname ASC");
	if(sizeof($pay_db) > 0){
		foreach($pay_db as $row){
			$payment_list .= '
				<div class="radio">
					<label><input type="radio" name="payment" id="payment_'.$row['account_id'].'" value="'.$row['account_id'].'" class="payment-list"'.((empty($payment_list) && empty($depositid)) || $curstatus['account_id'] == $row['account_id']?' checked':'').(!empty($depositid)?' disabled':'').'>'.(!empty($row['logo'])?'<img src="'.$row['logo'].'" height="30">':$row['bankname']).' <br> <b>'.$row['rek_no'].'</b>'.(!empty($row['rek_name'])?' a/n <b>'.$row['rek_name'].'</b>':'').'</b></label>
					<div style="display:none; padding-left:21px;">Transfer Amount : <span class="transfer-amount" id="transfer-amount-'.$row['account_id'].'"></span></div>
				</div>
			';
		}
	}
}

require_once "incl/global_template.php";

$tmpl = gettemplate('deposit');
eval("\$template = \"$tmpl\";");
echo $template;

?>