<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

include_once __DIR__ . '/config.php'; // Database connection

$response = ["success" => false, "message" => "Something went wrong"];

// Get POST data
$data = json_decode(file_get_contents("php://input"), true);

if (!isset($data['id']) || empty($data['id'])) {
    $response['message'] = "User ID is required";
    echo json_encode($response);
    exit;
}

$userId = intval($data['id']);

// List of fields allowed to update
$fields = [
    'first_name', 'last_name', 'country', 'phone', 'dob', 'email', 'username', 'fullname',
    'address', 'aboutme', 'imgName', 'education', 'industry', 'financial_industry',
    'forex_exp', 'monthly_transaction', 'investment_plan', 'funds_source',
    'investment_purpose', 'total_value', 'annual_income', 'state', 'city',
    'lang', 'profile_image', 'gender', 'wallet_address', 'bank_detail',
    'account_holder_name', 'bank_name', 'bank_account_no', 'IFSC_Code', 'swift_code'
];

// Prepare dynamic SQL
$updateFields = [];
$updateValues = [];
foreach ($fields as $field) {
    if (isset($data[$field])) {
        $updateFields[] = "$field = ?";
        $updateValues[] = $data[$field];
    }
}

if (empty($updateFields)) {
    $response['message'] = "No fields to update";
    echo json_encode($response);
    exit;
}

$updateValues[] = $userId; // For WHERE clause

$sql = "UPDATE loginusers SET " . implode(", ", $updateFields) . " WHERE id = ?";

$stmt = $conn->prepare($sql);
if (!$stmt) {
    $response['message'] = "Prepare failed: " . $conn->error;
    echo json_encode($response);
    exit;
}

// Dynamically bind parameters
$types = str_repeat("s", count($updateValues) - 1) . "i"; // last one is integer (id)
$stmt->bind_param($types, ...$updateValues);

if ($stmt->execute()) {
    $response['success'] = true;
    $response['message'] = "User updated successfully";
} else {
    $response['message'] = "Update failed: " . $stmt->error;
}

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

echo json_encode($response);
?>
