<?php
header("Content-Type: text/plain"); // IMPORTANT: plain text
require('dbcon.php');

// Read JSON input
$data = json_decode(file_get_contents("php://input"), true);

$identifier = $data['emailOrPhone'] ?? null;
$amount = $data['amount'] ?? null;

if (!$identifier) {
    echo "ERROR_NO_IDENTIFIER";
    exit;
}

// Fetch user securely
$stmt = $pdo->prepare("SELECT name, account_no, bank_name, city FROM users WHERE email = ? OR phone = ?");
$stmt->execute([$identifier, $identifier]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$user) {
    echo "USER_NOT_FOUND";
    exit;
}

// Prepare required fields
$name = strtoupper(substr($user['name'], 0, 25));
$account = $user['account_no'];
$bank = strtoupper($user['bank_name']);
$city = strtoupper($user['city'] ?? 'JOS');

// NQR only supports NGN
$currency = "566";

// Your valid NIBSS Merchant ID (replace with your real one)
$merchantID = "YOUR_VALID_NIBSS_MERCHANT_ID"; // e.g., 0014XXXXXXXXXXXX

// Optional amount in kobo (NQR expects smallest currency unit)
$amountField = "";
if ($amount) {
    $amountField = "54" . str_pad(strlen($amount), 2, "0", STR_PAD_LEFT) . $amount;
}

// Build payload
$payload =
    "000201" .                // Payload indicator
    "010212" .                // Version / Dynamic
    "26" . str_pad(strlen($merchantID), 2, "0", STR_PAD_LEFT) . $merchantID . // Merchant info
    "52" . "0000" .           // MCC (0000 default)
    "53" . $currency .        // Currency code
    $amountField .
    "58" . "02NG" .           // Country code
    "59" . str_pad(strlen($name), 2, "0", STR_PAD_LEFT) . $name .
    "60" . str_pad(strlen($city), 2, "0", STR_PAD_LEFT) . $city;

// Function to calculate CRC16 as per NIBSS spec
function crc16($payload) {
    $crc = 0xFFFF;
    $poly = 0x1021;
    $bytes = str_split($payload);
    foreach ($bytes as $b) {
        $c = ord($b);
        $crc ^= ($c << 8);
        for ($i = 0; $i < 8; $i++) {
            if (($crc & 0x8000) != 0) {
                $crc = (($crc << 1) ^ $poly) & 0xFFFF;
            } else {
                $crc = ($crc << 1) & 0xFFFF;
            }
        }
    }
    return strtoupper(dechex($crc));
}

// Append CRC16 to payload
$payload .= "63" . "04" . crc16($payload);

echo $payload;

?>
