<?php 
// config.php ki jagah yeh variables define karen apne credentials ke sath:
$merchantNo = "1811526477";
$appSecret = "4b46ecb8294b47f48bc2dc237afe2680";
$apiBase = "https://openapi-prod.kilipayment.com/pak-pay"; // apne gateway ka base URL set karen

function generateSign($data, $secret) {
    if (isset($data['sign'])) unset($data['sign']);
    ksort($data);
    $str = '';
    foreach ($data as $key => $value) {
        $str .= $key . '=' . $value;
    }
    $str .= $secret;
    return strtolower(md5($str));
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>KiliPay Payout Form with Debug</title>
    <style>
        body { font-family: Arial; margin: 40px; background: #f0f2f5; }
        form { max-width: 500px; margin: auto; background: white; padding: 20px; border-radius: 8px; }
        input, select { width: 100%; padding: 10px; margin-bottom: 15px; font-size: 1rem; }
        input[type="submit"] { background-color: #007bff; color: white; border: none; cursor: pointer; }
        input[type="submit"]:hover { background-color: #0056b3; }
        .response { white-space: pre-wrap; background: #fff; padding: 15px; border: 1px solid #ccc; max-width: 500px; margin: 20px auto; border-radius: 8px; }
        .error { color: red; font-weight: bold; }
    </style>
</head>
<body>

<h2 style="text-align:center;">KiliPay Payout Portal (PKR) - Debug Enabled</h2>

<form method="post" novalidate>
    <input type="text" name="tradeNo" placeholder="Order ID (Unique)" required>
    <input type="text" name="name" placeholder="Payee Name" required>
    <input type="text" name="customerCert" placeholder="CNIC (13 digits, no dash)" required pattern="\d{13}">
    <input type="email" name="email" placeholder="Email" required>
    <input type="text" name="mobile" placeholder="Mobile (e.g. 3111234567)" required pattern="3\d{9}">
    <input type="number" name="amount" placeholder="Amount in PKR (Min 100)" required min="100" step="1">
    <select name="accountType" required>
        <option value="">--Select Account Type--</option>
        <option value="BANK">BANK</option>
        <option value="WALLET">WALLET</option>
    </select>
    <input type="text" name="bankName" placeholder="Bank Name (e.g. ALLIED_BANK_LIMITED or JAZZCASH)" required>
    <input type="text" name="bankNumber" placeholder="Bank Account/Card Number or Wallet Mobile" required>
    <input type="text" name="remark" placeholder="Remark (e.g. Payment for invoice #1001)" required>
    <input type="submit" name="submit" value="Send Payout">
</form>

<?php
if (isset($_POST['submit'])) {
    echo "<div class='response'><strong>Debug Info:</strong><br>";
    // Validation
    $errors = [];
    
    if (!preg_match('/^\d{13}$/', $_POST['customerCert'])) {
        $errors[] = "Invalid CNIC format. Must be exactly 13 digits.";
    }
    if (!preg_match('/^3\d{9}$/', $_POST['mobile'])) {
        $errors[] = "Invalid mobile format. Must start with 3 and be 10 digits.";
    }
    $amount = intval($_POST['amount']);
    if ($amount < 100) {
        $errors[] = "Amount must be at least 100 PKR.";
    }
    if (empty($_POST['accountType']) || !in_array($_POST['accountType'], ['BANK','WALLET'])) {
        $errors[] = "Account type must be BANK or WALLET.";
    }
    if (empty($_POST['bankName'])) {
        $errors[] = "Bank name is required.";
    }
    if (empty($_POST['bankNumber'])) {
        $errors[] = "Bank number/account number is required.";
    }
    if (empty($_POST['tradeNo'])) {
        $errors[] = "TradeNo is required.";
    }

    if (count($errors) > 0) {
        echo "<div class='error'>Validation Errors:<br>- " . implode("<br>- ", $errors) . "</div></div>";
        exit;
    }

    // Prepare data
    $timestamp = round(microtime(true) * 1000);
    $tradeNo = $_POST['tradeNo'] . '_' . time(); // Make tradeNo unique

    $data = [
        "amount" => (string)$amount,
        "tradeNo" => $tradeNo,
        "name" => trim($_POST['name']),
        "customerCert" => trim($_POST['customerCert']),
        "email" => trim($_POST['email']),
        "mobile" => trim($_POST['mobile']),
        "accountType" => $_POST['accountType'],
        "bankName" => strtoupper(trim($_POST['bankName'])),
        "bankNumber" => trim($_POST['bankNumber']),
        "notifyUrl" => "https://fastpay.rdnslvhost.in.net/payout-system/config.php", // replace with your callback URL
        "remark" => trim($_POST['remark']),
        "timestamp" => (string)$timestamp
    ];

    $data['sign'] = generateSign($data, $appSecret);

    echo "<strong>Request Payload:</strong><br>" . htmlspecialchars(json_encode($data, JSON_PRETTY_PRINT)) . "<br><br>";

    // cURL call
    $ch = curl_init("$apiBase/v1/kilipayPK/payout");
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        "merchantNo: $merchantNo",
        "Content-Type: application/json"
    ]);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    $response = curl_exec($ch);

    if (curl_errno($ch)) {
        echo "<div class='error'>Curl error: " . curl_error($ch) . "</div>";
    } else {
        echo "<strong>API Response:</strong><br>" . htmlspecialchars($response);
    }
    curl_close($ch);

    echo "</div>";
}
?>

</body>
</html>
