<?php
ob_start();

include_once '../includes/session.php';
include_once '../includes/constants.php';
include_once '../includes/functions.php';
include_once '../includes/allstripslashes.php';

// Establish mysqli connection
$connection = new mysqli($host, $user, $pass, $db);
if ($connection->connect_error) {
    die("Connection failed: " . $connection->connect_error);
}

// Sanitize POST inputs
$version         = trim($_POST['version'] ?? '');
$delimdata       = trim($_POST['delimdata'] ?? '');
$relayresponse   = trim($_POST['relayresponse'] ?? '');
$login           = trim($_POST['login'] ?? '');
$trankey         = trim($_POST['trankey'] ?? '');
$cctype          = trim($_POST['cctype'] ?? '');

// Optional GET input
$payid           = $_GET['payid'] ?? '';
$userid          = 0;

echo htmlspecialchars($payid);

// Input validation
if (empty($login)) {
    $err = "1";
    $msg = "Login cannot be null";
} else {
    $err = "0";
    $msg = "";
}

// If there's an error, redirect back with error message
if ($err !== "0") {
    $msg = urlencode($msg);
    header("Location: index.php?Act=creditcard&payid=3&mode=edit&version=" . urlencode($version) . "&delimdata=" . urlencode($delimdata) . "&relayresponse=" . urlencode($relayresponse) . "&trankey=" . urlencode($trankey) . "&cctype=" . urlencode($cctype) . "&msg=$msg");
    exit;
} else {
    // Check if a record exists
    $check_sql = "SELECT 1 FROM partners_creditcard LIMIT 1";
    $result = $connection->query($check_sql);

    if ($result && $result->num_rows > 0) {
        // Record exists - perform update
        $stmt = $connection->prepare("UPDATE partners_creditcard SET cc_version = ?, cc_delimdata = ?, cc_relayresponse = ?, cc_login = ?, cc_trankey = ?, cc_type = ?");
        $stmt->bind_param("ssssss", $version, $delimdata, $relayresponse, $login, $trankey, $cctype);
        $stmt->execute();
        $stmt->close();
    } else {
        // No record exists - perform insert
        $stmt = $connection->prepare("INSERT INTO partners_creditcard (cc_version, cc_delimdata, cc_relayresponse, cc_login, cc_trankey, cc_type) VALUES (?, ?, ?, ?, ?, ?)");
        $stmt->bind_param("ssssss", $version, $delimdata, $relayresponse, $login, $trankey, $cctype);
        $stmt->execute();
        $stmt->close();
    }

    // Redirect with success message
    $msg = urlencode("Updation Successfull!!!!");
    header("Location: index.php?Act=payments&payid=1&mode=edit&msg=$msg");
    exit;
}
