<!DOCTYPE html>
<html lang="en">
<?php include('include/head.php');
include("loginCheck.php");
include('include/header.php');
include('include/menu.php'); ?>
<?php
$user_id1 = "";
if ($_GET) {
  if ($_GET['user_id']) {
    $user_id1 = $_GET['user_id'];
    $query = "SELECT count(*) from meddolic_user_details WHERE user_id='$user_id1'";
    $result = mysqli_query($con, $query);
    $val = mysqli_fetch_array($result);
    if ($val[0] == 0) { ?>
      <script>
        alert("Invalid User Id");
      </script>
      <?php
      $user_id1 = $_SESSION['admin_user_id'];
    }
  }
  if ($_GET['withdrawStatus']) {
    $withdrawStatus = $_GET['withdrawStatus'];
  }
  if ($_GET['from_date']) {
    $show_date = $_GET['from_date'];
    $cal_date = date("Y-m-d", strtotime($show_date));
  }
  if ($_GET['to_date']) {
    $show_date1 = $_GET['to_date'];
    $cal_date1 = date("Y-m-d", strtotime($show_date1));
  }
} else {
  $show_date = date("d-m-Y");
  $show_date1 = date("d-m-Y");
  $cal_date = date("Y-m-d");
  $cal_date1 = date("Y-m-d");
} ?>
<div id="main-content">
  <div class="container-fluid">
    <div class="block-header">
      <div class="row">
        <div class="col-lg-5 col-md-8 col-sm-12">
          <h2><a href="javascript:void(0);" onclick="window.history.back();"
              class="btn btn-xs btn-link btn-toggle-fullwidth"><i class="fa fa-arrow-left"></i></a> Withdraw History
          </h2>
          <ul class="breadcrumb">
            <li class="breadcrumb-item"><a href="dashboard"><i class="icon-home"></i></a></li>
            <li class="breadcrumb-item"> Withdraw </li>
            <li class="breadcrumb-item active"> Withdraw History</li>
          </ul>
        </div>
      </div>
    </div>

    <div class="row clearfix">
      <div class="col-md-12">
        <div class="card">
          <div class="body">
            <form>
              <div class="form-row">
                <div class="col-2">
                  <input class="form-control" type="text" placeholder="Enter User ID" name="user_id"
                    value="<?= $user_id1 ?>">
                </div>
                <div class="col-2">
                  <select class="form-control" name="withdrawStatus">
                    <option value=""> Select One </option>
                    <option value="0" <?php if ($withdrawStatus == 0)
                      echo 'selected'; ?>> Pending </option>
                    <option value="1" <?php if ($withdrawStatus == 1)
                      echo 'selected'; ?>> Manual Released </option>
                    <option value="2" <?php if ($withdrawStatus == 2)
                      echo 'selected'; ?>> Rejected </option>
                    <option value="3" <?php if ($withdrawStatus == 3)
                      echo 'selected'; ?>> Online Release </option>
                  </select>
                </div>
                <div class="col-2">
                  <input type="text" name="from_date" id="from_date" class="form-control" placeholder="e.g. From Date"
                    required value="<?= $show_date ?>" readonly>
                </div>
                <div class="col-2">
                  <input type="text" name="to_date" id="to_date" class="form-control" placeholder="e.g. To Date"
                    required value="<?= $show_date1 ?>" readonly>
                </div>
                <div class="col-2">
                  <input class="btn btn-primary" type="submit" value="Search">
                </div>
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>

    <!-- Bulk Action Form -->
    <div class="row clearfix">
      <div class="col-md-12">
        <div class="card">
          <div class="body">
            <form id="bulkActionForm">
              <div class="form-row align-items-end">
                <div class="col-2">
                  <label>Total Selected Amount</label>
                  <input class="form-control" type="text" readonly id="total_selected_amount" value="0.00"
                    style="background-color:#FFF; font-weight:bold;">
                </div>
                <div class="col-2">
                  <button class="btn btn-success btn-block" type="button" id="btnRelease"
                    onclick="releaseSelectedOnline()">Release Online</button>
                </div>
                <div class="col-2">
                  <button class="btn btn-success btn-block" type="button" id="btnRelease"
                    onclick="releaseSelected()">Release Manually</button>
                </div>
                <div class="col-2">
                  <button class="btn btn-danger btn-block" type="button" onclick="rejectSelected()">Reject
                    Selected</button>
                </div>
                <div class="col-2">
                  <div id="loader" style="display:none;">
                    <button class="btn btn-primary btn-block" disabled>
                      <span class="spinner-grow spinner-grow-sm"></span> Processing...
                    </button>
                  </div>
                </div>
                <input type="hidden" id="selected_ids" name="selected_ids" value="">
                <input type="hidden" id="selected_member_ids" name="selected_member_ids" value="">
                <input type="hidden" id="selected_amounts" name="selected_amounts" value="">
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>

    <div class="row clearfix">
      <div class="col-lg-12 col-md-12 col-sm-12">
        <div class="card">
          <div class="header">
            <h2>Withdraw History</h2>
            <span id="errorMsg"></span> </br>
            <span id="account"></span></br>
            <span id="getBalance"></span><br>
            <input type="hidden" id="walletKey" name="walletKey">
            <input type="hidden" id="currentTrxBalance">
          </div>
          <div class="body">
            <div class="table-responsive">
              <table class="table table-hover js-basic-example dataTable table-custom mb-0">
                <thead>
                  <tr>
                    <th>
                      <input type="checkbox" id="selectAll" onclick="toggleSelectAll(this)">
                    </th>
                    <th>#</th>
                    <th>UserId</th>
                    <th>Date</th>
                    <th>Gross Amount</th>
                    <th>Charge</th>
                    <th>Net Amount</th>
                    <th>OrderId</th>
                    <th>Wallet Address</th>
                    <th>Withdraw Status</th>
                    <th>Action Date</th>
                    <th>Remark</th>
                    <!-- <th>Action</th> -->
                  </tr>
                </thead>
                <tbody>
                  <?php
                  $queryIn = mysqli_query($con, "SELECT member_id FROM meddolic_user_details WHERE user_id='$user_id1'");
                  $valIn = mysqli_fetch_assoc($queryIn);
                  $member_id1 = $valIn[0];

                  $query = "";
                  if ($user_id1 != "") {
                    $query = $query . " AND a.member_id='$member_id1'";
                  }
                  if ($withdrawStatus != "") {
                    $query = $query . " AND a.released='$withdrawStatus'";
                  }
                  $count = 0;
                  $queryWithdraw = mysqli_query($con, "SELECT a.*,b.walletAddress,b.user_id FROM meddolic_user_wallet_withdrawal_crypto a, meddolic_user_details b WHERE CAST(a.date_time AS date) BETWEEN '$cal_date' AND '$cal_date1' $query AND a.member_id=b.member_id AND a.released='0' ORDER BY a.date_time DESC");
                  while ($valWithdraw = mysqli_fetch_assoc($queryWithdraw)) {
                    $count++; ?>
                    <tr>
                      <td>
                        <?php if ($valWithdraw['released'] == 0) { ?>
                          <input type="checkbox" class="withdrawCheckbox" data-id="<?= $valWithdraw['id'] ?>"
                            data-member="<?= $valWithdraw['member_id'] ?>" data-amount="<?= $valWithdraw['netAmount'] ?>"
                            data-userid="<?= $valWithdraw['user_id'] ?>" onchange="updateSelectedData()">
                        <?php } ?>
                      </td>
                      <td><?= $count ?></td>
                      <td><?= $valWithdraw['user_id'] ?></td>
                      <td class="text-left"><?= $valWithdraw['date_time'] ?></td>
                      <td><span class="badge badge-success">$ <?= $valWithdraw['amount'] ?></span></td>
                      <td><span class="badge badge-success">$ <?= $valWithdraw['withdrawCharge'] ?></span></td>
                      <td><span class="badge badge-danger">$ <?= $valWithdraw['netAmount'] ?></span></td>
                      <td><?= $valWithdraw['orderid'] ?></td>
                      <td><?= $valWithdraw['walletAddress'] ?></td>
                      <td>
                        <?php if ($valWithdraw['released'] == 0)
                          echo "<span class='badge badge-primary'>PENDING</span>";
                        else if ($valWithdraw['released'] == 1)
                          echo "<span class='badge badge-success'>MANUAL RELEASED</span>";
                        else if ($valWithdraw['released'] == 2)
                          echo "<span class='badge badge-danger'>REJECTED</span>";
                        else if ($valWithdraw['released'] == 3)
                          echo "<span class='badge badge-success'>ONLINE RELEASE</span>";
                        else
                          echo "<span class='badge badge-warning'>FAILED</span>"; ?>
                      </td>
                      <td><?= $valWithdraw['payment_date'] ?></td>
                      <td><?= $valWithdraw['remarks'] ?></td>
                      <!-- <td>
                                                <?php if ($valWithdraw['released'] == 0) { ?>
                                                    <a data-id="<?= $valWithdraw['id'] ?>" data-toggle="modal" data-target="#cryptoRemark" data-whatever="<?= $valWithdraw['id'] ?>" href="javascript:void(0)" class="btn btn-primary btn-xs"> Add </a>
                                                <?php } else if ($valWithdraw['released'] == 2) { ?>
                                                    <a data-id="<?= $valWithdraw['id'] ?>" data-toggle="modal" data-target="#cryptoRemark" data-whatever="<?= $valWithdraw['id'] ?>" href="javascript:void(0)" class="btn btn-primary btn-xs"> Edit </a>
                                                <?php } ?>
                                            </td> -->
                    </tr>
                  <?php } ?>
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>
<div class="modal fade" id="cryptoRemark" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
  aria-hidden="false">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="cryptoRemarkDash">
        <!-- Content goes in here -->
      </div>
    </div>
  </div>
</div>
<?php include('include/footer.php'); ?>

<script>
  // Toggle select all checkboxes
  function toggleSelectAll(source) {
    const checkboxes = document.querySelectorAll('.withdrawCheckbox');
    checkboxes.forEach(checkbox => {
      checkbox.checked = source.checked;
    });
    updateSelectedData();
  }

  // Update selected data when checkboxes change
  function updateSelectedData() {
    const selectedCheckboxes = document.querySelectorAll('.withdrawCheckbox:checked');

    let ids = [];
    let memberIds = [];
    let amounts = [];
    let totalAmount = 0;

    selectedCheckboxes.forEach(checkbox => {
      ids.push(checkbox.getAttribute('data-id'));
      memberIds.push(checkbox.getAttribute('data-member'));
      const amount = parseFloat(checkbox.getAttribute('data-amount'));
      amounts.push(amount);
      totalAmount += amount;
    });

    // Update hidden fields
    document.getElementById('selected_ids').value = ids.join(',');
    document.getElementById('selected_member_ids').value = memberIds.join(',');
    document.getElementById('selected_amounts').value = amounts.join(',');
    document.getElementById('total_selected_amount').value = '$ ' + totalAmount.toFixed(2);
  }

  // Release selected withdrawals
  function releaseSelected() {
    const selectedIds = document.getElementById('selected_ids').value;

    if (!selectedIds) {
      alert('Please select at least one withdrawal to release.');
      return;
    }

    if (!confirm('Are you sure you want to release the selected withdrawals?')) {
      return;
    }

    $('#btnRelease').hide();
    $('#loader').show();

    $.ajax({
      type: "POST",
      url: "ajaxCalls/bulkReleaseWithdrawalAjax.php",
      data: {
        ids: selectedIds,
        member_ids: document.getElementById('selected_member_ids').value,
        amounts: document.getElementById('selected_amounts').value
      },
      cache: false,
      success: function (response) {
        console.log("RAW RESPONSE:", response);
        $('#loader').hide();
        $('#btnRelease').show();

        try {
          const data = response;
          if (data.success) {
            alert('Withdrawals released successfully!');
            location.reload();
          } else {
            alert('Error: ' + (data.message || 'Unknown error occurred'));
          }
        } catch (e) {
          console.log(e);
          alert(e);
          alert('Withdrawals processed. Please refresh the page.');
          // location.reload();
        }
      },
      error: function (err) {
        $('#loader').hide();
        $('#btnRelease').show();
        console.log(err);
        alert('An error occurred while processing the request.');
      }
    });
  }
  function releaseSelectedOnline() {
    const selectedIds = document.getElementById('selected_ids').value;

    if (!selectedIds) {
      alert('Please select at least one withdrawal to release.');
      return;
    }

    if (!confirm('Are you sure you want to release the selected withdrawals?')) {
      return;
    }

    $('#btnRelease').hide();
    $('#loader').show();

    $.ajax({
      type: "POST",
      url: "ajaxCalls/bulkReleaseOnlineWithdrawalAjax.php",
      data: {
        ids: selectedIds,
        member_ids: document.getElementById('selected_member_ids').value,
        amounts: document.getElementById('selected_amounts').value
      },
      dataType: 'json', // Ensure we expect JSON
      success: function (response) {
        console.log("SERVER RESPONSE:", response);
        $('#loader').hide();
        $('#btnRelease').show();

        if (response.success) {
          // Success case
          let msg = response.message;
          if (response.details && response.details.length > 0) {
            msg += "\n\nWarnings:\n" + response.details.join("\n");
          }
          alert(msg);
          location.reload();
        } else {
          // Failure case
          let errMsg = response.message;
          if (response.details && response.details.length > 0) {
            errMsg += "\n\nDetails:\n" + response.details.join("\n");
          }
          alert('FAILED:\n' + errMsg);
          // Do NOT reload here so you can see the error
        }
      },
      error: function (xhr, status, error) {
        $('#loader').hide();
        $('#btnRelease').show();
        console.error("AJAX Error:", xhr.responseText);
        alert('System Error: Check console for details.');
      }
    });
  }


  // Reject selected withdrawals
  function rejectSelected() {
    const selectedIds = document.getElementById('selected_ids').value;

    if (!selectedIds) {
      alert('Please select at least one withdrawal to reject.');
      return;
    }

    if (!confirm('Are you sure you want to reject the selected withdrawals?')) {
      return;
    }

    $.ajax({
      type: "POST",
      url: "ajaxCalls/bulkRejectWithdrawalAjax.php",
      data: {
        ids: selectedIds,
        member_ids: document.getElementById('selected_member_ids').value
      },
      cache: false,
      success: function (response) {
        try {
          const data = JSON.parse(response);
          if (data.success) {
            alert('Withdrawals rejected successfully!');
            location.reload();
          } else {
            alert('Error: ' + (data.message || 'Unknown error occurred'));
          }
        } catch (e) {
          alert('Withdrawals processed. Please refresh the page.');
          location.reload();
        }
      },
      error: function (err) {
        console.log(err);
        alert('An error occurred while processing the request.');
      }
    });
  }

  // Existing modal code
  $('#cryptoRemark').on('show.bs.modal', function (event) {
    var button = $(event.relatedTarget);
    var recipient = button.data('whatever');
    var modal = $(this);
    var id = recipient;
    var userId = '<?= $user_id1 ?>';
    var withdrawStatus = '<?= $withdrawStatus ?>';
    var fromDate = '<?= $show_date ?>';
    var toDate = '<?= $show_date1 ?>';
    $.ajax({
      type: "POST",
      url: "ajaxCalls/cryptoRemarkAjax",
      data: {
        id: id,
        withdrawStatus: withdrawStatus,
        fromDate: fromDate,
        toDate: toDate,
        userId: userId
      },
      cache: false,
      success: function (data) {
        console.log(data);
        modal.find('.cryptoRemarkDash').html(data);
      },
      error: function (err) {
        console.log(err);
      }
    });
  });

  var d = document.getElementById("Withdraw");
  d.className += " active";
  var d = document.getElementById("walletWithdrawStatus");
  d.className += " active";
</script>

</body>

</html>