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

// Ensure the method is GET and order_id is present in the URL
if ($_SERVER["REQUEST_METHOD"] == "GET" && isset($_GET["order_id"])) {
    $ORDER_ID = htmlspecialchars($_GET["order_id"]); // Sanitize the order ID
    $AppID = $methodExtras["AppID"]; // Cashfree App ID
    $SecretKey = $methodExtras["SecretKey"]; // Cashfree Secret Key

    if (empty($AppID) || empty($SecretKey)) {
        echo json_encode([
            "success" => false,
            "message" => "API credentials missing."
        ]);
        exit;
    }

    // Fetch Payment Details from Cashfree API
    $ch = curl_init("https://api.cashfree.com/pg/orders/" . $ORDER_ID);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'x-client-id: ' . $AppID,
        'x-secret-key: ' . $SecretKey,
        'Content-Type: application/json',
    ]);

    // Execute the API request
    $response = curl_exec($ch);
    if (curl_errno($ch)) {
        $error_msg = curl_error($ch);
        curl_close($ch);
        echo json_encode([
            "success" => false,
            "message" => "cURL error: " . $error_msg
        ]);
        exit;
    }
    curl_close($ch);

    // Decode the response from Cashfree
    $response_array = json_decode($response, true);

    // If the response is invalid or the order is not PAID
    if (!$response_array || !isset($response_array["order_status"]) || $response_array["order_status"] !== "PAID") {
        echo json_encode([
            "success" => false,
            "message" => "Payment verification failed or invalid response."
        ]);
        exit;
    }

    // Payment details from Cashfree response
    $paidAmount = $response_array["order_amount"];
    $cashfreePaymentId = $ORDER_ID;

    // Check if this order_id has already been used in the payments table
    $paymentExists = $conn->prepare("SELECT payment_extra FROM payments WHERE payment_extra = :order_id");
    $paymentExists->execute(["order_id" => $cashfreePaymentId]);
    if ($paymentExists->rowCount() > 0) {
        echo json_encode([
            "success" => false,
            "message" => "Order ID has already been used."
        ]);
        exit;
    }

    // Insert payment into the database
    $insert = $conn->prepare("INSERT INTO payments (client_id, payment_amount, payment_method, payment_mode, payment_create_date, payment_ip, payment_extra)
                              VALUES (:client_id, :amount, :method, :mode, :date, :ip, :extra)");
    $insert->execute([
        "client_id" => $user["client_id"],
        "amount" => $paidAmount,
        "method" => $methodId,
        "mode" => "Automatic",
        "date" => date("Y.m.d H:i:s"),
        "ip" => GetIP(),
        "extra" => $cashfreePaymentId
    ]);

    // Get the payment ID inserted
    $paymentId = $conn->lastInsertId();

    // Apply payment fees, if any
    if ($paymentFee > 0) {
        $fee = ($paidAmount * ($paymentFee / 100));
        $paidAmount -= $fee;
    }

    // Apply payment bonuses, if applicable
    if ($paymentBonusStartAmount != 0 && $paidAmount > $paymentBonusStartAmount) {
        $bonus = $paidAmount * ($paymentBonus / 100);
        $paidAmount += $bonus;
    }

    // Convert payment amount to base currency
    $paidAmount = from_to($currencies_array, $methodCurrency, $settings["site_base_currency"], $paidAmount);

    // Update payment status and user balance
    $updatePayment = $conn->prepare('UPDATE payments SET client_balance = :balance, payment_status = :status, payment_delivery = :delivery WHERE payment_id = :id');
    $updatePayment->execute([
        'balance' => $user["balance"] + $paidAmount,
        'status' => 3,  // Payment confirmed
        'delivery' => 2,  // Payment processed
        'id' => $paymentId
    ]);

    // Update the user's balance
    $updateBalance = $conn->prepare('UPDATE clients SET balance = :balance WHERE client_id = :id');
    $updateBalance->execute([
        "balance" => $user["balance"] + $paidAmount,
        "id" => $user["client_id"]
    ]);

    // Send response to the front end
    echo json_encode([
        "success" => true,
        "message" => "The fund transfer has been successful and the money has been added to your account."
    ]);
} else {
    // Invalid method or missing order_id parameter
    http_response_code(405);
    echo json_encode([
        "success" => false,
        "message" => "Invalid request method or missing order_id parameter."
    ]);
    exit;
}
?>
