<?php
function sort_by_completion($a, $b)
{
    // Ensure $a and $b are arrays before proceeding
    if (!is_array($a) || !is_array($b)) {
        // Handle the case where one or both are not arrays.
        // This shouldn't ideally happen with uasort on your $categories array,
        // but adding a safeguard is good practice.
        return 0;  // Maintain original order if not arrays
    }

    $a_completed = true;
    foreach ($a as $todo) {
        if (isset($todo['status']) && $todo['status'] !== 'completed') {
            $a_completed = false;
            break;
        }
    }

    $b_completed = true;
    foreach ($b as $todo) {
        if (isset($todo['status']) && $todo['status'] !== 'completed') {
            $b_completed = false;
            break;
        }
    }

    if ($a_completed && $b_completed) {
        return 0;
    } elseif ($a_completed && !$b_completed) {
        return 1;
    } elseif (!$a_completed && $b_completed) {
        return -1;
    } else {
        return 0;
    }
}

function todo_display($todos)
{
    $categories = [];
    while ($row = $todos->fetch_assoc())
        $categories[$row['category']][] = $row;

    foreach ($categories as $c)
        uasort($c, 'sort_by_completion');

    $display = '
    <div class="todo_display">
      ' . todo_actions() . '
      <div class="todo_category_window">
    ';

    foreach (array_keys($categories) as $key)
        $display .= todo_category($key, $categories[$key]);

    $display .= '
      </div>
      ' . todo_modal(null, 'new_todo_item') . '
    </div>
  ';

    return $display;
}
