<?php
header("Content-Type: application/json; charset=UTF-8");
require_once "config.php";

// Allow POST only
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(["status" => "error", "message" => "Invalid request method"]);
    exit();
}

$id = trim($_POST['id'] ?? '');
if (empty($id)) {
    echo json_encode(["status" => "error", "message" => "Payment method ID is required"]);
    exit();
}

// Read fields
$fields = [
    "wallet_name"         => $_POST['wallet_name'] ?? '',
    "wallet_address"      => $_POST['wallet_address'] ?? '',
    "payment_type"        => $_POST['payment_type'] ?? '',
    "status"              => (in_array($_POST['status'] ?? '', ['active','inactive']) ? $_POST['status'] : ''),
    "bank_account_holder" => $_POST['bank_account_holder'] ?? '',
    "bank_payment_method" => $_POST['bank_payment_method'] ?? '',
    "bank_iban"           => $_POST['bank_iban'] ?? '',
    "bank_swift"          => $_POST['bank_swift'] ?? '',
    "bank_name"           => $_POST['bank_name'] ?? '',
    "bank_address"        => $_POST['bank_address'] ?? '',
    "bank_country"        => $_POST['bank_country'] ?? '',
    "account_currency"    => $_POST['account_currency'] ?? ''
];

// QR upload
$qr_upload = null;
$uploadDir = __DIR__ . "/uploads/";
$uploadUrl = "uploads/";
if (!file_exists($uploadDir)) mkdir($uploadDir, 0777, true);

if (isset($_FILES['qr_upload']) && $_FILES['qr_upload']['error'] === UPLOAD_ERR_OK) {
    $fileInfo = pathinfo($_FILES['qr_upload']['name']);
    $ext = strtolower($fileInfo['extension']);
    $allowed = ['jpg','jpeg','png','gif'];

    if (!in_array($ext, $allowed)) {
        echo json_encode(["status" => "error", "message" => "Invalid file type"]);
        exit();
    }

    $newName = time() . "_" . preg_replace("/[^a-zA-Z0-9._-]/", "_", $fileInfo['basename']);
    $dest = $uploadDir . $newName;

    if (move_uploaded_file($_FILES['qr_upload']['tmp_name'], $dest)) {
        $qr_upload = $uploadUrl . $newName;
        $fields["qr_upload"] = $qr_upload;
    }
}

// Build dynamic UPDATE query
$updateParts = [];
foreach ($fields as $column => $value) {
    if ($value !== '') {
        $updateParts[] = "$column = '" . $conn->real_escape_string($value) . "'";
    }
}

if (empty($updateParts)) {
    echo json_encode(["status" => "error", "message" => "No fields provided to update"]);
    exit();
}

$updateSql = "UPDATE payment_methods SET " . implode(", ", $updateParts) . " WHERE id = '" . $conn->real_escape_string($id) . "'";

if ($conn->query($updateSql)) {

    // GET updated row for history
    $result = $conn->query("SELECT * FROM payment_methods WHERE id = '$id'");
    $row = $result->fetch_assoc();

    // HISTORY SQL
    $historySql = "
        INSERT INTO payment_methods_history
        (payment_method_id, action, wallet_name, wallet_address, payment_type, status, qr_upload,
         bank_account_holder, bank_payment_method, bank_iban, bank_swift,
         bank_name, bank_address, bank_country, account_currency)
        VALUES (?, 'updated', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    ";

    $stmt = $conn->prepare($historySql);

    // Correct binding: 1 int + 14 strings = 15 params
    $stmt->bind_param(
        "isssssssssssss",
        $id,
        $row['wallet_name'],
        $row['wallet_address'],
        $row['payment_type'],
        $row['status'],
        $row['qr_upload'],
        $row['bank_account_holder'],
        $row['bank_payment_method'],
        $row['bank_iban'],
        $row['bank_swift'],
        $row['bank_name'],
        $row['bank_address'],
        $row['bank_country'],
        $row['account_currency']
    );

    $stmt->execute();
    $stmt->close();

    echo json_encode([
        "status" => "success",
        "message" => "Payment method updated successfully",
        "updated_fields" => $updateParts,
        "qr_upload" => $qr_upload
    ]);

} else {
    echo json_encode(["status" => "error", "message" => "Update failed: " . $conn->error]);
}

$conn->close();
?>
