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

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

// Read POST fields
$id = trim($_POST['id'] ?? '');
$wallet_name = trim($_POST['wallet_name'] ?? '');
$wallet_address = trim($_POST['wallet_address'] ?? '');
$payment_type = trim($_POST['payment_type'] ?? '');
$status = in_array($_POST['status'] ?? '', ['active','inactive']) ? $_POST['status'] : '';

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

// Handle QR upload if file is provided
$qr_upload = null;
$uploadDir = __DIR__ . "/uploads/";
$uploadUrlPath = "uploads/";

if (!file_exists($uploadDir)) mkdir($uploadDir, 0777, true);

if (isset($_FILES['qr_upload']) && $_FILES['qr_upload']['error'] === UPLOAD_ERR_OK) {
    $fileTmpPath = $_FILES['qr_upload']['tmp_name'];
    $originalName = basename($_FILES['qr_upload']['name']);
    $ext = strtolower(pathinfo($originalName, PATHINFO_EXTENSION));
    $allowedExt = ['jpg','jpeg','png','gif'];

    if (!in_array($ext, $allowedExt)) {
        echo json_encode(["status" => "error", "message" => "Invalid file type. Allowed: jpg, jpeg, png, gif"]);
        exit();
    }

    $newFileName = time() . '_' . preg_replace('/[^a-zA-Z0-9._-]/', '_', $originalName);
    $destination = $uploadDir . $newFileName;

    if (move_uploaded_file($fileTmpPath, $destination)) {
        $qr_upload = $uploadUrlPath . $newFileName;
    } else {
        echo json_encode(["status" => "error", "message" => "Failed to upload QR image"]);
        exit();
    }
}

// Build dynamic update query
$fields = [];
if ($wallet_name !== '') $fields[] = "wallet_name = '" . $conn->real_escape_string($wallet_name) . "'";
if ($wallet_address !== '') $fields[] = "wallet_address = '" . $conn->real_escape_string($wallet_address) . "'";
if ($payment_type !== '') $fields[] = "payment_type = '" . $conn->real_escape_string($payment_type) . "'";
if ($status !== '') $fields[] = "status = '" . $conn->real_escape_string($status) . "'";
if ($qr_upload !== null) $fields[] = "qr_upload = '" . $conn->real_escape_string($qr_upload) . "'";

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

$setQuery = implode(", ", $fields);
$sql = "UPDATE payment_methods SET $setQuery WHERE id = '" . $conn->real_escape_string($id) . "'";

// Execute update
// if ($conn->query($sql)) {
//     echo json_encode([
//         "status" => "success",
//         "message" => "Payment method updated successfully",
//         "updated_fields" => $fields,
//         "qr_upload" => $qr_upload
//     ]);
// } else {
//     echo json_encode(["status" => "error", "message" => "Database update failed: " . $conn->error]);
// }
if ($conn->query($sql)) {
    // Fetch updated row to log exact values
    $updatedStmt = $conn->query("SELECT * FROM payment_methods WHERE id = '$id'");
    $updatedRow = $updatedStmt->fetch_assoc();

    // ------------------ ADD HISTORY ------------------
    $historyStmt = $conn->prepare("
        INSERT INTO payment_methods_history 
        (payment_method_id, action, wallet_name, wallet_address, payment_type, status, qr_upload, action_date) 
        VALUES (?, 'updated', ?, ?, ?, ?, ?, NOW())
    ");
    $historyStmt->bind_param("isssss", $id, $updatedRow['wallet_name'], $updatedRow['wallet_address'], $updatedRow['payment_type'], $updatedRow['status'], $updatedRow['qr_upload']);
    $historyStmt->execute();
    $historyStmt->close();
    // ------------------ END HISTORY ------------------

    echo json_encode([
        "status" => "success",
        "message" => "Payment method updated successfully",
        "updated_fields" => $fields,
        "qr_upload" => $qr_upload
    ]);
} else {
    echo json_encode(["status" => "error", "message" => "Database update failed: " . $conn->error]);
}


$conn->close();
?>
