<?php
function generateSign($params, $secretKey) {
    unset($params['sign']);

    // Remove empty parameters
    $filteredParams = array_filter($params, function($v) {
        return $v !== '' && $v !== null;
    });

    // Sort by key ASCII order
    ksort($filteredParams);

    // Build key=value pairs joined by &
    $queryParts = [];
    foreach ($filteredParams as $key => $value) {
        $queryParts[] = $key . '=' . trim((string)$value);
    }
    $queryString = implode('&', $queryParts);

    // Append &key=secretKey exactly
    $stringToSign = $queryString . '&key=' . $secretKey;

    // Uncomment to debug signature string
    // echo "<pre>String to sign:\n" . htmlspecialchars($stringToSign) . "</pre>";

    $sign = md5($stringToSign);

    // Uncomment to debug md5 signature
    // echo "<pre>MD5 Signature:\n" . $sign . "</pre>";

    return $sign;
}

$response = null;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $payoutType = $_POST['payoutType'];
    $secretKey = "ioQxXoydAMbfcyKhDTYr"; // API secret key
    $appNo = trim($_POST['appNo']);
    $callbackUrl = trim($_POST['callbackUrl']);
    $amount = number_format((float)$_POST['amount'], 2, '.', '');
    $orderCode = trim($_POST['orderCode']) ?: 'ORD' . time();
    $remark = trim($_POST['remark']);
    $accountName = trim($_POST['accountName']);

    $commonFields = [
        "amount" => $amount,
        "appNo" => $appNo,
        "callbackUrl" => $callbackUrl,
        "orderCode" => $orderCode,
        "remark" => $remark,
        "accountName" => $accountName,
    ];

    if ($payoutType === 'bank') {
        $fields = array_merge($commonFields, [
            "accountNumber" => trim($_POST['accountNumber']),
            "ifsc" => trim($_POST['ifsc']),
        ]);
        $url = "https://api.mlpayment.cc/open-api/trade/payout";
    } else {
        $fields = array_merge($commonFields, [
            "upi" => trim($_POST['upi']),
        ]);
        $url = "https://api.mlpayment.cc/open-api/trade/upi/payout";
    }

    $fields['sign'] = generateSign($fields, $secretKey);

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type:application/json']);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $apiResponse = curl_exec($ch);
    curl_close($ch);

    $response = json_decode($apiResponse, true);
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Manual Payout - Modern Form</title>

    <!-- Bootstrap 5 CSS CDN -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">

    <style>
        body {
            background: #f8f9fa;
        }
        .form-container {
            max-width: 600px;
            margin: 40px auto;
            background: #fff;
            padding: 30px 40px;
            border-radius: 10px;
            box-shadow: 0 4px 15px rgb(0 0 0 / 0.1);
        }
        .form-title {
            margin-bottom: 30px;
            text-align: center;
            font-weight: 600;
            color: #343a40;
        }
        .form-text-muted {
            font-size: 0.85rem;
        }
    </style>
</head>
<body>

<div class="form-container">
    <h2 class="form-title">Manual Payout Form</h2>
    <form method="POST" novalidate>
        <div class="mb-3">
            <label for="payoutType" class="form-label">Payout Type</label>
            <select id="payoutType" name="payoutType" class="form-select" onchange="toggleFields(this.value)" required>
                <option value="bank" selected>Bank</option>
                <option value="upi">UPI</option>
            </select>
        </div>

        <div class="mb-3">
            <label for="accountName" class="form-label">Account Holder Name</label>
            <input type="text" id="accountName" name="accountName" class="form-control" required />
        </div>

        <div id="bankFields">
            <div class="mb-3">
                <label for="accountNumber" class="form-label">Account Number</label>
                <input type="text" id="accountNumber" name="accountNumber" class="form-control" />
            </div>
            <div class="mb-3">
                <label for="ifsc" class="form-label">IFSC Code</label>
                <input type="text" id="ifsc" name="ifsc" class="form-control" />
            </div>
        </div>

        <div id="upiFields" style="display:none;">
            <div class="mb-3">
                <label for="upi" class="form-label">UPI ID</label>
                <input type="text" id="upi" name="upi" class="form-control" />
            </div>
        </div>

        <div class="mb-3">
            <label for="amount" class="form-label">Amount</label>
            <input type="number" step="0.01" min="0" id="amount" name="amount" class="form-control" required />
            <div class="form-text form-text-muted">Enter amount with up to 2 decimal places.</div>
        </div>

        <div hidden class="mb-3">
            <label for="appNo" class="form-label">Merchant Code (appNo)</label>
            <input type="text" id="appNo" name="appNo" class="form-control" value="Bfun" required />
        </div>

        <div hidden class="mb-3">
            <label for="callbackUrl" class="form-label">Callback URL</label>
            <input type="url" id="callbackUrl" name="callbackUrl" class="form-control" 
                   value="https://kilicow.rdnslvhost.in.net/mlpaypayoutcallback.php" />
        </div>

        <div class="mb-3">
            <label for="orderCode" class="form-label">Order Code</label>
            <input type="text" id="orderCode" name="orderCode" class="form-control" placeholder="Auto-generated if left blank" />
        </div>

        <div class="mb-3">
            <label for="remark" class="form-label">Remark</label>
            <input type="text" id="remark" name="remark" class="form-control" />
        </div>

        <button type="submit" class="btn btn-primary w-100">Send Payout</button>
    </form>

    <?php if ($response): ?>
        <div class="mt-4">
            <h4>API Response</h4>
            <pre class="bg-light p-3 border rounded" style="max-height: 300px; overflow-y: auto;">
<?php echo htmlspecialchars(json_encode($response, JSON_PRETTY_PRINT)); ?>
            </pre>
        </div>
    <?php endif; ?>
</div>

<!-- Bootstrap 5 JS Bundle (Popper + JS) -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

<script>
function toggleFields(value) {
    const bankFields = document.getElementById('bankFields');
    const upiFields = document.getElementById('upiFields');
    if(value === 'bank') {
        bankFields.style.display = 'block';
        upiFields.style.display = 'none';
    } else {
        bankFields.style.display = 'none';
        upiFields.style.display = 'block';
    }
}

// Initialize on page load
document.addEventListener('DOMContentLoaded', function() {
    const select = document.getElementById('payoutType');
    toggleFields(select.value);
});
</script>

</body>
</html>
