<?php

class TasksAPI
{
  private $namespace = 'wb-onboard/v1';
  private $route = '/tasks';

  public function register_routes()
  {
    register_rest_route($this->namespace, $this->route . '/status', [
      [
        'methods' => 'GET',
        'callback' => [$this, 'get_tasks_status'],
        'permission_callback' => '__return_true'
      ],
      [
        'methods' => 'POST',
        'callback' => [$this, 'update_task_status'],
        'permission_callback' => '__return_true',
        'args' => [
          'task_id' => [
            'required' => true,
            'type' => 'string',
            'sanitize_callback' => 'sanitize_key'
          ],
          'status' => [
            'required' => true,
            'type' => 'boolean'
          ]
        ]
      ]
    ]);
  }

  public function get_tasks_status()
  {
    $task_states = get_option('wb_onboard_task_states', []);

    return rest_ensure_response([
      'success' => true,
      'data' => $task_states
    ]);
  }

  public function update_task_status($request)
  {
    error_log('update_task_status');
    $task_id = $request->get_param('task_id');
    $status = $request->get_param('status');

    // Get current states
    $task_states = get_option('wb_onboard_task_states', []);

    // Update specific task
    $task_states[$task_id] = $status;

    // Save to database
    $updated = update_option('wb_onboard_task_states', $task_states);

    if (!$updated) {
      return new \WP_Error(
        'task_update_failed',
        'Failed to update task status',
        ['status' => 500]
      );
    }

    return rest_ensure_response([
      'success' => true,
      'data' => [
        'message' => 'Task status updated successfully',
        'task_states' => $task_states
      ]
    ]);
  }
}
