<?php
function todo_modal($todo = [], $id = null)
{
  if (!isset($todo)) {
    $todo['created_at'] = '';
    $todo['updated_at'] = '';
    $todo['completed_at'] = '';
    $todo['todo_id'] = '';
    $todo['title'] = '';
    $todo['description'] = '';
    $todo['priority'] = '';
    $todo['due_date'] = '';
  }

  $modal = '
      <div class="modal card todo_item_details"' . (isset($id) ? ' id="' . $id . '"' : '') . '>
        <div id="modal_content">
          <div class="form_card">
            <div class="row_space_between">
              <h5 class="underline">Item View</h5>
              ';

  if (!empty($todo['title'])) {
    $modal .= '
              <div class="column over_right_margin">
                <small>Created: ' . $todo['created_at'] . '</small>
                <small>Updated: ' . $todo['updated_at'] . '</small>
                <small>Completed: ' . $todo['completed_at'] . '</small>
              </div>
    ';
  }

  $modal .= '
            </div>
            <span class="modal_close">&times;</span>
            <form>
              <input type="hidden" name="todo_id" value="' . (!empty($todo['todo_id']) ? $todo['todo_id'] : '-1') . '">

              <div class="row">
                <div class="column full_width">
                  <label for="title">Title:</label>
                  <input id="title" name="title" value="' . $todo['title'] . '" placeholder="Task Title" required>
                </div>
              </div>
  
              <div class="row">
                <div class="column full_width">
                  <label for="description">Description:</label>
                  <textarea id="description" name="description">' . $todo['description'] . '</textarea>
                </div>
              </div>
              
              <div class="row_space_between">
                <div class="column">
                  <label for="priority">Priority:</label>
                  <select id="priority" name="priority">
                    <option value="low"' . ($todo['priority'] == 'low' ? ' checked' : '') . '>Low</option>
                    <option value="medium"' . ($todo['priority'] == 'medium' ? ' checked' : '') . '>Medium</option>
                    <option value="high"' . ($todo['priority'] == 'high' ? ' checked' : '') . '>High</option>
                  </select>
                </div>
                <div class="column">
                  <label for="due_date">Due Date:</label>
                  <input type="datetime-local" id="due_date" name="due_date" value="' . format_date($todo['due_date']) . '">
                </div>
              </div>

              <input type="submit" class="button" value="' . (!empty($todo['todo_id']) ? 'Update Item' : 'Create Item') . '">
            </form>
          </div>
        </div>
      </div>
  ';

  return $modal;
}
