<?php
require_once('../database/header.php');

// Redirect if user status is 'paywait'
if ($userdata['status'] == 'paywait') {
echo '<script>window.location = "paywait.php"</script>';
}
?>


<!-- Begin Page Content -->
<div class="main-panel">
<div class="content-wrapper">

<!-- DataTales Example -->
<div class="card shadow mb-4">
<div class="card-header py-3 bg-primary">
<h6 class="m-0 font-weight-bold text-white">BharatPe 提现金额</h6>
</div>
<div class="card-body">

<?php
// API URL for fetching today's collection
$api_url = "https://smartupi.in.net/merchantapi/bharatpe/account.php?token=$token";

// Initialize today_collection variable
$today_collection = 0;

// Make the API call to fetch today's collection
$response = file_get_contents($api_url);
if ($response !== false) {
$data = json_decode($response, true);
if ($data && $data['status'] === 'success' && $data['success'] === true) {
$today_collection = isset($data['data']['current_principal']) ? $data['data']['current_principal'] : 0;
} elseif ($data && isset($data['status']) && $data['status'] === 'Failed' && $data['status_code'] == 401) {

echo '<div class="alert alert-danger" role="alert">
<strong>糟糕！</strong> 未绑定商户。请先连接 BharatPe 账户，然后再进行提现
  </div>';
   

}
}

// Handle form submission
if (isset($_POST['submit_amount']) && !empty($_POST['amount'])) {
// Sanitize and validate the amount
$amount = filter_var($_POST['amount'], FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);

// API URL for withdrawal
$withdraw_api_url = "https://smartupi.in.net/merchantapi/bharatpe/withdraw.php?token=$token&amount=" . $amount;

// Make the API call for withdrawal
$withdraw_response = file_get_contents($withdraw_api_url);
if ($withdraw_response !== false) {
$withdraw_data = json_decode($withdraw_response, true);

// Check the withdrawal status
if ($withdraw_data['status'] === 'Failed') {
  
// Display SweetAlert if status is Failed with status code 401
echo '<script>
Swal.fire({
icon: "error",
title: "糟糕",
text: "' . $withdraw_data['message'] . ' Rs.'.$today_collection.'",
});
  </script>';

} else {
// Withdrawal successful
$orderid = 'NEFT-' . uniqid();
$date = date('Y-m-d H:i:s');
$withdraw_type = 'NEFT BANK TRANSFER';
$status = $withdraw_data['data']['txn_status']; // Get txn_status from API response
$reference_id = $withdraw_data['data']['reference_id']; // Get reference_id from API response

// Insert data into the `withdrawal_amount` table
$sql = "INSERT INTO `withdrawal_amount` (`orderid`, `user`, `user_id`, `date`, `withdraw_type`, `status`, `amount`, `reference_id`, `txn_status`) 
VALUES (:orderid, :user, :user_id, :date, :withdraw_type, :status, :amount, :reference_id, :txn_status)";
$stmt = $conn->prepare($sql);
$stmt->bindParam(":orderid", $orderid);
$stmt->bindParam(":user", $userdata['username']);
$stmt->bindParam(":user_id", $userdata['id']);
$stmt->bindParam(":date", $date);
$stmt->bindParam(":withdraw_type", $withdraw_type);
$stmt->bindParam(":status", $status);
$stmt->bindParam(":amount", $amount);
$stmt->bindParam(":reference_id", $reference_id);
$stmt->bindParam(":txn_status", $status);

if ($stmt->execute()) {

echo '<script>
Swal.fire({
icon: "success",
title: "好",
text: "提现金额提交成功！",
});
  </script>';

} else {
echo '<script>
Swal.fire({
icon: "success",
title: "好",
text: "提现金额提交失败。",
});
  </script>';
  
}
}
} else {
// API call failed
echo '<div class="alert alert-danger" role="alert">
<strong>错误！</strong> 无法连接到提现 API。
  </div>';
}
}
?>

<!-- Form to submit amount -->
<form class="user" action="" method="POST">
<div class="form-group row">
<div class="col-sm-6 mb-3 mb-sm-0">
<label class="m-0 font-weight-bold text-dark">金额</label>
<input required type="number" step="0.01" class="form-control" placeholder="输入金额" name="amount" value="<?php echo $today_collection; ?>">
</div>
<div class="col-sm-6 mb-3 mb-sm-0">
<label class="m-0 font-weight-bold text-dark">提交</label>
<input required type="submit" name="submit_amount" class="btn btn-info btn-block" value="提交">
</div>
</div>
</form>
</div>
</div>

<!-- DataTales Example -->
<div class="card shadow mb-4">
<div class="card-header py-3 bg-primary">
<h6 class="m-0 font-weight-bold text-white">BharatPe 支付记录</h6>
</div>
<div class="card-body">
<div class="table-responsive">
<table class="table table-bordered" id="order-listing" width="100%" cellspacing="0">
<thead>
<tr>
<th style='display:none;'>SL No.</th>
<th class='text-dark'>用户</th>
<th class='text-dark'>订单 ID</th>
<th class='text-dark'>参考 ID</th>
<th class='text-dark'>日期</th>
<th class='text-dark'>类型</th>
<th class='text-dark'>金额</th>
<th class='text-dark'>状态</th> 
</tr>
</thead>
<tbody>
<?php if ($userdata['usertype'] == "mainadmin") { ?>
<?php
$stmt = $conn->prepare("SELECT * FROM withdrawal_amount ORDER BY `id` DESC");
$stmt->execute();
$sl = 1;
while ($row = $stmt->fetch()) {
$status = '<span class="badge badge-info">待处理</span>';
if ($row['status'] == 'SUCCESS') {
$status = '<span class="badge badge-success">成功</span>';
}
if ($row['status'] == 'PENDING') {
$status = '<span class="badge badge-info">待处理</span>';
}
if ($row['status'] == 'FAILED') {
$status = '<span class="badge badge-danger">失败</span>';
}
echo "<tr>
<td style='display:none;'>" . $sl . "</td>
<td class='text-dark'>" . $row['user'] . "</td>
<td style='font-size:13px' class='text-dark'>" . strtoupper($row['orderid']) . "</td>
<td style='font-size:13px' class='text-dark'>" . strtoupper($row['reference_id']) . "</td>
<td style='font-size:13px' class='text-dark'>" . strtoupper($row['date']) . "</td>
<td style='font-size:13px' class='text-dark'>" . strtoupper($row['withdraw_type']) . "</td>
<td style='font-size:13px' class='text-dark'>Rs. " . strtoupper($row['amount']) . "</td>
<td class='text-primary'><i>" . $status . "</i></td>
  </tr>";
$sl++;
}
?>
<?php } else { ?>
<?php
$stmt = $conn->prepare("SELECT * FROM withdrawal_amount WHERE user = ? ORDER BY `id` DESC");
$stmt->execute([$userdata['username']]);
$sl = 1;
while ($row = $stmt->fetch()) {
echo "<tr>
<td style='display:none;'>" . $sl . "</td>
<td style='font-size:13px' class='text-dark'>" . strtoupper($row['merchant_id']) . "</td>
<td style='font-size:13px' class='text-dark'>" . strtoupper($row['merchant_name']) . "</td>
<td style='font-size:13px' class='text-dark'>" . strtoupper($row['created_at']) . "</td>
<td class='text-dark'><b>" . strtoupper($row['status']) . "</b></td>
<td>
<form method='POST' style='display:inline;'>
<input type='hidden' name='delete_id' value='" . $row['id'] . "'>
<button type='submit' class='btn btn-danger btn-sm' onclick='return confirm(\"Are you sure you want to delete this merchant?\");'>删除</button>
</form>
</td>
  </tr>";
$sl++;
}
?>
<?php } ?>
</tbody>
</table>
</div>
</div>
</div>

</div>
<!-- /.container-fluid -->

<?php
require_once('../database/footer.php');
?>