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

// Fetch RSPay Merchant Data
$merch_stmt = $conn->prepare("SELECT * FROM add_merchant WHERE user = ? AND merchant_name = 'RSPay'");
$merch_stmt->execute([$userdata['username']]);
$merch_row = $merch_stmt->fetch(PDO::FETCH_ASSOC);

// Defaults (Fallback to loginusers if add_merchant data missing)
$merchant_id_display = $merch_row['merchant_id'] ?? '未生成';
$api_key_display = $merch_row['access_token'] ?? $userdata['api_key'];
$callback_url_display = $merch_row['callback_url'] ?? $userdata['callback_url'];

// Handle Form Submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $msg_html = '';
    
    if (isset($_POST['action']) && $_POST['action'] == 'Generate New Key') {
        // Generate new API Key
        $new_key = 'sk_' . bin2hex(random_bytes(16));
        
        // Update loginusers
        $sql_u = "UPDATE `loginusers` SET `api_key` = :api_key WHERE id = :id";
        $stmt_u = $conn->prepare($sql_u);
        $stmt_u->execute([':api_key' => $new_key, ':id' => $userdata['id']]);
        
        // Update add_merchant
        if ($merch_row) {
            $sql_m = "UPDATE `add_merchant` SET `access_token` = :token WHERE user = :user AND merchant_name = 'RSPay'";
            $stmt_m = $conn->prepare($sql_m);
            $stmt_m->execute([':token' => $new_key, ':user' => $userdata['username']]);
        } else {
            // If entry doesn't exist, create it (Safety net)
            $user_merchant_id = 'MER_' . time() . rand(100,999); 
             $sql_ins = "INSERT INTO `add_merchant`(`user`, `user_id`, `merchant_name`, `status`, `last_sync`, `access_token`, `merchant_id`) 
                         VALUES (:user, :uid, 'RSPay', 'Active', NOW(), :token, :mid)";
             $stmt_ins = $conn->prepare($sql_ins);
             $stmt_ins->execute([
                 ':user' => $userdata['username'],
                 ':uid' => $userdata['id'],
                 ':token' => $new_key,
                 ':mid' => $user_merchant_id
             ]);
        }
        
        $msg_html = '<div class="alert alert-success">新 API 密钥生成成功！</div>';
        // Refresh values
        $api_key_display = $new_key;
        if(isset($user_merchant_id)) $merchant_id_display = $user_merchant_id;
        
    } elseif (isset($_POST['callback_url'])) {
        // Update Callback URL
        $new_url = filter_var($_POST['callback_url'], FILTER_SANITIZE_URL);
        
        // Update loginusers
        $sql_u = "UPDATE `loginusers` SET `callback_url` = :url WHERE id = :id";
        $stmt_u = $conn->prepare($sql_u);
        $stmt_u->execute([':url' => $new_url, ':id' => $userdata['id']]);
        
        // Update add_merchant
        if ($merch_row) {
             $sql_m = "UPDATE `add_merchant` SET `callback_url` = :url WHERE user = :user AND merchant_name = 'RSPay'";
             $stmt_m = $conn->prepare($sql_m);
             $stmt_m->execute([':url' => $new_url, ':user' => $userdata['username']]);
        }
        
        $msg_html = '<div class="alert alert-success">回调 URL 保存成功！</div>';
        $callback_url_display = $new_url;
    }
    
    // Redirect to clear post
    if ($msg_html) {
         echo $msg_html . '<script>setTimeout(function(){ window.location = ""; }, 1500);</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">API 设置 (RSPay)</h6>
            </div>
            <div class="card-body">
                
                <div class="table-responsive">
                    <table class="table table-bordered" width="100%" cellspacing="0">
                        <thead>
                            <tr>
                                <th class='text-primary' style="width: 20%;">设置</th>
                                <th class='text-primary' style="width: 60%;">值</th>
                                <th class='text-primary' style="width: 20%;">操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            <!-- Merchant ID Row -->
                            <tr>
                                <td class='text-primary font-weight-bold'>商户 ID</td>
                                <td>
                                    <code id="merchId" style="font-size: 1.1em;"><?php echo htmlspecialchars($merchant_id_display); ?></code>
                                </td>
                                <td>
                                    <button class="btn btn-secondary btn-sm" onclick="copyToClipboard('merchId')">复制</button>
                                </td>
                            </tr>
                            
                            <!-- API Key Row -->
                            <tr>
                                <td class='text-primary font-weight-bold'>API 密钥</td>
                                <td>
                                    <code id="apiKey" style="font-size: 1.1em;"><?php echo htmlspecialchars($api_key_display); ?></code>
                                </td>
                                <td>
                                    <div class="d-flex">
                                        <button class="btn btn-secondary btn-sm mr-2" onclick="copyToClipboard('apiKey')">复制</button>
                                        <form action="" method="post">
                                            <input type="submit" name="action" class="btn btn-warning btn-sm" value="Generate New Key" onclick="return confirm('您确定吗？这将使旧密钥失效。')">
                                        </form>
                                    </div>
                                </td>
                            </tr>
                            
                            <!-- Callback URL Row -->
                            <tr>
                                <td class='text-primary font-weight-bold'>回调 URL</td>
                                <td colspan="2">
                                    <form action="" method="post" class="form-inline" style="width: 100%">
                                        <div class="input-group" style="width: 100%">
                                            <input type="url" name="callback_url" class="form-control" 
                                                   value="<?php echo htmlspecialchars($callback_url_display); ?>" 
                                                   placeholder="https://example.com/callback" required>
                                            <div class="input-group-append">
                                                <button type="submit" class="btn btn-primary">保存 URL</button>
                                            </div>
                                        </div>
                                    </form>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                    
                    <!-- Callback Documentation -->
                    <div class="mt-4 p-3 bg-light rounded border">
                        <h5 class="text-dark">回调参数：</h5>
                        <p>我们发送带有此 JSON 主体的 POST 请求：</p>
                        <pre class="bg-dark text-white p-3 rounded">
{
    "user_id": "<?php echo htmlspecialchars($userdata['username']); ?>",
    "merchant_id": "<?php echo htmlspecialchars($merchant_id_display); ?>",
    "order_id": "ORDER12345",
    "amount": "100.00",
    "status": "SUCCESS",
    "utr": "123456789012",
    "txn_id": "txn_...",
    "created_at": "2023-01-01 12:00:00"
}</pre>
                    </div>
                </div>
            </div>
        </div>
    </div>

<script>
function copyToClipboard(elementId) {
  var copyText = document.getElementById(elementId);
  var range = document.createRange();
  range.selectNode(copyText);
  window.getSelection().removeAllRanges(); 
  window.getSelection().addRange(range); 
  document.execCommand("copy");
  window.getSelection().removeAllRanges();
  alert("已复制！");
}
</script>

<!-- /.container-fluid -->
<?php
require_once('../database/footer.php');
?>