<?php

/**
 * Content Craft AI - Get Generations API Handler
 */

if (!defined('ABSPATH')) {
  exit;
}

/**
 * Handle request to get filtered article generations
 * 
 * @param WP_REST_Request $request The REST API request.
 * @return WP_REST_Response The REST API response.
 */
function content_craft_ai_get_generations($request)
{
  // Get request parameters with defaults
  $page = $request->get_param('page') ? (int)$request->get_param('page') : 1;
  $per_page = $request->get_param('per_page') ? (int)$request->get_param('per_page') : 10;

  // Get filters
  $filters = $request->get_param('filters') ? $request->get_param('filters') : [];

  // Sanitize filters
  $sanitized_filters = [];

  if (!empty($filters['status'])) {
    $sanitized_filters['status'] = sanitize_text_field($filters['status']);
  }

  if (!empty($filters['postStatus'])) {
    $sanitized_filters['postStatus'] = sanitize_text_field($filters['postStatus']);
  }

  if (!empty($filters['category']) && $filters['category'] !== '0') {
    $sanitized_filters['category'] = (int)$filters['category'];
  }

  if (!empty($filters['dateFrom'])) {
    $sanitized_filters['dateFrom'] = sanitize_text_field($filters['dateFrom']);
  }

  if (!empty($filters['dateTo'])) {
    $sanitized_filters['dateTo'] = sanitize_text_field($filters['dateTo']);
  }

  if (!empty($filters['search'])) {
    $sanitized_filters['search'] = sanitize_text_field($filters['search']);
  }

  // Get database manager and fetch the data
  $article_status_controller = new ContentCraftAI_ArticleStatusController();
  $result = $article_status_controller->get_paginated_generations($page, $per_page, $sanitized_filters);

  if ($result) {
    return rest_ensure_response([
      'success' => true,
      'data' => $result
    ]);
  } else {
    return rest_ensure_response([
      'success' => false,
      'message' => 'Failed to fetch generations'
    ]);
  }
}
