<?php
require_once 'config/database.php';
require_once 'utils/helpers.php';

if ($_SERVER['REQUEST_METHOD'] !== 'PUT') {
    Helpers::sendResponse(false, 'Method not allowed', null, 405);
}

// Get and verify token
$token = Helpers::getBearerToken();
$userData = Helpers::verifyJWT($token);

if (!$userData) {
    Helpers::sendResponse(false, 'Unauthorized', null, 401);
}

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

$database = new Database();
$db = $database->getConnection();

// Build update query dynamically based on provided fields
$updateFields = [];
$params = [':id' => $userData['user_id']];

if (!empty($data->first_name)) {
    $updateFields[] = "first_name = :first_name";
    $params[':first_name'] = $data->first_name;
}

if (!empty($data->last_name)) {
    $updateFields[] = "last_name = :last_name";
    $params[':last_name'] = $data->last_name;
}

if (!empty($data->phone_number)) {
    $updateFields[] = "phone_number = :phone_number";
    $params[':phone_number'] = $data->phone_number;
}

if (!empty($data->gender)) {
    $updateFields[] = "gender = :gender";
    $params[':gender'] = $data->gender;
}

if (!empty($data->department)) {
    $updateFields[] = "department = :department";
    $params[':department'] = $data->department;
}

if (!empty($data->user_type)) {
    $updateFields[] = "user_type = :user_type";
    $params[':user_type'] = $data->user_type;
}

if (!empty($data->password)) {
    if (strlen($data->password) < 6) {
        Helpers::sendResponse(false, 'Password must be at least 6 characters', null, 400);
    }
    $updateFields[] = "password = :password";
    $params[':password'] = Helpers::hashPassword($data->password);
}

if (empty($updateFields)) {
    Helpers::sendResponse(false, 'No fields to update', null, 400);
}

$query = "UPDATE users SET " . implode(', ', $updateFields) . " WHERE id = :id";
$stmt = $db->prepare($query);

foreach ($params as $key => $value) {
    $stmt->bindValue($key, $value);
}

if ($stmt->execute()) {
    // Get updated user data
    $query = "SELECT id, email, first_name, last_name, phone_number, gender, department_id AS department, user_type, role 
              FROM users WHERE id = :id";
    $stmt = $db->prepare($query);
    $stmt->bindParam(':id', $userData['user_id']);
    $stmt->execute();
    $user = $stmt->fetch();

    Helpers::sendResponse(true, 'Profile updated successfully', [
        'user' => $user
    ]);
} else {
    Helpers::sendResponse(false, 'Update failed', null, 500);
}
