<?php

/*
 *
 * MARKETPLACE - WITHDRAW
 * EXECUTE WITHDRAW FOR A LIST OF MKP ACCOUNTS
 *
 */
 
// Utility functions
require_once("../shared/functions.php");

// Classes API Wallet Cash-out
require("ScanMarketplace.class.php");

$updated = $error = $ignored = 0;

if(isset($_GET['debug']) && $_GET['debug'] > 0) { $debug = $_GET['debug']; }
else $debug = 0;

if(isset($_POST['MerchantID']) && $_POST['MerchantID'] > 0) {
    $MerchantID = (int) $_POST['MerchantID'];
}
else $MerchantID = 0;

// Initialize Class
$ScanMarketplace = new ScanMarketplace($MerchantID);
$ScanMarketplace->debug = $debug;
if($debug) { echo 'ScanMarketplace'; krumo($ScanMarketplace); }

$AllAccounts = array();

if(isset($_POST['action']) && $MerchantID && $_POST['SelectedAccounts']) {
    
    $SelectedAccounts = explode("\r\n", $_POST['SelectedAccounts']);
    if(is_array($SelectedAccounts) && count($SelectedAccounts)) {
        foreach($SelectedAccounts as $key => $AccountID) {
            $AccountID = (int) trim($AccountID);

            if($AccountID) {
                $balance = $ScanMarketplace->getBalance($AccountID);

                if(isset($balance) && isset($balance->amount) && $balance->amount) {
                    $AllAccounts[$AccountID] = new StdClass();
                    $AllAccounts[$AccountID]->balance = $balance;
                }
            }
        }
    }


}

?>
<html lang="en">
    <head>
        <meta http-equiv="Content-type" content="text/html; charset=utf-8">
        <meta charset="utf-8">
        <title>Withdraw | Marketplace</title>
        <link rel="icon" type="image/png" href="images/bank.png" />

        <script src="//code.jquery.com/jquery-3.1.0.min.js" integrity="sha256-cCueBR6CsyA4/9szpPfrX3s49M9vUU5BgtiJj06wt/s=" crossorigin="anonymous"></script>
        <script src="//code.jquery.com/ui/1.12.1/jquery-ui.min.js" integrity="sha256-VazP97ZCwtekAsvgPBSUwPFKdrwD3unUfSGVYrahUqU=" crossorigin="anonymous"></script>

        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css" />

        <!-- Latest compiled and minified CSS -->
        <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
		<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.4/css/bootstrap-select.min.css">

        <!-- Optional theme -->
        <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

        <!-- Latest compiled and minified JavaScript -->
        <script src="//cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" crossorigin="anonymous"></script>
        <script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
		<script src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.4/js/bootstrap-select.min.js"></script>


        <style>
            .ui-autocomplete {
                z-index: 100;
            }
            .loader {
                display: none;
                border: 5px solid #f3f3f3;
                -webkit-animation: spin 1s linear infinite;
                animation: spin 1s linear infinite;
                border-top: 5px solid #555;
                border-radius: 50%;
                width: 50px;
                height: 50px;
            }

            @keyframes spin {
                0% { transform: rotate(0deg); }
                100% { transform: rotate(360deg); }
            }

            .balance {
                width:120px;
                text-align: right;
            }
        </style>

        <script>
            $(function() {
                $( 'button.submit' ).click(function() {
                    $(this).parent().parent().submit();
                });


                $('[data-toggle="tooltip"]').tooltip()

                $( '.hideAccount').click(function(){
                    var AccountID = $(this).attr("data-account-id");
                    if(AccountID > 0) {
                        $("tr[data-account-id="+AccountID+"]").remove();
                    }
                });

                $( '.withdrawAccount').click(function(){
                    var MerchantID = $('#MerchantID').val();
                    var AccountID = $(this).attr("data-account-id");
                    var TotalAmount = $(this).attr("data-amount");

                    if(AccountID > 0) {
                        var Amount = $('#Balance_'+AccountID).val();
                        Withdrawal(MerchantID, AccountID, Amount);
                    }
                });

                $( '.withdrawAllAccounts').click(function(e){

                    var MerchantID = $('#MerchantID').val();
                    $( "#AccountList tr" ).each(function( index ) {
                        var AccountID = $(this).attr("data-account-id");

                        if(AccountID > 0) {
                            var Amount = $('#Balance_'+AccountID).val();
                            Withdrawal(MerchantID, AccountID, Amount);
                        }
                    });
                 });

                $( '.hideEmptyBalance').click(function(e){

                    $( "#AccountList tr" ).each(function( index ) {
                        var AccountID = $(this).attr("data-account-id");

                        if(AccountID > 0) {
                            var Amount = $('#Balance_'+AccountID).val();
                            
                            if(Amount <= 0) {
                                $("tr[data-account-id="+AccountID+"]").remove();
                            }
                        }
                    });
                });
                 
            });

            function Withdrawal(MerchantID, AccountID, Amount) {

                $.ajax({
                    url: "Withdrawal.ajax.php",
                    method: "POST",
                    data: { MerchantID: MerchantID, AccountID: AccountID, Amount: Amount },
                    cache: false,
                    async: true // wait for previous call to complete before executing the next withdrawal

                    
                }).done(function(data) {
                    console.log("Withdraw "+AccountID+" launched"+data);
                        console.log(data);
                        //

                        if(data.message === null || data.message === undefined) { data.message = ''; }
                        if(data.detail === null || data.detail === undefined) { data.detail = ''; }

                        if(data.code !== null && data.code !== undefined) {
                            var message = data.message;

                            if(data.code == 0) {
                                $("tr[data-account-id="+AccountID+"]").remove();
                            }
                        }
                        else {
                            var message = data;
                            data.code = 'X';
                        }

                        $('#WithdrawalResult > tbody').prepend("<tr><td>"+AccountID+"</td><td>"+data.code+"</td><td>"+message+"</td><td>"+data.detail+"</td></tr>");
                }).fail(function(data) {
                    console.log(data);
                    alert( "Error on ajax call" );
                });
            }

        </script>

    </head>
    <body>

         <div class="container">
         <?php if(isset($display_result)) { ?>
            <div class="alert alert-warning" role="alert"><?=$display_result?></div>
         <?php } ?>

            <h2>Marketplace Manual Withdraw</h2>
            <div class="well well-sm" style="width:620px;">Select marketplace and Paste the Wallet accounts (1 account ID per line).<br /><b>Warning, do NOT paste User Space ID</b>.<br /><br />
            You <b>must</b> get a <b>written approval from the operator</b> before executing this action.</div>
            <div class="row">
            <form method="post" action="">
                <div class="form-group">
                    <label for="MerchantID">Choose ScanMarketplace</label>
                    <?php
                        $ScanMarketplace->ListMerchants();
						if(is_array($ScanMarketplace->Merchants)) {
					?>
							<select name="MerchantID" id="MerchantID" class="selectpicker">
                                <option></option>
					<?php 
							foreach($ScanMarketplace->Merchants as $Merchant) {
                                echo "<option value='$Merchant->ID'";
                                if($Merchant->ID == $MerchantID) echo " selected='selected'";
                                echo ">$Merchant->Marketplace ($Merchant->API_ENV)</option>";
							}
					?>
							</select>
					<?php		
						}
					?>
                </div>
				<div class="form-group">
                    <label for="SelectedAccounts">Paste Account ID List</label>
					<textarea name="SelectedAccounts" rows="12" class="form-control" style="width:350px;"><?php echo @$_POST['SelectedAccounts']; ?></textarea>
				</div>
                <div class="form-group">
                    <input type="hidden" name="action" value="check" />
                    <button type="button" class="btn btn-info submit"><span class="glyphicon glyphicon-search"></span> Check Balance</button>
                </div>
            </form>
            </div>

<?php
if(count($AllAccounts)) {
?>
    <script type="text/javascript">
        window.history.forward();
        window.onload = function()
        {
        window.history.forward();
        };

        window.onunload = function() {
        null;
        };
    </script>
    <h2>List of Accounts found with a positive balance</h2>
        <form method="post" action=""><!--  class="form-inline" -->
            <table class="table" id="AccountList">
                <thead>
                    <tr>
                    <th scope="col">#</th>
                    <th scope="col">Account ID</th>
                    <th scope="col">Balance</th>
                    <th scope="col" colspan="2">Actions</th>
                    </tr>
                </thead>
                <tbody>
<?php
    $i=0;
    foreach($AllAccounts as $AccountID => $Account) {
?>
            <tr data-account-id='<?=$AccountID?>'>
                <td scope="row"><?=$i?></td>
                <td><?=$AccountID?></td>
                <td><input class="balance"  type="text" name="Balance[<?=$AccountID?>]" id="Balance_<?=$AccountID?>" value="<?=$Account->balance->amount?>" /> <?=$Account->balance->currency?></td>
                <td><a href="javascript:void(0);" class="withdrawAccount" data-account-id='<?=$AccountID?>' data-amount='<?=$Account->balance->amount?>'>withdraw</a></td>
                <td><a href="javascript:void(0);" class="hideAccount" data-account-id='<?=$AccountID?>'>hide</a></td>
            </tr>
<?php $i++; } ?>

                </tbody>
                </table>

                <div class="row">
                    <button type="button" class="btn btn-success withdrawAllAccounts"><span class="glyphicon glyphicon-retweet"></span> Withdraw All</button>
                    <button type="button" class="btn btn-warning hideEmptyBalance"><span class="glyphicon glyphicon-filter"></span> Hide empty balance</button>
                </div>

            <h2>Withdraw Result</h2>

            <div class="well well-sm" style="width:620px;">This list will be filled after each withdraw attempt. <b>Do not forget to save it</b>, it will be lost as soon as you close or leave this page.</div>

            <table class="table" id="WithdrawalResult">
                <thead>
                    <tr>
                    <th scope="col">Account ID</th>
                    <th>Code</th>
                    <th>Message</th>
                    <th>Reason</th>
                    </tr>
                </thead>
                <tbody>
                </tbody>
                </table>

        </form>
<?php
} 
?>

        </div>
        
    </body>
</html>