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

// Ensure database columns exist for callback functionality
try {
    $conn->exec("ALTER TABLE add_merchant ADD COLUMN callback_url VARCHAR(500) DEFAULT NULL");
} catch (Exception $e) {}

try {
    $conn->exec("ALTER TABLE add_merchant ADD COLUMN callback_ip VARCHAR(255) DEFAULT NULL");
} catch (Exception $e) {}

// Ensure password column is long enough for Bcrypt hashes
try {
    $conn->exec("ALTER TABLE loginusers MODIFY password VARCHAR(255)");
} catch (Exception $e) {}

$message = "";

// 1. Determine Target User (If MainAdmin views another user)
// Currently defaulting to logged-in user, but setup for extensibility
$target_user = $userdata['username'];
if (isset($_GET['user']) && $userdata['usertype'] == 'mainadmin') {
    $target_user = $_GET['user']; 
    // TODO: Verify user exists if needed
}

// 2. Handle Form Submission
if (isset($_POST['update_settings'])) {
    
    $callback_url = $_POST['callback_url'] ?? '';
    $callback_ip = $_POST['callback_ip'] ?? '';
    $new_password = $_POST['new_password'] ?? '';
    
    // Update Add Merchant Table
    $upd_merchant = $conn->prepare("UPDATE add_merchant SET callback_url = ?, callback_ip = ? WHERE user = ? AND merchant_name = 'RSPay'");
    $upd_merchant->execute([$callback_url, $callback_ip, $target_user]);
    
    // Update Password if not empty
    if (!empty($new_password)) {
        $pass_hash = password_hash($new_password, PASSWORD_DEFAULT);
        $upd_pass = $conn->prepare("UPDATE loginusers SET password = ? WHERE username = ?");
        $upd_pass->execute([$pass_hash, $target_user]);
        $message = '<div class="alert alert-success">详情和密码更新成功！</div>';
    } else {
        $message = '<div class="alert alert-success">设置更新成功！</div>';
    }
}

// 3. Fetch User & Merchant Data
$stmt_user = $conn->prepare("SELECT * FROM loginusers WHERE username = ?");
$stmt_user->execute([$target_user]);
$curr_user = $stmt_user->fetch(PDO::FETCH_ASSOC);

$stmt_merch = $conn->prepare("SELECT * FROM add_merchant WHERE user = ? AND merchant_name = 'RSPay'");
$stmt_merch->execute([$target_user]);
$curr_merch = $stmt_merch->fetch(PDO::FETCH_ASSOC);

// Fallback if no merchant entry found (Unlikely if created properly)
if (!$curr_merch) {
    $curr_merch = ['merchant_id' => 'N/A', 'access_token' => 'N/A', 'callback_url' => '', 'callback_ip' => ''];
}

?>

<div class="main-panel">
    <div class="content-wrapper">
        
        <div class="row">
            <div class="col-md-8 offset-md-2 grid-margin stretch-card">
                <div class="card shadow">
                    <div class="card-header bg-primary py-3">
                        <h6 class="m-0 font-weight-bold text-white">RSPay 集成详情</h6>
                    </div>
                    <div class="card-body">
                        <?php echo $message; ?>
                        
                        <form class="forms-sample" method="POST" action="">
                            <h5 class="text-primary mb-3"><i class="mdi mdi-account-key"></i> 凭证</h5>
                            
                            <div class="form-group row">
                                <div class="col-sm-6">
                                    <label class="font-weight-bold">用户名（手机）</label>
                                    <input type="text" class="form-control" value="<?php echo htmlspecialchars($curr_user['mobile_no'] ?? $target_user); ?>" readonly disabled>
                                </div>
                                <div class="col-sm-6">
                                    <label class="font-weight-bold">更改密码</label>
                                    <input type="text" class="form-control" name="new_password" placeholder="输入新密码以重置">
                                    <small class="text-muted">留空以保留当前密码。</small>
                                </div>
                            </div>

                            <div class="form-group">
                                <label class="font-weight-bold text-success">商户 ID</label>
                                <div class="input-group">
                                    <input type="text" class="form-control" value="<?php echo htmlspecialchars($curr_merch['merchant_id']); ?>" id="merchantId" readonly>
                                    <div class="input-group-append">
                                        <button class="btn btn-outline-secondary" type="button" onclick="copyToClipboard('merchantId')">复制</button>
                                    </div>
                                </div>
                            </div>

                            <div class="form-group">
                                <label class="font-weight-bold text-danger">API 密钥 / 访问令牌</label>
                                <div class="input-group">
                                    <input type="text" class="form-control" value="<?php echo htmlspecialchars($curr_merch['access_token']); ?>" id="apiKey" readonly>
                                    <div class="input-group-append">
                                        <button class="btn btn-outline-secondary" type="button" onclick="copyToClipboard('apiKey')">复制</button>
                                    </div>
                                </div>
                            </div>

                            <hr>
                            <h5 class="text-primary mb-3"><i class="mdi mdi-webhook"></i> 回调配置</h5>

                            <div class="form-group">
                                <label class="font-weight-bold">回调 URL</label>
                                <input type="url" class="form-control" name="callback_url" placeholder="https://your-domain.com/api/callback" value="<?php echo htmlspecialchars($curr_merch['callback_url'] ?? ''); ?>">
                                <small class="text-muted">我们将向此 URL 发送交易更新。</small>
                            </div>

                            <div class="form-group">
                                <label class="font-weight-bold">白名单回调 IP</label>
                                <input type="text" class="form-control" name="callback_ip" placeholder="192.168.1.1" value="<?php echo htmlspecialchars($curr_merch['callback_ip'] ?? ''); ?>">
                                <small class="text-muted">可选：仅限制对此 IP 地址的回调。</small>
                            </div>

                            <button type="submit" name="update_settings" class="btn btn-primary btn-block btn-lg mt-4">保存更改</button>
                        </form>
                    </div>
                </div>
            </div>
        </div>
        
    </div>
    
<script>
function copyToClipboard(elementId) {
  var copyText = document.getElementById(elementId);
  copyText.select();
  copyText.setSelectionRange(0, 99999); /* For mobile devices */
  document.execCommand("copy");
  
  // Optional: Alert the user
  // alert("Copied: " + copyText.value);
  
  // Better feedback: Change button text temporarily
  var btn = copyText.nextElementSibling.querySelector('button');
  var originalText = btn.innerText;
  btn.innerText = "已复制！";
  setTimeout(function(){ btn.innerText = originalText; }, 1500);
}
</script>

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