<br><br>
<div class="card-body card-info" id="main-card-body" style="">
  <div class="row">
    <div class="col-md-18">
      Welcome User
    </div>
  </div>

  <br>
  <div class="row card-info">
    <div class="col-md-18 card bg-gray text-xl border-rounded" style="width:100%;height:20%;">
      <div class="row">
        <div class="col-md-6">
          Total Balance
        </div>
        <div class="col-md-6" id="total-balance">

        </div>
      </div>
      <div class="row">
        <div class="col-md-6">

        </div>
        <div class="col-md-6" id="credited-balance">

        </div>
      </div>
      <br><br>
      <div class="row">
        <div class="col-md-6 text-sm" id="phone-number">
          ...
        </div>
        <div class="col-md-6">

        </div>
      </div>


    </div>
  </div>

</div>




<div class="card" id="secondary-card">
  <div class="card-header ui-sortable-handle" style="cursor: move;display: none;">
    <h3 class="card-title" style=""></h3>
    <div class="card-tools">

    </div>
  </div>
  <div class="card-body ">
    <div class="row card-body">



    </div>
  </div>
</div>

<div class="card" id="secondary-card-betting">
  <div class="card-header ui-sortable-handle" style="cursor: move;display: none;">
    <h3 class="card-title" style=""></h3>
    <div class="card-tools">

    </div>
  </div>
  <div class="card-body ">
    <div class="row card-body">
      <div class="col mx-auto" id="">
        Bet type:
      </div>
      <div class="col mx-auto" id="">
        <select id="b-type" class="form-control"></select>
      </div>
    </div>
    <div class="row card-body">
      <div class="col mx-auto" id="">
        Date:
      </div>
      <div class="col mx-auto" id="">
        <select id="sched" class="form-control"></select>
      </div>
    </div>




  </div>
</div>



<div class="card" id="third-card-betting">
  <div class="card-header ui-sortable-handle" style="cursor: move;">
    <h3 class="card-title" style="" id="selected-numbers"></h3>
    <div class="card-tools bg-warning" style="display: none;">
      Maximum Numbers Selected
    </div>
  </div>
  <div class="card-body text-center" id="bubble-sheet-card">






  </div>
</div>

<div class="card" id="fourth-card-confirm" style="display: none;">

  <div class="card-body text-center" id="bubble-sheet-card">
    <button class="form-control border-rounded  btn-danger" onclick="trytosubmitB();">Confirm</button>

  </div>
</div>
<div id="br-space" style="display:none;">
  <br><br><br><br><br><br><br>
</div>




<script>



  var gamesdetails = null;
  var gamemaxnumberofdigits = null;
  var digitselection = null;
  var numberofdigits = 0;
  var numofbets = 0;
  var minimumbet = null;


  function numberofselectedbuttons() {
    return $(".l-button.btn-danger").length;
  }

  function IsSelectedNumbersMax() {
    if ($(".custom-select.numbersinorderselect").length !== 0) {
      return true;
    }

    if (!gamemaxnumberofdigits || gamemaxnumberofdigits === -1) {
      return false;
    }
    if (numberofselectedbuttons() < gamemaxnumberofdigits) {
      return false;
    } else { return true; }

  }

  function currentgametype() {
    return $("#b-type").val();
  }

  function hideconfirmbutton() {
    $("#third-card-betting .card-tools").hide();
    $("#fourth-card-confirm").hide();
  }

  function hideselectednumbersTop() {
    $("#selected-numbers").html("");
  }

  function showconfirmbutton() {
    $("#third-card-betting .card-tools").show(); $("#fourth-card-confirm").fadeIn(200);
    $("#br-space").show();
  }


  function repopulatebtype(response) {
    //console.log();
    $("#b-type").empty();
    $("#sched").empty();
    hideconfirmbutton();
    hideselectednumbersTop();

    let dateoptions = '';


    for (var key in response) {
      var optionValue = response[key]['hashkey'];
      var optionText = response[key]['bet_type'];

      $("#b-type").append($('<option>', { value: optionValue, text: optionText }));


    }
    reloadschedbyvalue();

  }

  function repopulatedatesched(response) {

    for (var key in response) {
      var optionValue = response[key];


      $("#sched").append($('<option>', { value: optionValue, text: optionValue }));

    }

    populatebuttonsb();

  }

  function reloadschedbyvalue() {
    hideconfirmbutton();
    hideselectednumbersTop();
    $("#sched").empty();
    const currentgametype = $("#b-type").val();
    const dataRight = { game: currentgametype };
    AjaxDo('?user/bet/sched', dataRight, repopulatedatesched, null, reqtype = 'POST');
  }

  function generateAmountButton() {
    return 'Amount: <input  type="number" min=' + minimumbet + ' max=' + total_balance + ' class="form-control amountcontrol">';
  }
  function GenerateAddBetButton() {
    return '<button class="form-control btn-primary" onclick="AddBetNow(this)">Add Bet</button>';
  }

  function AmounthasEmptyOrZeroValue() {
    let hasEmptyOrZero = false;

    $('.amountcontrol').each(function () {
      const inputValue = $(this).val();

      if (inputValue === '' || parseFloat(inputValue) === 0) {
        hasEmptyOrZero = true;
        return false;
      }
    });

    return hasEmptyOrZero;
  }

  function isTotalBalanceExceeded() {
    const totalBalance = parseFloat(total_balance);
    let currentTotal = 0;

    $('.amountcontrol').each(function () {
      const inputValue = parseFloat($(this).val());
      if (!isNaN(inputValue)) {
        currentTotal += inputValue;
      }
    });

    return currentTotal > totalBalance;
  }
  function EmptyAmountControl() {
    $('.amountcontrol').val('');
  }


  function GenerateNewBet() {
    numofbets++;
    numberofdigits = 0;
    let html = "<div class='row NumRow'>";


    digitselection.forEach(function (rowValues, rowIndex) {
      html += '<div class="col-3 mx-auto" style="padding-bottom:10px;">';
      html += ("<select class='form-control num-select'>");
      numberofdigits++;
      rowValues.forEach(function (value) {

        html += '<option value=' + value + '>' + value + '</option>';
      });
      html += '</select></div>'
    });
    html += '</div>';
    return html + '<br><br>' + generateAmountButton() + '<br><br>' + GenerateAddBetButton() + '<hr class="bet-separator">';

  }


  function AddBetNow(button) {

    if (AmounthasEmptyOrZeroValue()) { EmptyAmountWarning(); return false; }
    if (isTotalBalanceExceeded()) {
      TotalBalanceExceededWarning();
      EmptyAmountControl();
      return false;
    }

    $("#bubble-sheet-card").append('<br>' + GenerateNewBet() + '');
    $(window).scrollTop($(document).height());

    $(button).remove();

  }





  function populatebuttonsnow(response) {
    //console.log(response);
    numofbets = 0;
    minimumbet = response.price;
    showconfirmbutton();
    hideselectednumbersTop();
    $('#bubble-sheet-card').fadeOut(200);
    $('#bubble-sheet-card').empty();


    let newhtmlbuttons;
    if (response.digit_selection) {
      digitselection = response.digit_selection;
      $("#bubble-sheet-card").html(GenerateNewBet());
    }

    newhtmlbuttons += '<br><br>'

    //$("#bubble-sheet-card").html(newhtmlbuttons);
    $("#bubble-sheet-card").fadeIn(200);

    var Bbuttons = [];

    gamemaxnumberofdigits = response.number_of_digits;
    $(".l-button").click(function () {
      if ($(this).hasClass("btn-primary")) {
        if (!IsSelectedNumbersMax()) {
          $(this).removeClass("btn-primary");
          $(this).addClass("btn-danger");
        } else {
          // Handle case when max numbers are selected
        }
      } else {
        $(this).removeClass("btn-danger");
        $(this).addClass("btn-primary");
        $("#third-card-betting .card-tools").hide();
        $("#fourth-card-confirm").hide();
      }
      showSelectedNumbers(gamemaxnumberofdigits);
    });

  }

  function populatebuttonsb() {
    $("#bubble-sheet-card").fadeOut(200);
    $("#bubble-sheet-card").empty();

    const dataRight = { game: $("#b-type").val() };

    AjaxDo('?user/bet/buttons', dataRight, populatebuttonsnow, null, reqtype = 'POST');
  }



  function showSelectedNumbers(number_of_digits = -1) {
    const selectedButtons = document.querySelectorAll('.l-button.btn-danger');
    let selectedNumbers = '';
    if (selectedButtons.length === number_of_digits) {
      showconfirmbutton();
    }
    selectedButtons.forEach(button => {
      selectedNumbers += button.textContent + '-';
    });

    document.getElementById('selected-numbers').textContent = 'Selected Numbers: ' + selectedNumbers;
    return selectedNumbers;
  }


  function getselectednumbersold() {

    var buttonValues = "";
    if ($(".l-button.btn-danger").length === 0) {

      const selectedValues = [];

      $(".numbersinorderselect").each(function () {
        if ($(this).is("select")) {
          let currentnumber = $(this).val().toString().padStart(2, "0")
          selectedValues.push($(this).val());
          buttonValues += currentnumber + '-';
        }
      });

    } else {

      $(".l-button.btn-danger").each(function () {
        var buttonValue = $(this).val();
        buttonValues += buttonValue + "-";
      });
    }

    return buttonValues;
  }

  function getselectednumbers() {

    const numSelectValues = $('.num-select').map(function () {
      return $(this).val();
    }).get();

    const result = [];
    let currentIndex = 0;

    while (currentIndex < numSelectValues.length) {
      const chunkSize = Math.min(numberofdigits, numSelectValues.length - currentIndex);
      const chunk = numSelectValues.slice(currentIndex, currentIndex + chunkSize);
      result.push(chunk);
      currentIndex += chunkSize;
    }
    return result;
  }

  function collectAmountControlValues() {
    return $('.amountcontrol').map(function () {
      return $(this).val();
    }).get();
  }





  function mergeValuesIntoObjects(numSelectValues, amountControlValues) {
    const result = [];
    const maxLength = Math.max(numSelectValues.length, amountControlValues.length);

    for (let i = 0; i < maxLength; i++) {
      const pair = {
        numSelect: numSelectValues[i] || null,
        amountControl: amountControlValues[i] || null
      };

      result.push(pair);
    }

    return result;
  }


  function getAllSelectedNumbers() {

    const numSelectValues = getselectednumbers(numberofdigits);
    const amountControlValues = collectAmountControlValues();
    const mergedObjects = mergeValuesIntoObjects(numSelectValues, amountControlValues, numberofdigits);
    return mergedObjects;
  }


  function BetFailed(response) {
    CreateAndShowModal('betting-failed', 'Failed', 'Your bet didn\'t go through. Please Try Again Later!', '');
  }
  function BetSuccessful(response) {
    CreateAndShowModal('betting-success', 'Success', 'Successfully Entered Bet!', '');
    gotoPage('bet_qr', response);
  }

  function TotalBalanceExceededWarning() {
    CreateAndShowModal('balance-not-enough-warning', 'Total Amount Exceeded', 'Not Enough Balance!', '');
  }
  function EmptyAmountWarning() {
    CreateAndShowModal('empty-amount-warning', 'Amount', 'No Amount Entered.<br><br>Please Enter an Amount!', '');
  }

  function SubmitFailed() {
    CreateAndShowModal('submit-failed-warning', 'Failed', 'Unable to Place Bet Please Try Again later!', '');
  }

  function SubmitNow(response) {
console.log(response);
    if (Array.isArray(response) || !response || typeof response !== "string") {
      BetFailed(response);
      return false;
    }

    if (response.length !== 72) {
      BetFailed(response);
      return false;
    }

    BetSuccessful(response);







  }

  function trytosubmitB() {
    if (isTotalBalanceExceeded()) { TotalBalanceExceededWarning(); return false; }
    if (AmounthasEmptyOrZeroValue()) { EmptyAmountWarning(); return false; }
    let selectedNumbers = getAllSelectedNumbers();

    const data = { user_target: currenttarget, game: currentgametype(), selected_numbers: selectedNumbers, schedule: $("#sched").val() };
    AjaxDo('?user/new/bet/transaction', data, SubmitNow, null, reqtype = 'POST');
  }




  $(document).ready(function () {
   
if (currenttarget===0){
  loaduserdatadashboard();
}
   
    AjaxDo('?user/bet/tps', null, repopulatebtype, null, reqtype = 'POST');

    const currentgametype = $("#b-type").val();
    const dataRight = { game: currentgametype };


    $("#b-type").change(reloadschedbyvalue);



    if (currenttarget !== 0) {

   function PostUserNumber(response) {
    // CreateAndShowModal('TargetBetUserWarn', 'Betting for a Different User', 'You are betting for ' + response + '.');
     ModalQuickDismiss('Betting for a Different User', 'You are betting for ' + response + '.');
   }
   AjaxDo('?query/user/number/byhash', { user_target: currenttarget }, PostUserNumber, null, reqtype = 'POST');

   function UpdateTotalBalanceforDifferentUser(response){
   if (!response){return false;}
   total_balance=response;
   }

AjaxDo('?query/user/balance', { user_target: currenttarget }, UpdateTotalBalanceforDifferentUser, null, reqtype = 'POST');
 
 }



  });



  







</script>