<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

include '../../dbcon.php';

// Since we use FormData in the frontend, we use $_POST
$user_id = mysqli_real_escape_string($conn, $_POST['user_id'] ?? '');
$full_name = mysqli_real_escape_string($conn, $_POST['full_name'] ?? '');
$phone = mysqli_real_escape_string($conn, $_POST['phone'] ?? '');
$country = mysqli_real_escape_string($conn, $_POST['country'] ?? '');
$password = $_POST['password'] ?? '';

if (!$user_id) {
    echo json_encode(["status" => "error", "message" => "User ID is required"]);
    exit;
}

// Build update query
$updateQuery = "UPDATE users SET full_name = '$full_name', phone = '$phone', country = '$country'";

if (!empty($password)) {
    $hashed_password = password_hash($password, PASSWORD_BCRYPT);
    $updateQuery .= ", password = '$hashed_password'";
}

$updateQuery .= " WHERE id = '$user_id'";

if (mysqli_query($conn, $updateQuery)) {
    // Fetch updated user info with role name
    $result = mysqli_query($conn, "
        SELECT u.*, r.role_name 
        FROM users u 
        JOIN roles r ON u.role_id = r.id 
        WHERE u.id = '$user_id' LIMIT 1
    ");

    if (mysqli_num_rows($result) === 1) {
        $user = mysqli_fetch_assoc($result);
        
        $userData = [
            "id" => $user['id'],
            "role" => $user['role_name'],
            "full_name" => $user['full_name'],
            "email" => $user['email'],
            "phone" => $user['phone'],
            "country" => $user['country'],
            "status" => $user['status']
        ];

        echo json_encode([
            "status" => "success",
            "message" => "Profile updated successfully",
            "user" => $userData
        ]);
    } else {
        echo json_encode(["status" => "error", "message" => "Profile updated, but failed to fetch new data"]);
    }
} else {
    echo json_encode(["status" => "error", "message" => "Database update failed: " . mysqli_error($conn)]);
}
?>
