<?php
require_once('session.php');
$externalPlayerId = $_GET['extplayer'];
$provider = $_GET['vendor'];

  $getPlayer = mysqli_query($conn,"SELECT * FROM `tb_ppplayer` WHERE externalPlayerId = '$externalPlayerId' AND status = 1 AND provider = '$provider'") or die(mysqli_error());
  $gp = mysqli_fetch_array($getPlayer);
  $providernya = $gp['provider'];
  $balance = $gp['balance'];
  $usersID = $gp['userID'];

  $kode_unik = substr(str_shuffle(1234567890),0,3);
  $kd_transaksi = date('Ymds').$kode_unik;
  $requestID = substr(str_shuffle('abcdefghijklmnopqrstuvwxyz123456789'),0,8);
  $requestIDD = $requestID.date('s');
  $created_date = date('Y-m-d H:i:s');

  $sql_provider = mysqli_query($conn,"SELECT * FROM `tb_tripayapi` WHERE provider = '$providernya'") or die(mysqli_error());
  $sp = mysqli_fetch_array($sql_provider);
  $urlRequest = $sp['urlRequest'];
  $gameUrl = $sp['urlResponse'];
  $secureLogin = $sp['api_key']; //apiKey
  $secretKey = $sp['secret_key']; //brandID

  $catatan = $providernya.' Transfer Back';

  if($providernya == 'PragmaticPlay'){
    $params = 'externalPlayerId='.$externalPlayerId.'&secureLogin='.$secureLogin.$secretKey;
    $hashNeed = md5($params);
    $curl = curl_init();
                                                
    curl_setopt_array($curl, array(
        CURLOPT_URL => $urlRequest.'/balance/current',
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_POSTFIELDS => "secureLogin=".$secureLogin."&externalPlayerId=".$externalPlayerId."&hash=".$hashNeed,
        CURLOPT_HTTPHEADER => array(
          "Content-Type: application/x-www-form-urlencoded",
          "Cache-Control: no-cache"
        ),
    ));
                                                             
    $response = curl_exec($curl);
    //echo $response;
    curl_close($curl);
    $hasil = json_decode($response, true);
    $newSaldo = $hasil['balance'];
    $updatePlayerSaldo = mysqli_query($conn,"UPDATE `tb_ppplayer` SET `balance` = '$newSaldo' WHERE userID = '$usersID' AND provider = '$providernya'") or die(mysqli_error());
    sleep(2);
    $params1 = 'amount=-'.$newSaldo.'&externalPlayerId='.$externalPlayerId.'&externalTransactionId='.$kd_transaksi.'&secureLogin='.$secureLogin.$secretKey;
    $hashNeed1 = md5($params1);
    $curl1 = curl_init();
                            
    curl_setopt_array($curl1, array(
      CURLOPT_URL => $urlRequest.'/balance/transfer',
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_ENCODING => "",
      CURLOPT_MAXREDIRS => 10,
      CURLOPT_TIMEOUT => 0,
      CURLOPT_FOLLOWLOCATION => true,
      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
      CURLOPT_CUSTOMREQUEST => "POST",
      CURLOPT_POSTFIELDS => "secureLogin=".$secureLogin."&externalPlayerId=".$externalPlayerId."&externalTransactionId=".$kd_transaksi."&amount=-".$newSaldo."&hash=".$hashNeed1,
      CURLOPT_HTTPHEADER => array(
        "Content-Type: application/x-www-form-urlencoded",
        "Cache-Control: no-cache"
      ),
    ));
                                    
    $response1 = curl_exec($curl1);
    //echo $response1;
    curl_close($curl1);
    $hasil1 = json_decode($response1, true);
    if($hasil1['description'] == 'OK'){
        $getBalancePlayer = mysqli_query($conn,"SELECT * FROM `tb_ppplayer` WHERE userID = '$usersID' AND provider = '$providernya'") or die(mysqli_error());
        $gbp = mysqli_fetch_array($getBalancePlayer);
        $balances = $gbp['balance'];
        $insert_transaksi = mysqli_query($conn,"INSERT INTO `tb_transaksi` (`kd_transaksi`, `date`, `transaksi`, `total`, `saldo`, `note`, `gameid`, `providerID`, `jenis`, `metode`, `pay_from`, `userID`, `status`) VALUES ('$kd_transaksi','$created_date','Transfer','$balances',0, '$catatan', '', '1','6','0','$providerID','$usersID',1)") or die(mysqli_error($conn));
        $updateBalance = mysqli_query($conn,"UPDATE `tb_balance` SET `active` = active + '$balances' WHERE userID = '$usersID'") or die(mysqli_error($conn));
        $updatePlayer = mysqli_query($conn,"UPDATE `tb_ppplayer` SET `status` = 0, `balance` = balance - '$balances' WHERE userID = '$usersID' AND provider = '$providernya'") or die(mysqli_error($conn));
    
        $params2 = 'externalPlayerId='.$externalPlayerId.'&secureLogin='.$secureLogin.$secretKey;
        $hashNeed2 = md5($params2);
        $curl2 = curl_init();
                                  
        curl_setopt_array($curl2, array(
            CURLOPT_URL => $urlRequest.'/game/session/terminate',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => "secureLogin=".$secureLogin."&externalPlayerId=".$externalPlayerId."&hash=".$hashNeed2,
            CURLOPT_HTTPHEADER => array(
              "Content-Type: application/x-www-form-urlencoded",
              "Cache-Control: no-cache"
            ),
        ));
                                          
        $response2 = curl_exec($curl2);
        //echo $response1;
        curl_close($curl2);

    }

  }
  else if($providernya == 'Habanero'){
    $curl = curl_init();
        
    curl_setopt_array($curl, array(
        CURLOPT_URL => $urlRequest.'QueryPlayer',
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_POSTFIELDS => '{
          "BrandId": "'.$secretKey.'", 
          "APIKey": "'.$secureLogin.'", 
          "Username": "'.$externalPlayerId.'",
          "password":"Testaja123"
        }',
        CURLOPT_HTTPHEADER => array(
          "Content-Type: application/x-www-form-urlencoded",
          "Cache-Control: no-cache"
        ),
    ));
                                        
    $response = curl_exec($curl);
    //echo $response;
    curl_close($curl);
    $hasil = json_decode($response, true);
    $newSaldo = $hasil['RealBalance'];
    $updatePlayerSaldo = mysqli_query($conn,"UPDATE `tb_ppplayer` SET `balance` = '$newSaldo' WHERE userID = '$usersID' AND provider = '$providernya'") or die(mysqli_error());
    sleep(2);
    
    $curl3 = curl_init();
                        
    curl_setopt_array($curl3, array(
      CURLOPT_URL => $urlRequest.'WithdrawPlayerMoney',
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_ENCODING => "",
      CURLOPT_MAXREDIRS => 10,
      CURLOPT_TIMEOUT => 0,
      CURLOPT_FOLLOWLOCATION => true,
      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
      CURLOPT_CUSTOMREQUEST => "POST",
      CURLOPT_POSTFIELDS => '{
        "BrandId": "'.$secretKey.'", 
        "APIKey": "'.$secureLogin.'", 
        "Username": "'.$externalPlayerId.'",
        "password":"Testaja123", 
        "currencycode":"IDR",
        "Amount": "-'.$balance.'",
        "WithdrawAll": "true",
        "RequestId":"'.$kode_unik.'"
      }',
      CURLOPT_HTTPHEADER => array(
        "Content-Type: application/json",
        "Cache-Control: no-cache"
      ),
    ));
                      
    $response3 = curl_exec($curl3);
    //echo $response1;
    curl_close($curl3);
    $hasil3 = json_decode($response3, true);
    $getBalancePlayer = mysqli_query($conn,"SELECT * FROM `tb_ppplayer` WHERE userID = '$usersID' AND provider = '$providernya'") or die(mysqli_error());
    $gbp = mysqli_fetch_array($getBalancePlayer);
    $balances = $gbp['balance'];
    
    $insert_transaksi = mysqli_query($conn,"INSERT INTO `tb_transaksi` (`kd_transaksi`, `date`, `transaksi`, `total`, `saldo`, `note`, `gameid`, `providerID`, `jenis`, `metode`, `pay_from`, `userID`, `status`) VALUES ('$kd_transaksi','$created_date','Transfer','$balances',0, '$catatan', '', '3','6','0','$providerID','$usersID',1)") or die(mysqli_error());
    $updateBalance = mysqli_query($conn,"UPDATE `tb_balance` SET `active` = active + '$balances' WHERE userID = '$usersID'") or die(mysqli_error());
    $updatePlayer = mysqli_query($conn,"UPDATE `tb_ppplayer` SET `status` = 0, `balance` = balance - '$balances' WHERE userID = '$usersID' AND provider = '$providernya'") or die(mysqli_error());

    $curl2 = curl_init();
                        
    curl_setopt_array($curl2, array(
      CURLOPT_URL => $urlRequest.'LogoutPlayerRequest',
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_ENCODING => "",
      CURLOPT_MAXREDIRS => 10,
      CURLOPT_TIMEOUT => 0,
      CURLOPT_FOLLOWLOCATION => true,
      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
      CURLOPT_CUSTOMREQUEST => "POST",
      CURLOPT_POSTFIELDS => '{
        "BrandId": "'.$secretKey.'", 
        "APIKey": "'.$secureLogin.'", 
        "Username": "'.$externalPlayerId.'",
        "password":"Testaja123"
      }',
      CURLOPT_HTTPHEADER => array(
        "Content-Type: application/json",
        "Cache-Control: no-cache"
      ),
    ));
                      
    $response2 = curl_exec($curl2);
    //echo $response1;
    curl_close($curl2);
    $hasil2 = json_decode($response2, true);
  }
  else if($providernya == 'PGSoft'){
    function getGUID(){
        if (function_exists('com_create_guid')){
            return com_create_guid();
        }else{
            mt_srand((double)microtime()*10000);//optional for php 4.2.0 and up.
            $charid = strtoupper(md5(uniqid(rand(), true)));
            $hyphen = chr(45);// "-"
            $uuid = 
                substr($charid, 0, 8).$hyphen
                .substr($charid, 8, 4).$hyphen
                .substr($charid,12, 4).$hyphen
                .substr($charid,16, 4).$hyphen
                .substr($charid,20,12);
                
            return $uuid;
        }
    }

    $guid = getGUID();

    $curl = curl_init();
                           
    curl_setopt_array($curl, array(
      CURLOPT_URL => $urlRequest.'external/Cash/v3/GetPlayerWallet?trace_id='.$guid,
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_ENCODING => "",
      CURLOPT_MAXREDIRS => 10,
      CURLOPT_TIMEOUT => 0,
      CURLOPT_FOLLOWLOCATION => true,
      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
      CURLOPT_CUSTOMREQUEST => "POST",
      CURLOPT_POSTFIELDS => "operator_token=".$secureLogin."&secret_key=".$secretKey."&player_name=".$externalPlayerId,
      CURLOPT_HTTPHEADER => array(
        "Content-Type: application/x-www-form-urlencoded",
        "Cache-Control: no-cache"
      ),
    ));
                            
    $response = curl_exec($curl);
    //echo $response;
    curl_close($curl);
    $hasil = json_decode($response, true);
    $newSaldos = $hasil['data']['totalBalance'];
    $newSaldo = $newSaldo * 1000;
    $updatePlayerSaldo = mysqli_query($conn,"UPDATE `tb_ppplayer` SET `balance` = '$newSaldo' WHERE userID = '$userID' AND provider = '$providernya'") or die(mysqli_error());
    sleep(2);

    function getGUIDD(){
        if (function_exists('com_create_guid')){
            return com_create_guid();
        }else{
            mt_srand((double)microtime()*10000);//optional for php 4.2.0 and up.
            $charid = strtoupper(md5(uniqid(rand(), true)));
            $hyphen = chr(45);// "-"
            $uuid = 
                substr($charid, 0, 8).$hyphen
                .substr($charid, 8, 4).$hyphen
                .substr($charid,12, 4).$hyphen
                .substr($charid,16, 4).$hyphen
                .substr($charid,20,12);
                
            return $uuid;
        }
    }

    $guidd = getGUIDD();

    $curl1 = curl_init();
                           
    curl_setopt_array($curl1, array(
      CURLOPT_URL => $urlRequest.'external/Cash/v3/TransferAllOut?trace_id='.$guidd,
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_ENCODING => "",
      CURLOPT_MAXREDIRS => 10,
      CURLOPT_TIMEOUT => 0,
      CURLOPT_FOLLOWLOCATION => true,
      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
      CURLOPT_CUSTOMREQUEST => "POST",
      CURLOPT_POSTFIELDS => "operator_token=".$secureLogin."&secret_key=".$secretKey."&player_name=".$externalPlayerId."&transfer_reference=".$kd_transaksi."&currency=IDR",
      CURLOPT_HTTPHEADER => array(
        "Content-Type: application/x-www-form-urlencoded",
        "Cache-Control: no-cache"
      ),
    ));
                           
    $response1 = curl_exec($curl1);
    //echo $response;
    curl_close($curl1);

    $getBalancePlayer = mysqli_query($conn,"SELECT * FROM `tb_ppplayer` WHERE userID = '$userID' AND provider = '$providernya'") or die(mysqli_error());
    $gbp = mysqli_fetch_array($getBalancePlayer);
    $balances = $gbp['balance'];
    
    $insert_transaksi = mysqli_query($conn,"INSERT INTO `tb_transaksi` (`kd_transaksi`, `date`, `transaksi`, `total`, `saldo`, `note`, `gameid`, `providerID`, `jenis`, `metode`, `pay_from`, `userID`, `status`) VALUES ('$kd_transaksi','$created_date','Transfer','$balances',0, '$catatan', '', '4','6','0','$providerID','$userID',1)") or die(mysqli_error());
    $updateBalance = mysqli_query($conn,"UPDATE `tb_balance` SET `active` = active + '$balances' WHERE userID = '$userID'") or die(mysqli_error());
    $updatePlayer = mysqli_query($conn,"UPDATE `tb_ppplayer` SET `status` = 0, `balance` = balance - '$balances' WHERE userID = '$userID' AND provider = '$providernya'") or die(mysqli_error());

    function getGUIDO(){
        if (function_exists('com_create_guid')){
            return com_create_guid();
        }else{
            mt_srand((double)microtime()*10000);//optional for php 4.2.0 and up.
            $charid = strtoupper(md5(uniqid(rand(), true)));
            $hyphen = chr(45);// "-"
            $uuid = 
                substr($charid, 0, 8).$hyphen
                .substr($charid, 8, 4).$hyphen
                .substr($charid,12, 4).$hyphen
                .substr($charid,16, 4).$hyphen
                .substr($charid,20,12);
                
            return $uuid;
        }
    }

    $guido = getGUIDO();

    $curl2 = curl_init();
                           
    curl_setopt_array($curl2, array(
      CURLOPT_URL => $urlRequest.'external/Cash/v3/Player/Kick?trace_id='.$guido,
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_ENCODING => "",
      CURLOPT_MAXREDIRS => 10,
      CURLOPT_TIMEOUT => 0,
      CURLOPT_FOLLOWLOCATION => true,
      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
      CURLOPT_CUSTOMREQUEST => "POST",
      CURLOPT_POSTFIELDS => "operator_token=".$secureLogin."&secret_key=".$secretKey."&player_name=".$externalPlayerId,
      CURLOPT_HTTPHEADER => array(
        "Content-Type: application/x-www-form-urlencoded",
        "Cache-Control: no-cache"
      ),
    ));
                           
    $response2 = curl_exec($curl2);
    //echo $response;
    curl_close($curl2);
  }
  else if($providernya == 'Joker'){
    $timestamp = time();

    $fields1 = ['Method' => 'GC',
               'Username' => $externalPlayerId,
               'Timestamp' => $timestamp
              ];
    ksort($fields1);
    $signature1 = urlencode(base64_encode(hash_hmac("sha1", urldecode(http_build_query($fields1,'', '&')), $secretKey, TRUE)));

    $curl1 = curl_init();
    curl_setopt_array($curl1, array(
        CURLOPT_URL => $urlRequest.'?appid='.$secureLogin.'&signature='.$signature,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_POSTFIELDS => '{"Method":"GC","Username":"'.$externalPlayerId.'","Timestamp":"'.$timestamp.'"}',
        CURLOPT_HTTPHEADER => array(
            "Content-Type: application/json",
            "Cache-Control: no-cache"
        ),
    ));
                                                           
    $response1 = curl_exec($curl1);
    //echo $response;
    curl_close($curl1);
    $hasil1 = json_decode($response1, true);
    $newSaldo = $hasil1['Credit'];
    $updatePlayerSaldo = mysqli_query($conn,"UPDATE `tb_ppplayer` SET `balance` = '$newSaldo' WHERE userID = '$userID' AND provider = '$providernya'") or die(mysqli_error());
    sleep(2);

    $fields2 = ['Method' => 'WAC',
               'Username' => $externalPlayerId,
               'Timestamp' => $timestamp,
               'RequestID' => $requestID
              ];
    ksort($fields2);
    $signature2 = urlencode(base64_encode(hash_hmac("sha1", urldecode(http_build_query($fields2,'', '&')), $secretKey, TRUE)));
    $curl2 = curl_init();
    curl_setopt_array($curl2, array(
        CURLOPT_URL => $urlRequest.'?appid='.$secureLogin.'&signature='.$signature2,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_POSTFIELDS => '{"Method":"WAC","Username":"'.$externalPlayerId.'","Timestamp":"'.$timestamp.'","RequestID":"'.$requestIDD.'"}',
        CURLOPT_HTTPHEADER => array(
            "Content-Type: application/json",
            "Cache-Control: no-cache"
        ),
    ));
                                
    $response2 = curl_exec($curl2);
    //echo $response;
    curl_close($curl2);
    $hasil2 = json_decode($response2, true);

    $getBalancePlayer = mysqli_query($conn,"SELECT * FROM `tb_ppplayer` WHERE userID = '$userID' AND provider = '$providernya'") or die(mysqli_error());
    $gbp = mysqli_fetch_array($getBalancePlayer);
    $balances = $gbp['balance'];
    
    $insert_transaksi = mysqli_query($conn,"INSERT INTO `tb_transaksi` (`kd_transaksi`, `date`, `transaksi`, `total`, `saldo`, `note`, `gameid`, `providerID`, `jenis`, `metode`, `pay_from`, `userID`, `status`) VALUES ('$kd_transaksi','$created_date','Transfer','$balances',0, '$catatan', '', '2','6','0','$providerID','$userID',1)") or die(mysqli_error());
    $updateBalance = mysqli_query($conn,"UPDATE `tb_balance` SET `active` = active + '$balances' WHERE userID = '$userID'") or die(mysqli_error());
    $updatePlayer = mysqli_query($conn,"UPDATE `tb_ppplayer` SET `status` = 0, `balance` = balance - '$balances' WHERE userID = '$userID' AND provider = '$providernya'") or die(mysqli_error());

    $fields3 = ['Method' => 'SO',
               'Username' => $externalPlayerId,
               'Timestamp' => $timestamp
              ];
    ksort($fields3);
    $signature3 = urlencode(base64_encode(hash_hmac("sha1", urldecode(http_build_query($fields3,'', '&')), $secretKey, TRUE)));

    $curl3 = curl_init();
    curl_setopt_array($curl3, array(
        CURLOPT_URL => $urlRequest.'?appid='.$secureLogin.'&signature='.$signature3,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_POSTFIELDS => '{"Method":"SO","Username":"'.$externalPlayerId.'","Timestamp":"'.$timestamp.'"}',
        CURLOPT_HTTPHEADER => array(
            "Content-Type: application/json",
            "Cache-Control: no-cache"
        ),
    ));
                                                           
    $response3 = curl_exec($curl3);
    //echo $response;
    curl_close($curl3);
    $hasil3 = json_decode($response3, true);
  }

header('location:../room/');
exit();
?>