<?php
header("Content-Type: application/json");
require_once "../database.php";

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(["error" => "Only POST method allowed"]);
    exit;
}

$data = json_decode(file_get_contents("php://input"));

if (!isset($data->id) || !is_numeric($data->id)) {
    http_response_code(400);
    echo json_encode(["error" => "Invalid or missing user ID"]);
    exit;
}

$allowed_fields = ['name', 'surname', 'email', 'phone', 'address', 'role', 'balance', 'reg_no', 'sex'];
$fields = [];
$placeholders = [];
$bindings = [];
$userId = intval($data->id);

// Prepare fields and bindings
foreach ($allowed_fields as $field) {
    if (isset($data->$field)) {
        $fields[] = $field;
        $placeholders[] = ":$field";
        $bindings[":$field"] = $data->$field;
    }
}

if (empty($fields)) {
    http_response_code(400);
    echo json_encode(["error" => "No valid fields provided"]);
    exit;
}

$bindings[':id'] = $userId;

try {
    // Check if user ID exists
    $stmt = $conn->prepare("SELECT id FROM users WHERE id = :id");
    $stmt->execute([':id' => $userId]);
    $userExists = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($userExists) {
        // Try updating
        $update_parts = array_map(fn($f) => "$f = :$f", $fields);
        $update_sql = "UPDATE users SET " . implode(", ", $update_parts) . " WHERE id = :id";

        $stmt = $conn->prepare($update_sql);
        foreach ($bindings as $key => $value) {
            $stmt->bindValue($key, $value);
        }
        $stmt->execute();

        if ($stmt->rowCount() > 0) {
            echo json_encode(["message" => "User updated successfully"]);
        } else {
            echo json_encode(["message" => "No changes made. User data unchanged."]);
        }
    } else {
        // Insert new user
        $fields[] = 'id';
        $placeholders[] = ':id';

        $insert_sql = "INSERT INTO users (" . implode(", ", $fields) . ") VALUES (" . implode(", ", $placeholders) . ")";
        $stmt = $conn->prepare($insert_sql);
        foreach ($bindings as $key => $value) {
            $stmt->bindValue($key, $value);
        }
        $stmt->execute();

        echo json_encode(["message" => "User inserted successfully"]);
    }
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(["error" => "Database error", "details" => $e->getMessage()]);
}
?>
