<?php
require_once "config.php";

$username = trim($_POST['username'] ?? '');
$password = trim($_POST['password'] ?? '');
$new_password = trim($_POST['new_password'] ?? '');
$new_username = trim($_POST['new_username'] ?? '');

if ($username === '') {
    echo "Username is required";
    exit;
}

if ($new_password !== '' && $password === '') {
    echo "Old password is required to change password";
    exit;
}

$stmt = $conn->prepare("SELECT id, username, password FROM users WHERE username = ?");
$stmt->bind_param("s", $username);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows == 0) {
    echo "Username not found";
    exit;
}

$user = $result->fetch_assoc();
$stmt->close();

if ($password !== '' && $user['password'] != $password) {
    echo "Old password is incorrect";
    exit;
}

$updates = [];
$types = '';
$values = [];

if ($new_username !== '' && $new_username !== $user['username']) {
    if (strlen($new_username) < 5) {
        echo "New username must be at least 5 characters";
        exit;
    }

    $check = $conn->prepare("SELECT id FROM users WHERE username = ? AND id != ?");
    $check->bind_param("si", $new_username, $user['id']);
    $check->execute();
    $checkResult = $check->get_result();

    if ($checkResult->num_rows > 0) {
        echo "Username already exists";
        exit;
    }
    $check->close();

    $updates[] = "username = ?";
    $types .= "s";
    $values[] = $new_username;
}

if ($new_password !== '') {
    $updates[] = "password = ?";
    $types .= "s";
    $values[] = $new_password;
}

if (empty($updates)) {
    echo "No changes to update";
    exit;
}

$sql = "UPDATE users SET " . implode(", ", $updates) . " WHERE id = ?";
$types .= "i";
$values[] = $user['id'];

$update = $conn->prepare($sql);
$bindParams = array_merge([$types], $values);

$tmp = [];
foreach ($bindParams as $key => $value) {
    $tmp[$key] = &$bindParams[$key];
}

call_user_func_array([$update, 'bind_param'], $tmp);

if ($update->execute()) {
    echo "Profile updated successfully";
} else {
    echo "Failed to update profile";
}

$update->close();
$conn->close();
?>