<?php
// filepath: c:\xampp\htdocs\insight\change_profile.php
header('Content-Type: application/json');
session_start();

// Database connection (update with your credentials)
$pdo = new PDO('mysql:host=localhost;dbname=itsilhkd_notifications_db', 'itsilhkd_root', '+#QU2BpDi.gw');

// Get POST data
$current_username = trim($_POST['current_username'] ?? '');
$current_password = $_POST['current_password'] ?? '';
$new_username = trim($_POST['new_username'] ?? '');
$new_password = $_POST['new_password'] ?? '';

if (!$current_username || !$current_password) {
    echo json_encode(['success' => false, 'error' => 'Current username and password are required.']);
    exit;
}

// Fetch user
$stmt = $pdo->prepare("SELECT id, username, password FROM users WHERE username = ?");
$stmt->execute([$current_username]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$user || !password_verify($current_password, $user['password'])) {
    echo json_encode(['success' => false, 'error' => 'Incorrect current username or password.']);
    exit;
}

// Prepare update
$fields = [];
$params = [];

if ($new_username && $new_username !== $current_username) {
    // Check if new username is taken
    $check = $pdo->prepare("SELECT id FROM users WHERE username = ? AND id != ?");
    $check->execute([$new_username, $user['id']]);
    if ($check->fetch()) {
        echo json_encode(['success' => false, 'error' => 'Username already taken.']);
        exit;
    }
    $fields[] = "username = ?";
    $params[] = $new_username;
}

if ($new_password) {
    $fields[] = "password = ?";
    $params[] = password_hash($new_password, PASSWORD_DEFAULT);
}

if (empty($fields)) {
    echo json_encode(['success' => false, 'error' => 'No changes to update.']);
    exit;
}

$params[] = $user['id'];
$sql = "UPDATE users SET " . implode(', ', $fields) . " WHERE id = ?";
$update = $pdo->prepare($sql);
if ($update->execute($params)) {
    echo json_encode([
        'success' => true,
        'message' => 'Profile updated!',
        'new_username' => $new_username ?: $current_username
    ]);
} else {
    echo json_encode(['success' => false, 'error' => 'Update failed.']);
}
