<?php
  //  $_REQUEST['streamid'] = '8eb88b38c4fa6b1b8f73a76f81e38e11';
  // print_r($_REQUEST);
?><!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <meta http-equiv="X-UA-Compatible" content="ie=edge" />
  <meta name="mobile-web-app-capable" content="yes">
  <title>Sats4LIVE</title>
  <link href="https://cdn.jsdelivr.net/npm/@nimiq/style@v0.7.4/nimiq-style.min.css" rel="stylesheet" />
  <link href="https://fonts.googleapis.com/css?family=Muli:400,600,700" rel="stylesheet" />
  <link href="https://fonts.googleapis.com/css?family=Fira+Mono&text=0123456789ABCDEFGHJKLMNPQRSTUVXY" rel="stylesheet" />
  <style>
    .nq-card {
      margin: 1rem auto;
      /* background: #d3d3d3;
      height: 200px; */
    }

    img {
      margin: auto;
      display: block;
    }

    #result {
      word-wrap: anywhere;
    }

    .slidecontainer {
      width: 100%;
    }

    .slider {
      -webkit-appearance: none;
      width: 100%;
      height: 25px;
      background: #d3d3d3;
      outline: none;
      opacity: 0.7;
      -webkit-transition: .2s;
      transition: opacity .2s;
      border-radius: 5px;
    }

    .slider:hover {
      opacity: 90;
    }

    .slider::-webkit-slider-thumb {
      -webkit-appearance: none;
      appearance: none;
      width: 25px;
      height: 25px;
      border-radius: 50%;
      background: #4CAF50;
      cursor: pointer;
    }

    .slider::-moz-range-thumb {
      width: 25px;
      height: 25px;
      background: #4CAF50;
      cursor: pointer;
    }

    .inputtext {
      margin: 10px;
      width: 100%;
      height: 25px;
      float: center;
      text-align: center;
      display: none;
    }
    
    svg {
      max-height: 50px;
      max-width: 50px;
    }

    #identicon {
      background: #4CAF50;
      margin: 0px 0px 0px 0px;
      height: 0px;
      float: center;
      position: relative; 
      top: 20px;
      right: -140px;
    }
  </style>
  <script src="https://cdn.jsdelivr.net/npm/@nimiq/hub-api@v1.0/dist/standalone/HubApi.standalone.umd.js" integrity="sha256-HZuohwzM5nRdRQh3HLpAcYGbpNe6PtqZRyK+VvUI+nU=" crossorigin="anonymous"></script>
</head>


<body class="nq-style">
  <div class="nq-card"  >
    <div class="nq-card-header">
        
        <?php

// check if donation has already been processed (=file created)
if($_REQUEST['requestid']){
    $filename = "tmp/" . $_REQUEST['requestid'];

    if (!file_exists($filename)) {
        // echo "DOES NOT EXIST";
    } else {
        $link_url_home = "<A href=\"/?streamid=" . $_REQUEST['streamid'] .  "\">Go back</A>";
        echo "Request processed thank you for your donation. $link_url_home";
        exit;
    }

    $myfile = fopen($filename, "w");
}

//this is the webhook
if($_REQUEST['requestid']){
    $request_json = json_encode($_REQUEST);

    $url = 'https://noviomedia.com/live.php';
    //echo $url;
    echo "YES! Your request has been accepted! <BR><BR> <a href=\"https://noviomedia.com/?streamid=" . $_REQUEST['streamid'] . "\">Please go back to main page</A>";

    $fp = fopen('data.txt', 'a');//opens file in append mode  
    fwrite($fp, $request_json . '
' . $url . '
');  
    fclose($fp);
    
    $fields = array();
    $apikey = '';
    $fields['top'] = 'Donation of ' . $_REQUEST['amount'] .' sats';
    $fields['bottom'] = $_REQUEST['memo'];
    $fields['type'] = 'donation';
    $fields['message'] = $_REQUEST['memo'];
    $fields['amount'] = $_REQUEST['amount'];
    $fields['streamid'] = $_REQUEST['streamid'];
    $fields['currency'] = 'sats';
    $output = visitSSLURL2($url, $fields, $apikey);
    //print_r($output);
    exit;
} 

//this is the request for QR part
if($_REQUEST['memo']){

//if SatoshiRadio
  if($_REQUEST['streamid'] == '8eb88b38c4fa6b1b8f73a76f81e38e11' ){
  $apikey = '60ca4845aecf488288e66c017c966daf';
}
  else 
{
 $apikey = 'df578394327542ff8bf9f944009dd9f6';

}

$url = 'https://lnbits.noviomedia.com:5000/api/v1/payments';

function generateRandomString($length = 10) {
    return substr(str_shuffle(str_repeat($x='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', ceil($length/strlen($x)) )),1,$length);
}
$requestid = generateRandomString(30);

$array = array();
$array['out'] = false;

$array['amount'] = intval($_REQUEST['amount']);
if($_REQUEST['memo']){
    $array['memo'] = $_REQUEST['memo'];
} else {
    $array['memo'] = 'memo'; 
}

//$array['memo'] = htmlspecialchars($array['memo']);
$array['webhook'] = 'https://noviomedia.com/index.php?requestid=' . $requestid . '&memo=' . $array['memo'] . '&amount=' . $array['amount'] . '&streamid=' . $_REQUEST['streamid'];
$output = visitSSLURL($url, $array, $apikey);
$output_json = json_decode($output);
//  print_r($output);

$lnurl = "lightning:" . $output_json->payment_request;

include('phpqrcode/qrlib.php');
QRcode::png($lnurl, 'tmp/' . $requestid . '.png'); // creates file
$src = 'tmp/' . $requestid . '.png';


echo "<div class=\"nq-h1\">Scan & Pay to submit to live stream</div>";

echo "<CENTER><A href=\"$lnurl\">";
echo "<IMG src=\"$src\" style=\"width:100%\"></a>";

if($_REQUEST['streamid'] == '8eb88b38c4fa6b1b8f73a76f81e38e11' ){
  $livestreamtxt = 'Satoshi Radio live stream';
} else {
  $livestreamtxt = 'live stream';
}

echo "<p><b>Message to send to $livestreamtxt:</b><br> " . $array['memo'] . "</p>";

//DEBUG
//echo "<BR><BR>For webhook: <A href=\"" . $array['webhook'] . "\">link webhook</A>";

echo "<BR><BR>You can temporarily bypass this payment request my click: <A href=\"" . $array['webhook'] . "\">here</A>";

$filename = "tmp/" . $requestid;

if (!file_exists($filename)) {
    ?>
  <script>        
      function doesFileExist(urlToFile) {
            var xhr = new XMLHttpRequest();
            xhr.open('HEAD', urlToFile, false);
            xhr.send();
            if (xhr.status == "404") {
                return false;
            } else {
                return true;
            }
        }

      var i = 1;                 
      function myLoop() {        
        var filename = "<?php echo $filename; ?>";
        var check = doesFileExist(filename);
        console.log(check);
        var reload_url = window.location.href + '?&requestid=<?php echo $requestid; ?>'
        console.log(reload_url)
        if(check === true) {
          //window.location.reload()
          window.location.href = reload_url;
        }
        setTimeout(function() {   
          i++;                    
          if (i < 1000) {          
            myLoop();             
          }         
        }, 3000)
      }

      myLoop();

  </script>
    <?php
} 


}

//this is the landing page part
if(!$_REQUEST['memo'] AND !$_REQUEST['requestid'] ){

if(isset($_GET['streamid'])){
   $streamid = $_GET['streamid'];
  } else {
    $streamid = 'zf97p1a2OX37x91e23';
  }

  if($_REQUEST['streamid'] == '8eb88b38c4fa6b1b8f73a76f81e38e11' ){
    $livestreamtxt = 'Satoshi Radio live stream';
  } else {
    $livestreamtxt = 'live stream';
  }

echo "<FORM method='post' onsubmit='return validateForm()'>
<div class=\"nq-h1\">Message to  $livestreamtxt</div>";

echo "
<p class=\"nq-notice bs\" style=\"margin-top:15px;margin-bottom:8px;\">Enter a message in the field below that will be sent to the live stream.</p>
<p class=\"nq-notice error bs\" id=\"error\" style=\"margin-top:8px;margin-bottom:8px;\"></p>
<input type='text' name='memo' id='inputmemo' class=\"nq-input \" style='width:350px' maxlength='62'>";

?>
      <div id="before-order">
      
      <div style="padding-top:10px;padding-bottom:10px;">
        <button class="nq-button-s light-blue" id="donate_1">&euro; 0.10</button> 
        <button class="nq-button-s light-blue" id="donate_2">&euro; 1</button>
        <button class="nq-button-s light-blue" id="donate_3">&euro; 5</button>
        <button class="nq-button-s light-blue" id="donate_4">&euro; 10</button>
        &nbsp; &euro; <input type='text' id='inputvalue' class="nq-input" style='height:30px;width:83px' maxlength='4'>
      </div>

          <p class="nq-notice" style="display:none;" >Slide the knob to the amount of sats that you want to donate</p>
          <div class="slidecontainer" style="display:none;">
            <input type="range" min="0.10" max="10" step="0.1" value="0.1" class="slider" id="myRange">
          </div>
          <div id="donate_txt"></div><div id="sats"></div><div></div><div id="euro"></div>
          <input type="hidden" name="value1btc" id="value1btc" value="45000">
          <input type="hidden" name="amount" id="value1btc_timestamp" >
          <input type="hidden" name="amount" id="amount">
          <input type="hidden" name="streamid" value="<?php echo $streamid; ?>">
          <input type="hidden" id="eurusd">
        </p>
      </div>

<script type="module">
  var inputvalue = document.getElementById("inputvalue");
  inputvalue.addEventListener("focusout", custommnt);

  function custommnt(){
    var y = inputvalue.value;
    y = y.replace(/,/g, '.')
    
    var x = Number(y);
    if(x == 'NaN'){
       inputvalue.value = '';
       return false;
     }
     if(x == '0.00'){
       inputvalue.value = '';
       return false;
     }
     if(x > 10){
      document.getElementById("error").innerHTML = "Sorry, the current maximum you can donate is &euro; 10. ";
       inputvalue.value = '';
       return false;
     }

    console.log(x.toFixed(2));
    inputvalue.value = x.toFixed(2);
    document.getElementById("myRange").value = x.toFixed(2);
    sliderupdate(x.toFixed(2));
  }

  var donate_1 = document.getElementById("donate_1");
  donate_1.onclick = function() {
    document.getElementById("myRange").value = "0.10";
    sliderupdate('0.10');
    return false;
  }

  var donate_2 = document.getElementById("donate_2");
  donate_2.onclick = function() {
    document.getElementById("myRange").value = 1;
    sliderupdate(1);
    return false;
  }

  var donate_3 = document.getElementById("donate_3");
  donate_3.onclick = function() {
    document.getElementById("myRange").value = 5;
    sliderupdate(5);
    return false;
  }

  var donate_4 = document.getElementById("donate_4");
  donate_4.onclick = function() {
    document.getElementById("myRange").value = 10;
    sliderupdate(10);
    return false;
  }

  document.getElementById("checkout").disabled = true;
  var slider = document.getElementById("myRange");
  slider.oninput = function() {
    sliderupdate(slider.value);
  }

  function numberWithCommas(x) {
    return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}

  function sliderupdate(slidervalue){
    var value1btc = document.getElementById('value1btc').value;
    var sats = Math.round((slidervalue / value1btc) * 100000000);
    let request_amount = parseFloat(slidervalue);
    //document.getElementById('checkout').innerHTML = 'Yes, I want to order ± '+ sats + ' sats for &euro; '  + request_amount.toFixed(2) + ' !';
    // console.log('± '+ sats + ' sats for &euro; '  + request_amount.toFixed(2) + ' !');
    // document.getElementById('euro').innerHTML = '&euro;  ' + request_amount.toFixed(2);
    // document.getElementById('sats').innerHTML = sats + ' sats';
    document.getElementById('amount').value = sats;
    sats = numberWithCommas(sats);
    var usd = document.getElementById('eurusd').value * slidervalue;
    // document.getElementById('donate_txt').innerHTML = 'Donate ' + sats + ' sats &asymp; ' + '&euro;  ' + request_amount.toFixed(2) + ' &asymp; $ ' + usd.toFixed(2) + '';
    document.getElementById('donate_txt').innerHTML = 'Donate ' + '&euro;  ' + request_amount.toFixed(2) + ' &asymp; $ ' + usd.toFixed(2) + ' &asymp; ' + sats + ' sats';
  }

  function refreshvalue(){
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
        const obj = JSON.parse(this.responseText);
        console.log(obj);
        document.getElementById('value1btc').value = obj.value1btc;
        document.getElementById('eurusd').value = obj.eurusd;
        document.getElementById('value1btc_timestamp').value = obj.timestamp;
        sliderupdate(document.getElementById("myRange").value);
        if(document.getElementById("checkout").disabled == true && document.getElementById('amount').value!=''){
          document.getElementById("checkout").disabled = false;
        }
      }
    };
    xhttp.open("GET", "currentvalue.php", true);
    xhttp.send();

  setTimeout(function() {

  if(document.getElementById("checkout").value == 0){
    refreshvalue();
  }  
  }, 10000);
}

refreshvalue();


</script>

<?php

echo "
<button class='nq-button' id='checkout' >✅ Donate ! ❤</button>
</FORM>
";

function print_icon($icon_name)
      {
          $icon = '';
          return $icon;
      }

?>
<div style="width:100%;display: flex;justify-content: center;border-style: dotted;">
<p style="font-size:8pt;text-align:center">
<?php echo print_icon('alert-triangle'); ?>&nbsp;&nbsp;
This is a demo website! <?php echo print_icon('alert-triangle'); ?> <BR>
You can use a wallet that can sent BTC (on Lightning network) such as BlueWallet, Wallet of Satoshi, Muun Wallet or Breeze. We collect SATS as a small donation to convert to live stream so show 'ease-of-use' ;). <BR> By visiting this website, and especially pressing the donate button, you will accept our <A HREF="privacy.php">Privacy Statement</A> . 
</p></div>
<?php


echo '
<script>
    document.getElementById("inputmemo").focus();   
    function validateForm() {
      console.log(document.getElementById("value1btc").value);
      console.log(document.getElementById("amount").value);
      
     var data = document.getElementById("inputmemo").value;
     if (data == "") {
        document.getElementById("error").innerHTML = "Please enter a messsage below before clicking the button. Thank you.";
        document.getElementById("inputmemo").focus();
        console.log(data)
        return false;
     }
  }

</script>';

}



function visitSSLURL(string $url, array $fields, $apikey)
{
    $fields_string = '';
    foreach ($fields as $key => $value) {
        $fields_string .= $key . '=' . $value . '&';
    }
    rtrim($fields_string, '&');
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_URL, $url);

    if(count($fields)>0){
        $data = json_encode($fields);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    }

    //echo $data;

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        "X-Api-Key: $apikey",
        "Content-type: application/json"
        )); 
    $server_output = curl_exec($ch);
    curl_close($ch);
    return $server_output;
}

function visitSSLURL2(string $url, array $fields, $apikey)
{
    $fields_string = '';
    foreach ($fields as $key => $value) {
        $fields_string .= $key . '=' . $value . '&';
    }
    rtrim($fields_string, '&');
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_URL, $url);

    //print_r($fields);
    if(count($fields)>0){
        //$data = json_encode($fields);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
    }

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    // curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    //     "X-Api-Key: $apikey",
    //     "Content-type: application/json"
    //     )); 
    $server_output = curl_exec($ch);
    curl_close($ch);
    return $server_output;
}
?>