<?php
include '../config.php';

$response = array();
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $user_id = $_POST['user_id'];
    $first_name = $_POST['first_name'];
    $last_name = $_POST['last_name'];
    $phone = $_POST['phone'];
    $email = $_POST['email'];
    $occupation = $_POST['occupation'];
    $institution = $_POST['institution'];
    
    // Tengeneza sehemu ya SQL dinamikali
    $fields = "first_name = ?, last_name = ?, phone = ?, email = ?, occupation = ?, institution = ?";
    $params = array($first_name, $last_name, $phone, $email, $occupation, $institution);
    $types = "ssssss";
    
    // Ongeza password ikiwa imetolewa na sio tupu, ikihash kwa PASSWORD_DEFAULT
    if (isset($_POST['password']) && !empty($_POST['password'])) {
        $password = password_hash($_POST['password'], PASSWORD_DEFAULT);
        $fields .= ", password = ?";
        $params[] = $password;
        $types .= "s";
    }
    
    // Ongeza profile_image ikiwa imetumwa
    if (isset($_FILES['profile_image']) && !empty($_FILES['profile_image']['name'])) {
        $image_name = time() . '_' . basename($_FILES['profile_image']['name']);
        $target_path = 'uploads/profiles/' . $image_name;
        if (move_uploaded_file($_FILES['profile_image']['tmp_name'], $target_path)) {
            $fields .= ", profile_image = ?";
            $params[] = $image_name;
            $types .= "s";
        }
    }
    
    // Ongeza WHERE clause
    $sql = "UPDATE users SET $fields WHERE id = ?";
    $params[] = $user_id;
    $types .= "i";
    
    $stmt = $conn->prepare($sql);
    // Bind parameters kwa kutumia spread operator (PHP 5.6+)
    $stmt->bind_param($types, ...$params);
    
    if ($stmt->execute()) {
        $response['success'] = true;
        $response['message'] = "Profile updated successfully";
    } else {
        $response['success'] = false;
        $response['message'] = "Profile update failed";
    }
    
    $stmt->close();
    $conn->close();
} else {
    $response['success'] = false;
    $response['message'] = "Invalid request";
}

echo json_encode($response);
?>
