<?php

class KLCNN_Category_Manager extends KLCNN_API_Base
{

  /**
   * Handle REST API request for category suggestions
   */
  public static function get_suggestions($request)
  {
    try {
      $instance = new self(
        get_option('klcnn_client_key', ''),
        get_option('klcnn_secret_key', '')
      );

      $data = $request->get_json_params();

      if (empty($data)) {
        return new WP_Error(
          'invalid_request',
          'No data provided',
          ['status' => 400]
        );
      }

      $suggestions = $instance->suggest_categories($data);

      return rest_ensure_response([
        'success' => true,
        'data' => $suggestions
      ]);
    } catch (Exception $e) {
      return new WP_Error(
        'suggestion_failed',
        'Failed to get category suggestions: ' . esc_html($e->getMessage()),
        ['status' => 500]
      );
    }
  }

  /**
   * Get category suggestions from Kaufland API
   */
  private function suggest_categories($product_data)
  {
    try {
      // Validate required fields
      if (empty($product_data['item']['title'])) {
        throw new Exception('Product title is required');
      }

      // Ensure description and manufacturer are at least empty strings
      $product_data['item']['description'] = $product_data['item']['description'] ?? '';
      $product_data['item']['manufacturer'] = $product_data['item']['manufacturer'] ?? '';

      // Ensure price is a positive integer
      if (!isset($product_data['price']) || !is_numeric($product_data['price']) || $product_data['price'] < 0) {
        $product_data['price'] = 0; // Set default price if invalid
      }

      // Send the request data exactly as shown in documentation
      $request_data = [
        'item' => [
          'title' => $product_data['item']['title'],
          'description' => $product_data['item']['description'],
          'manufacturer' => $product_data['item']['manufacturer']
        ],
        'price' => (int) $product_data['price']
      ];

      $response = $this->request('POST', 'categories/decide', $request_data);

      if (!isset($response['data'])) {
        throw new Exception('Invalid response format from Kaufland API');
      }

      return $response['data'];
    } catch (Exception $e) {
      throw new Exception('Failed to get category suggestions: ' . esc_html($e->getMessage()));
    }
  }

  /**
   * Get category attributes
   */
  public function get_category_attributes($category_id)
  {
    return $this->request(
      'GET',
      sprintf('categories/%d', $category_id),
      ['embedded' => ['optional_attributes', 'required_attributes']]
    );
  }

  /**
   * Search categories
   */
  public function search_categories($query)
  {
    return $this->request('GET', 'categories', [
      'q' => $query,
      'storefront' => $this->storefront
    ]);
  }

  /**
   * Get child categories
   */
  public function get_child_categories($parent_id = 1)
  {
    return $this->request('GET', 'categories', [
      'id_parent' => $parent_id,
      'storefront' => $this->storefront
    ]);
  }
}
