<?php
if (!defined("PAYMENT")) {
    http_response_code(404);
    die();
}

// read raw payload
$payload = file_get_contents("php://input");
$data = json_decode($payload, true);

// get sign header (try common variants)
$sign = $_SERVER["HTTP_SIGN"] ?? ($_SERVER["HTTP_X_SIGN"] ?? ($_SERVER["HTTP_X_SIGNATURE"] ?? ""));

// minimal payload check
if (!$data || !isset($data['order_id'])) {
    http_response_code(400);
    echo json_encode(["status" => "error", "message" => "Invalid payload"]);
    exit;
}

$orderId = $data["order_id"];

// find payment record by order id
$check = $conn->prepare("SELECT * FROM payments WHERE payment_extra = :orderId LIMIT 1");
$check->execute(["orderId" => $orderId]);
$payment = $check->fetch(PDO::FETCH_ASSOC);

if (!$payment) {
    // no payment found
    http_response_code(404);
    echo json_encode(["status" => "error", "message" => "Order not found"]);
    exit;
}

// load method extras for that payment method
$pm = $conn->prepare("SELECT methodExtras FROM paymentmethods WHERE methodId = :id LIMIT 1");
$pm->execute(["id" => $payment["payment_method"]]);
$pmRow = $pm->fetch(PDO::FETCH_ASSOC);
$methodExtras = [];
if ($pmRow && !empty($pmRow["methodExtras"])) {
    $methodExtras = json_decode($pmRow["methodExtras"], true);
}

// normalize key names (support both camelCase and snake_case)
$apiKey = $methodExtras["apiKey"] ?? $methodExtras["api_key"] ?? $methodExtras["paymentKey"] ?? "";

// verify sign
$expectedSign = md5(base64_encode($payload) . $apiKey);

if (empty($apiKey) || $sign !== $expectedSign) {
    http_response_code(403);
    echo json_encode(["status" => "error", "message" => "Invalid signature"]);
    exit;
}

$status = strtolower($data["status"] ?? "");
$amount = floatval($data["amount"] ?? 0);

// consider Cryptomus 'paid' as successful
if ($status === "paid") {

    // check current payment status to avoid double-processing
    // your table used 'Pending' in other code — adapt if needed
    if ($payment["payment_status"] !== "Completed") {

        // update payments table
        $update = $conn->prepare("UPDATE payments SET payment_status = 'Completed', client_balance = :balance WHERE payment_id = :id");
        // Note: if you maintain client_balance column in payments, otherwise update only payment_status
        // We'll update payments.payment_status and update clients.balance separately

        $u = $conn->prepare("UPDATE payments SET payment_status = 'Completed' WHERE payment_id = :id");
        $u->execute(["id" => $payment["payment_id"]]);

        // credit client's balance
        $credit = $conn->prepare("UPDATE clients SET balance = balance + :amount WHERE client_id = :id");
        $credit->execute([
            "amount" => $amount,
            "id" => $payment["client_id"]
        ]);
    }

    // reply success
    echo json_encode(["status" => "success"]);
    exit;
}

// ignored / other statuses
echo json_encode(["status" => "ignored"]);
exit;
?>