<?php
// Enable full error reporting
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

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 = ?";

// Wrap in try-catch to display errors
try {
    $stmt = $conn->prepare($sql);
    if (!$stmt) {
        throw new Exception("Prepare failed: " . $conn->error);
    }

    // Dynamically bind parameters
    $types = str_repeat("s", count($updateValues) - 1) . "i"; // last one is integer (id)
    if (!$stmt->bind_param($types, ...$updateValues)) {
        throw new Exception("Bind param failed: " . $stmt->error);
    }

    if (!$stmt->execute()) {
        throw new Exception("Execute failed: " . $stmt->error);
    }

    $response['success'] = true;
    $response['message'] = "User updated successfully";

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

} catch (Exception $e) {
    $response['success'] = false;
    $response['message'] = "Error: " . $e->getMessage();
}

echo json_encode($response);
?>
