<?php
if (!defined("ADDFUNDS")) {
    http_response_code(404);
    exit();
}

$response = [];

try {
    // Ensure methodExtras exists (fetch if not passed)
    if (!isset($methodExtras) || !is_array($methodExtras)) {
        $methodQuery = $conn->prepare("SELECT * FROM paymentmethods WHERE methodId=:id LIMIT 1");
        $methodQuery->execute(["id" => $methodId]);
        $methodRow = $methodQuery->fetch(PDO::FETCH_ASSOC);
        $methodExtras = $methodRow ? json_decode($methodRow["methodExtras"], true) : [];
    }

    // Accept both camelCase and snake_case keys from DB
    $merchantId = trim($methodExtras["merchantId"] ?? $methodExtras["merchant_id"] ?? "");
    $apiKey     = trim($methodExtras["apiKey"] ?? $methodExtras["api_key"] ?? $methodExtras["paymentKey"] ?? "");

    if (empty($merchantId) || empty($apiKey)) {
        throw new Exception("Cryptomus configuration missing in admin panel.");
    }

    // create unique order id and save pending payment before redirect
    $order_id   = uniqid("crypto_");
    $amount     = number_format($paymentAmount, 2, '.', '');
    $currency   = $methodCurrency ?: "USD";

    // prepare payload for Cryptomus API — use snake_case keys expected by Cryptomus
    $payload = [
        "merchant_id"   => $merchantId,
        "amount"        => $amount,
        "currency"      => $currency,
        "order_id"      => $order_id,
        "url_return"    => site_url("addfunds"),
        "url_callback"  => site_url("payment/cryptomus"),
        "lifetime"      => 3600
    ];

    $jsonData = json_encode($payload, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);

    // sign as Cryptomus expects: md5(base64_encode(body) + apiKey)
    $signature = md5(base64_encode($jsonData) . $apiKey);

    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => "https://api.cryptomus.com/v1/payment",
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => [
            "merchant: " . $merchantId,
            "sign: " . $signature,
            "Content-Type: application/json"
        ],
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => $jsonData,
        CURLOPT_TIMEOUT => 30,
    ]);
    $responseData = curl_exec($ch);
    $curlErr = curl_error($ch);
    curl_close($ch);

    if ($curlErr) {
        throw new Exception("CURL error: " . $curlErr);
    }

    $result = json_decode($responseData, true);

    if (!empty($result["result"]["url"])) {

        // insert pending payment record (so callback can match payment_extra = order_id)
        $insert = $conn->prepare("INSERT INTO payments 
            (client_id, payment_method, payment_amount, payment_status, payment_extra, payment_create_date)
            VALUES (:client_id, :method, :amount, 'Pending', :order_id, NOW())");
        $insert->execute([
            "client_id" => $user["client_id"],
            "method"    => $methodId,
            "amount"    => $paymentAmount,
            "order_id"  => $order_id
        ]);

        // return frontend JSON with redirect content (your frontend expects success/content)
        $response = [
            "success" => true,
            "message" => "Redirecting to Cryptomus...",
            "content" => "<script>window.location.href='" . htmlspecialchars($result["result"]["url"], ENT_QUOTES, 'UTF-8') . "';</script>"
        ];

    } else {
        $errMsg = $result["message"] ?? ($result["error"] ?? $responseData);
        $response = [
            "success" => false,
            "message" => "Cryptomus error: " . $errMsg
        ];
    }

} catch (Exception $e) {
    $response = [
        "success" => false,
        "message" => $e->getMessage()
    ];
}
?>