<?php
session_start();
error_reporting(0); 

require_once __DIR__ . '/includes/config.php';

// Admin Authentication
if (!isset($_SESSION['admin_id'])) {
    if (isset($_POST['action']) && $_POST['action'] === 'check_status') {
        echo json_encode(['success' => false, 'message' => 'Unauthorized.']);
        exit;
    }
    header("Location: login.php"); exit;
}

// ============================================================================
// 🔥 BACKEND LOGIC: TOPPAY STATUS CHECKER (BY ORDER ID) 🔥
// ============================================================================
if (isset($_POST['action']) && $_POST['action'] === 'check_status') {
    header('Content-Type: application/json');

    $order_id_input = isset($_POST['order_id']) ? trim($_POST['order_id']) : '';
    $txn_type = isset($_POST['txn_type']) ? $_POST['txn_type'] : '';

    if (empty($order_id_input) || empty($txn_type)) {
        echo json_encode(['success' => false, 'message' => 'Please enter the full Order ID.']);
        exit;
    }

    $merchant_id = 191; 
    $secret_key  = "77b900bc099a80be6d2c8ec96d4ee0d1"; 
    $query_url   = "https://api.toppay-app.com/api/pay/query/order"; 
    $server_ip   = "187.127.128.155"; 

    // 1. Database mein record dhoondhna (Status update karne ke liye)
    if ($txn_type === 'withdraw') {
        $stmt = $conn->prepare("SELECT id FROM withdrawals WHERE mch_transfer_id = ?");
        $api_type = 1; 
    } else {
        $stmt = $conn->prepare("SELECT id FROM deposits WHERE order_no = ?"); 
        $api_type = 0; 
    }

    $stmt->bind_param("s", $order_id_input);
    $stmt->execute();
    $res = $stmt->get_result();
    $row = $res->fetch_assoc();
    $stmt->close();

    if (!$row) {
        echo json_encode(['success' => false, 'message' => 'Order ID not found in your Database.']);
        exit;
    }

    $db_row_id = $row['id'];

    // 2. Prepare TopPay Payload & Signature
    $data = array(
        'type'            => (int)$api_type,
        'merchantId'      => (int)$merchant_id,
        'merchantOrderNo' => (string)$order_id_input
    );

    $sign_data = array();
    foreach($data as $key => $val) {
        if($val !== null && $val !== '') {
            $sign_data[$key] = $val;
        }
    }
    ksort($sign_data); 
    
    $sign_string = "";
    foreach($sign_data as $key => $val) {
        $sign_string .= $key . "=" . $val . "&";
    }
    $sign_string .= "secret=" . trim($secret_key);
    $data['sign'] = strtolower(md5($sign_string));

    // 3. Send cURL Request
    $ch = curl_init();
    $payload = json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);

    curl_setopt($ch, CURLOPT_URL, $query_url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_INTERFACE, $server_ip); 
    curl_setopt($ch, CURLOPT_TIMEOUT, 15);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json',
        'Accept: application/json',
        'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64)',
        'Content-Length: ' . strlen($payload)
    ));

    $response = curl_exec($ch);
    $err = curl_error($ch);
    curl_close($ch);

    if ($err) {
        echo json_encode(['success' => false, 'message' => 'Connection Error: ' . $err]);
        exit;
    }

    $json = json_decode($response, true);

    // 4. Handle Response & Update DB
    if ($json && $json['code'] == 200 && isset($json['data']['status'])) {
        $status = (int)$json['data']['status'];
        $table = ($txn_type === 'withdraw') ? 'withdrawals' : 'deposits';
        
        if ($status === 1 || $status === 4) {
            $conn->query("UPDATE $table SET status='successful' WHERE id=$db_row_id");
            echo json_encode(['success' => true, 'status_text' => 'Successful ✅', 'message' => 'Status updated to SUCCESS in Database.']);
        } elseif ($status === 2 || $status === 3) {
            $conn->query("UPDATE $table SET status='rejected' WHERE id=$db_row_id");
            echo json_encode(['success' => true, 'status_text' => 'Rejected ❌', 'message' => 'Status updated to REJECTED in Database.']);
        } elseif ($status === 0) {
            echo json_encode(['success' => true, 'status_text' => 'Processing ⏳', 'message' => 'Gateway is still processing this order.']);
        }
    } else {
        $msg = $json['message'] ?? 'Signature Error or Invalid Order ID at TopPay.';
        echo json_encode(['success' => false, 'message' => $msg]);
    }
    exit; 
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Admin - TopPay Checker</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
  :root { --bg: #f3f4f6; --sidebar: #111827; --card: #ffffff; --text: #1f2937; --red: #ef4444; }
  * { box-sizing: border-box; } 
  body { margin: 0; font-family: -apple-system, sans-serif; background: var(--bg); color: var(--text); display: flex; }
  .sidebar { width: 250px; background: var(--sidebar); color: #fff; height: 100vh; position: fixed; padding: 20px; }
  .nav a { display: block; padding: 12px; color: #9ca3af; text-decoration: none; border-radius: 6px; margin-bottom: 5px; }
  .nav a.active { background: #374151; color: #fff; }
  .main { margin-left: 250px; padding: 40px; flex: 1; display: flex; justify-content: center; }
  .panel { background: var(--card); border-radius: 12px; padding: 30px; width: 100%; max-width: 500px; box-shadow: 0 4px 10px rgba(0,0,0,0.05); border: 1px solid #e5e7eb; }
  .form-group { margin-bottom: 20px; }
  .form-group label { display: block; margin-bottom: 8px; font-weight: 600; font-size: 14px; }
  .form-control { width: 100%; padding: 12px; border: 1px solid #d1d5db; border-radius: 6px; font-size: 15px; }
  .btn-check { display: block; width: 100%; padding: 14px; background: var(--red); color: #fff; border: none; border-radius: 6px; font-weight: 700; cursor: pointer; transition: 0.2s; }
  .btn-check:hover { background: #dc2626; }
  .btn-check:disabled { background: #fca5a5; }
</style>
</head>
<body>
<div class="sidebar">
  <div class="logo" style="font-size: 20px; margin-bottom: 30px;">COSCO ADMIN</div>
  <nav class="nav">
    <a href="dashboard.php">Dashboard</a>
    <a href="withdraw.php">Withdrawals</a>
    <a href="deposits.php">Deposits</a>
    <a class="active" href="topay-check_status.php">TopPay Checker</a>
    <a href="logout.php" style="color: #fca5a5; margin-top: 20px;">Logout</a>
  </nav>
</div>
<div class="main">
  <div class="panel">
    <h3 style="color: var(--red); margin-top:0; border-bottom: 1px solid #eee; padding-bottom: 15px;">TopPay Manual Checker</h3>
    <div style="background: #fef2f2; border: 1px solid #fecaca; padding: 20px; border-radius: 8px; margin-top: 20px;">
      <div class="form-group">
          <label>Check Type</label>
          <select id="check_txn_type" class="form-control">
              <option value="withdraw">Withdrawal (Payout)</option>
              <option value="deposit">Deposit (Collection)</option>
          </select>
      </div>
      <div class="form-group">
          <label>Full Order ID</label>
          <input type="text" id="order_id_input" class="form-control" placeholder="Example: OUT1774475726...">
      </div>
      <button class="btn-check" onclick="runCheck(this)">🔍 Verify Status</button>
    </div>
  </div>
</div>
<script>
function runCheck(btn) {
    let type = document.getElementById('check_txn_type').value;
    let oid = document.getElementById('order_id_input').value.trim();
    if(!oid) return alert("Please enter the Order ID");

    let oldText = btn.innerHTML;
    btn.innerHTML = "Verifying..."; btn.disabled = true;

    let fd = new FormData();
    fd.append('action', 'check_status');
    fd.append('order_id', oid);
    fd.append('txn_type', type);

    fetch('topay-check_status.php', { method: 'POST', body: fd })
    .then(r => r.json())
    .then(data => {
        btn.innerHTML = oldText; btn.disabled = false;
        if(data.success) {
            alert("✅ " + data.status_text + "\n" + data.message);
        } else {
            alert("❌ ERROR: " + data.message);
        }
    }).catch(e => {
        btn.innerHTML = oldText; btn.disabled = false;
        alert("Network Error");
    });
}
</script>
</body>
</html>