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


// API URL
$apiUrl = "https://smartupi.in.net/merchantapi/bharatpe/account.php?token=$token";

// Use cURL with timeout to prevent page hanging
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 3); // 3 second timeout
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2); // 2 second connection timeout
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curlError = curl_error($ch);
curl_close($ch);

// Decode the JSON response
$data = null;
if ($response && $httpCode == 200) {
    $data = json_decode($response, true);
}

// Check if the API call was successful
if ($data && isset($data['status']) && $data['status'] === "success") {
    $current_balance = $data['data']['current_balance'];
    $current_principal = $data['data']['current_principal'];
    $today_collection = $data['data']['today_collection'];
    $today_total_withdrawal = $data['data']['today_total_withdrawal'];
    $hold_balance = $data['data']['hold_balance'];
} else {
    // Handle API error - set defaults
    $current_balance = $current_principal = $today_collection = $today_total_withdrawal = $hold_balance = "N/A";
    // Optional: Log the error for debugging
    // error_log("SmartUPI API Error: " . ($curlError ? $curlError : "Invalid response"));
}
?>

<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (isset($_POST['access_token']) && !isset($_POST['merchant_id'])) {
// Handle Business Name Button Click
$access_token = $_POST['access_token'];
$apiUrl = "https://smartupi.in.net/merchantapi/bharatpe/profile.php?access_token=" . $access_token;

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($ch);

if (curl_errno($ch)) {
echo json_encode(['error' => 'cURL error: ' . curl_error($ch)]);
} else {
$data = json_decode($response, true);
$merchant_id = $data['merchant_id'];
$business_name = $data['business_name'];
$message = $data['message'];

if ($data && $data['status_code'] == 200 && $data['status'] == 'Success') {
echo '
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
Swal.fire({
title: "'.$business_name.' ",
text: "Merchant Id '.$merchant_id.' ",
icon: "success",
showConfirmButton: true,
timer: 2000,
willClose: () => {
window.location.href = "index.php";
}
});
</script>
';
} else {
echo '
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
Swal.fire({
title: "Opps ",
text: " No Merchant. ",
icon: "error",
showConfirmButton: true,
timer: 2000,
willClose: () => {
window.location.href = "index.php";
}
});
</script>
';    
}
}

curl_close($ch);
exit;
} elseif (isset($_POST['merchant_id']) && isset($_POST['access_token'])) {
// Handle QR Code Button Click
$merchant_id = $_POST['merchant_id'];
$access_token = $_POST['access_token'];
$apiUrl = "https://smartupi.in.net/merchantapi/bharatpe/download-qr.php?merchant_id=$merchant_id&access_token=$access_token";

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($ch);

if (curl_errno($ch)) {
echo json_encode(['error' => 'cURL error: ' . curl_error($ch)]);
} else {
$data = json_decode($response, true);

if ($data && $data['status'] == 'success' && isset($data['qr_url'])) {
$qr_url = $data['qr_url'];
$message = $data['message'];

// Show alert, open QR code URL in a new tab, and refresh the current page
echo '
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
Swal.fire({
title: "Opening QR Code...",
text: "The QR code will open in a new tab in 2 seconds.",
icon: "info",
timer: 2000,
showConfirmButton: false,
willClose: () => {
window.open("'.$qr_url.'", "_blank"); // Open QR code in a new tab
window.location.href = "index.php"; // Refresh the current page
}
});
</script>
';
} else {
    
echo '
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
Swal.fire({
title: "Opps ",
text: " No Merchant. ",
icon: "error",
showConfirmButton: true,
timer: 2000,
willClose: () => {
window.location.href = "index.php";
}
});
</script>
';     
}
}

curl_close($ch);
exit;
}
}
?>

      <div class="main-panel">
        <div class="content-wrapper">
          <div class="row mb-4">
            <div class="col-12 d-flex justify-content-between align-items-center">
              <h3 class="font-weight-bold">控制台</h3>
              <?php if($userdata['usertype'] == "mainadmin") { ?>
              <div class="d-flex">
                  <button type="button" class="btn btn-light bg-white btn-icon mr-3" onclick="window.location.href='create-users.php';" title="Create User">
                    <i class="mdi mdi-plus text-muted"></i>
                  </button>
                  <button class="btn btn-primary" onclick="window.location.href='bharatpe-transactions.php';">实时报告</button>
              </div>
              <?php } ?>
            </div>
          </div>

<?php
            // Calculate Today's Pay-In Stats
            $start_of_day = date('Y-m-d 00:00:00');
            $end_of_day = date('Y-m-d 23:59:59');
            $uid = $userdata['id'];
            $username = $userdata['username'];

            // Fetch Settings for Fee Calculation
            $set_stmt = $conn->prepare("SELECT * FROM settings LIMIT 1");
            $set_stmt->execute();
            $settings = $set_stmt->fetch(PDO::FETCH_ASSOC);

            $current_gateway = $settings['default_gateway'] ?? 'rspay';

            if ($current_gateway == 'bank_upi') {
                // Bank UPI Logic
                $total_percent = floatval($settings['bank_upi_commission'] ?? 0);
                $total_fixed = floatval($settings['bank_upi_fixed'] ?? 0);
            } else {
                // RSPay / Default Logic
                $global_payin_base = floatval($settings['rspay_payin_base'] ?? 0);
                $global_payin_fixed_base = floatval($settings['rspay_payin_fixed'] ?? 0);
                
                // Use user margin if available, otherwise global default
                $usr_payin_margin = floatval($userdata['payin_commission'] ?? $settings['payin_commission'] ?? 0);
                $usr_fixed_margin = floatval($userdata['payin_fixed'] ?? $settings['payin_fixed'] ?? 0);

                $total_percent = $global_payin_base + $usr_payin_margin;
                $total_fixed = $global_payin_fixed_base + $usr_fixed_margin;
            }

            // ============================================
            // OPTIMIZED: Use SQL for calculations instead of PHP loops
            // ============================================
            
            // Pay-In: Today's Stats (Single Query)
            $stmt = $conn->prepare("
                SELECT 
                    SUM(CASE WHEN txn_status = 'SUCCESS' THEN (amount - (amount * ? / 100) - ?) ELSE 0 END) as success_net,
                    SUM(CASE WHEN txn_status = 'PENDING' THEN amount ELSE 0 END) as pending,
                    SUM(CASE WHEN txn_status = 'FAILED' THEN amount ELSE 0 END) as failed,
                    COUNT(*) as total_count
                FROM create_orders 
                WHERE user_id = ? AND date BETWEEN ? AND ?
            ");
            $stmt->execute([$total_percent, $total_fixed, $uid, $start_of_day, $end_of_day]);
            $today_stats = $stmt->fetch(PDO::FETCH_ASSOC);
            
            $today_success = floatval($today_stats['success_net'] ?? 0);
            $today_pending = floatval($today_stats['pending'] ?? 0);
            $today_failed = floatval($today_stats['failed'] ?? 0);
            $today_count = intval($today_stats['total_count'] ?? 0);


            // Calculate Payout & Balance Stats
            // 1. Total All-Time Success Pay-In (For Balance) - OPTIMIZED
            $stmt = $conn->prepare("
                SELECT SUM(amount - (amount * ? / 100) - ?) as net_total
                FROM create_orders 
                WHERE txn_status = 'SUCCESS' AND user_id = ?
            ");
            $stmt->execute([$total_percent, $total_fixed, $uid]);
            $all_time_payin = floatval($stmt->fetchColumn() ?? 0);

            // 2. Total All-Time Payout (Non-Rejected)
            $all_time_payout = 0;
            try {
                $stmt = $conn->prepare("SELECT COALESCE(SUM(amount), 0) FROM payout_requests WHERE user = ? AND status NOT IN ('REJECTED', 'FAILED')");
                $stmt->execute([$username]);
                $all_time_payout = $stmt->fetchColumn();
            } catch (PDOException $e) { $all_time_payout = 0; }

            $available_balance = $all_time_payin - $all_time_payout;


            // Today Payout Stats
            $today_payout_success = 0;
            $today_payout_pending = 0;
            $today_payout_requests = 0;
            try {
                // Today Success Payout
                $stmt = $conn->prepare("SELECT COALESCE(SUM(amount), 0) FROM payout_requests WHERE user = ? AND status IN ('SUCCESS', 'APPROVED') AND created_at BETWEEN ? AND ?");
                $stmt->execute([$username, $start_of_day, $end_of_day]);
                $today_payout_success = $stmt->fetchColumn();

                // Today Pending Payout
                $stmt = $conn->prepare("SELECT COALESCE(SUM(amount), 0) FROM payout_requests WHERE user = ? AND status = 'PENDING' AND created_at BETWEEN ? AND ?");
                $stmt->execute([$username, $start_of_day, $end_of_day]);
                $today_payout_pending = $stmt->fetchColumn();

                // Today Payout Count
                $stmt = $conn->prepare("SELECT COUNT(*) FROM payout_requests WHERE user = ? AND created_at BETWEEN ? AND ?");
                $stmt->execute([$username, $start_of_day, $end_of_day]);
                $today_payout_requests = $stmt->fetchColumn();
            } catch (PDOException $e) { }
          ?>

          <div class="row">
            <!-- Card 1: Total Collection -->
            <div class="col-md-3 grid-margin stretch-card">
              <div class="card shadow-sm border-0" style="border-radius: 8px;">
                <div class="card-body">
                  <div class="d-flex justify-content-between align-items-center mb-2">
                    <span class="text-muted" style="font-size: 14px;">总收款</span>
                    <span class="badge badge-success text-white" style="font-size: 10px; padding: 3px 6px;">实时</span>
                  </div>
                  <h3 class="font-weight-bold text-success mb-0">₹ <?php echo number_format($today_success, 2); ?></h3>
                </div>
              </div>
            </div>

            <!-- Card 2: Pending Collection -->
            <div class="col-md-3 grid-margin stretch-card">
              <div class="card shadow-sm border-0" style="border-radius: 8px;">
                <div class="card-body">
                  <div class="d-flex justify-content-between align-items-center mb-2">
                    <span class="text-muted" style="font-size: 14px;">待处理订单 (代收)</span>
                    <span class="badge badge-warning text-white" style="font-size: 10px; padding: 3px 6px;">实时</span>
                  </div>
                  <h3 class="font-weight-bold text-warning mb-0">₹ <?php echo number_format($today_pending, 2); ?></h3>
                </div>
              </div>
            </div>

            <!-- Card 3: Failed Collection -->
            <div class="col-md-3 grid-margin stretch-card">
              <div class="card shadow-sm border-0" style="border-radius: 8px;">
                <div class="card-body">
                  <div class="d-flex justify-content-between align-items-center mb-2">
                    <span class="text-muted" style="font-size: 14px;">失败订单</span>
                    <span class="badge badge-danger text-white" style="font-size: 10px; padding: 3px 6px;">实时</span>
                  </div>
                  <h3 class="font-weight-bold text-danger mb-0">₹ <?php echo number_format($today_failed, 2); ?></h3>
                </div>
              </div>
            </div>

            <!-- Card 4: Total PayIn Count -->
            <div class="col-md-3 grid-margin stretch-card">
              <div class="card shadow-sm border-0" style="border-radius: 8px;">
                <div class="card-body">
                  <div class="d-flex justify-content-between align-items-center mb-2">
                    <span class="text-muted" style="font-size: 14px;">总交易数</span>
                    <span class="badge badge-info text-white" style="font-size: 10px; padding: 3px 6px;">今日</span>
                  </div>
                  <h3 class="font-weight-bold text-dark mb-0"><?php echo $today_count; ?></h3>
                </div>
              </div>
            </div>
          </div>

          <!-- Payout & Balance Row -->
          <div class="row mb-4">
             <div class="col-12">
               <h3 class="font-weight-bold">提现与余额</h3>
             </div>
          </div>

          <div class="row">
             <!-- Card 1: Available Balance -->
             <div class="col-md-3 grid-margin stretch-card">
              <div class="card shadow-sm border-0" style="border-radius: 8px; background-color: #f3e5f5;">
                <div class="card-body">
                  <div class="d-flex justify-content-between align-items-center mb-2">
                    <span class="text-dark" style="font-size: 14px; font-weight: 600;">可用余额</span>
                    <span class="badge badge-primary text-white" style="font-size: 10px; padding: 3px 6px;">钱包</span>
                  </div>
                  <h3 class="font-weight-bold text-primary mb-0">₹ <?php echo number_format($available_balance, 2); ?></h3>
                </div>
              </div>
            </div>

            <!-- Card 2: Today Success Withdrawal -->
            <div class="col-md-3 grid-margin stretch-card">
              <div class="card shadow-sm border-0" style="border-radius: 8px;">
                <div class="card-body">
                  <div class="d-flex justify-content-between align-items-center mb-2">
                    <span class="text-muted" style="font-size: 14px;">今日提现</span>
                    <span class="badge badge-success text-white" style="font-size: 10px; padding: 3px 6px;">成功</span>
                  </div>
                  <h3 class="font-weight-bold text-success mb-0">₹ <?php echo number_format($today_payout_success, 2); ?></h3>
                </div>
              </div>
            </div>

            <!-- Card 3: Today Pending Withdrawal -->
            <div class="col-md-3 grid-margin stretch-card">
              <div class="card shadow-sm border-0" style="border-radius: 8px;">
                <div class="card-body">
                  <div class="d-flex justify-content-between align-items-center mb-2">
                    <span class="text-muted" style="font-size: 14px;">待处理提现</span>
                    <span class="badge badge-warning text-white" style="font-size: 10px; padding: 3px 6px;">请求</span>
                  </div>
                  <h3 class="font-weight-bold text-warning mb-0">₹ <?php echo number_format($today_payout_pending, 2); ?></h3>
                </div>
              </div>
            </div>

             <!-- Card 4: Total Requests Count -->
            <div class="col-md-3 grid-margin stretch-card">
              <div class="card shadow-sm border-0" style="border-radius: 8px;">
                <div class="card-body">
                  <div class="d-flex justify-content-between align-items-center mb-2">
                    <span class="text-muted" style="font-size: 14px;">总请求数</span>
                    <span class="badge badge-dark text-white" style="font-size: 10px; padding: 3px 6px;">计数</span>
                  </div>
                  <h3 class="font-weight-bold text-dark mb-0"><?php echo $today_payout_requests; ?></h3>
                </div>
              </div>
            </div>
          </div>


          <div class="row">
            <div class="col-md-12 stretch-card">
              <div class="card">
                <div class="card-body">
                  <p class="card-title">近期交易</p>
                  <div class="table-responsive">
                    <table id="recent-purchases-listing" class="table">
                      <thead>
                        <tr>
                            <th>用户</th>
                            <th>日期</th>
                            <th>订单号</th>
                            <th>金额</th>
                            <th>应用</th>
                            <th>商户</th>
                            <th>UTR</th>
                            <th>状态</th>
                        </tr>
                      </thead>
                      <tbody>
<?php if($userdata['usertype']=="mainadmin") {?>	  				  
<?php
$stmt = $conn->prepare("select * from create_orders ORDER BY `id` DESC LIMIT 5");
$stmt->execute();
$sl=1;
while($row=$stmt->fetch()) {

$status = '<span class="badge badge-info">Pending</span>';
if($row['txn_status']== 'SUCCESS'){
$status = '<span class="badge badge-success">Success</span>';    
}
if($row['txn_status']== 'PENDING'){
$status = '<span class="badge badge-info">Pending</span>';    
}
if($row['txn_status']== 'FAILED'){
$status = '<span class="badge badge-danger">Failed</span>';    
}
    echo "<tr>
    <td style='display:none;'>".$sl."</td>
     <td class='text-dark'>".$row['user']."</td>
     <td class='text-dark'>".strtoupper($row['date'])."</td>
    <td class='text-dark'>".$row['orderid']."</td>
    <td style='font-size:13px' class='text-dark'>Rs. ".(isset($row['amount']) ? strtoupper($row['amount']) : '')."</td>
    <td style='font-size:13px' class='text-dark'>".((isset($row['received_from']) && strtoupper($row['received_from']) == 'RSPAY') ? 'pay2inr' : (isset($row['received_from']) ? strtoupper($row['received_from']) : ''))."</td>
    <td style='font-size:13px' class='text-dark'>".((isset($row['merchant_name']) && strtoupper($row['merchant_name']) == 'RSPAY') ? 'pay2inr' : (isset($row['merchant_name']) ? strtoupper($row['merchant_name']) : ''))."</td>
    <td style='font-size:13px' class='text-dark'>".(isset($row['utr_number']) ? strtoupper($row['utr_number']) : '')."</td>
    <td class='text-primary'><i>".$status."</i></td>
  </tr>";
$sl++;}							
?>					
<?php
}else{
?>
<?php
$stmt = $conn->prepare("select * from create_orders WHERE user = ? ORDER BY `id` DESC LIMIT 5");
$stmt->execute([$userdata['username']]);
$sl=1;
while($row=$stmt->fetch()) {
$status = '<span class="badge badge-info">Pending</span>';
if($row['txn_status']== 'SUCCESS'){
$status = '<span class="badge badge-success">Success</span>';    
}
if($row['txn_status']== 'PENDING'){
$status = '<span class="badge badge-info">Pending</span>';    
}
if($row['txn_status']== 'FAILED'){
$status = '<span class="badge badge-danger">Failed</span>';    
}

    echo "<tr>
    <td style='display:none;'>".$sl."</td>
     <td class='text-dark'>".$row['user']."</td>
     <td class='text-dark'>".strtoupper($row['date'])."</td>
    <td class='text-dark'>".$row['orderid']."</td>
    <td style='font-size:13px' class='text-dark'>Rs. ".(isset($row['amount']) ? strtoupper($row['amount']) : '')."</td>
    <td style='font-size:13px' class='text-dark'>".((isset($row['received_from']) && strtoupper($row['received_from']) == 'RSPAY') ? 'pay2inr' : (isset($row['received_from']) ? strtoupper($row['received_from']) : ''))."</td>
    <td style='font-size:13px' class='text-dark'>".((isset($row['merchant_name']) && strtoupper($row['merchant_name']) == 'RSPAY') ? 'pay2inr' : (isset($row['merchant_name']) ? strtoupper($row['merchant_name']) : ''))."</td>
    <td style='font-size:13px' class='text-dark'><b>".(isset($row['utr_number']) ? strtoupper($row['utr_number']) : '')."</b></td>
    <td class='text-primary'><i>".$status."</i></td>
  </tr>";
$sl++;}							
?>
<?php
}
?>                          

                        
                      </tbody>
                    </table>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <!-- content-wrapper ends -->
        <!-- partial:partials/_footer.html -->
        <footer class="footer">
          <div class="d-sm-flex justify-content-center justify-content-sm-between">
            <span class="text-muted text-center text-sm-left d-block d-sm-inline-block"><?php echo $webdata['copyright'];?>.</span>
            <span class="float-none float-sm-right d-block mt-1 mt-sm-0 text-center"><?php echo $webdata['webname']; ?> & made with <i class="mdi mdi-heart text-danger"></i></span>
          </div>
        </footer>
        <!-- partial -->
      </div>
      <!-- main-panel ends -->
    </div>
    <!-- page-body-wrapper ends -->
  </div>
  <!-- container-scroller -->

  <!-- plugins:js -->
  <script src="../assets/vendors/base/vendor.bundle.base.js"></script>
  <!-- endinject -->
  <!-- Plugin js for this page-->
  <script src="../assets/vendors/chart.js/Chart.min.js"></script>
  <script src="../assets/vendors/datatables.net/jquery.dataTables.js"></script>
  <script src="../assets/vendors/datatables.net-bs4/dataTables.bootstrap4.js"></script>
  <!-- End plugin js for this page-->
  <!-- inject:js -->
  <script src="../assets/js/off-canvas.js"></script>
  <script src="../assets/js/hoverable-collapse.js"></script>
  <script src="../assets/js/template.js"></script>
  <!-- endinject -->
  <!-- Custom js for this page-->
  <script src="../assets/js/dashboard.js"></script>
  <script src="../assets/js/data-table.js"></script>
  <script src="../assets/js/jquery.dataTables.js"></script>
  <script src="../assets/js/dataTables.bootstrap4.js"></script>
  <!-- End custom js for this page-->
</body>

</html>

