<?php

declare(strict_types=1);

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

class KLCNN_Product_Sync extends KLCNN_API_Base
{
  /**
   * Get WooCommerce products with pagination
   */
  public function get_products($page = 1, $per_page = 10, $search = '')
  {
    $args = [
      'status' => 'publish',
      'limit' => $per_page,
      'page' => $page,
      'paginate' => true
    ];

    if (!empty($search)) {
      $args['s'] = sanitize_text_field($search);
    }

    $query = new WC_Product_Query($args);
    $results = $query->get_products();

    // Get Kaufland sync status for each product
    $products = array_map(function ($product) {
      // Get main product image
      $image_id = $product->get_image_id();
      $image_url = $image_id ? wp_get_attachment_url($image_id) : null;

      // Get gallery images
      $gallery_image_ids = $product->get_gallery_image_ids();
      $gallery_images = array_map(function ($id) {
        $url = wp_get_attachment_url($id);
        return [
          'id' => $id,
          'url' => $url
        ];
      }, $gallery_image_ids);

      $data = [
        'id' => $product->get_id(),
        'name' => $product->get_name(),
        'sku' => $product->get_sku(),
        'price' => $product->get_price(),
        'regular_price' => $product->get_regular_price(),
        'stock_quantity' => $product->get_stock_quantity(),
        'stock_status' => $product->get_stock_status(),
        'description' => $product->get_description(),
        'short_description' => $product->get_short_description(),
        'manufacturer' => $product->get_meta('_manufacturer') ?: 'Unknown',
        'kaufland_status' => get_post_meta($product->get_id(), '_klcnn_sync_status', true),
        'kaufland_category_id' => get_post_meta($product->get_id(), '_klcnn_kaufland_category_id', true),
        'kaufland_category_name' => get_post_meta($product->get_id(), '_klcnn_kaufland_category_name', true),
        'kaufland_category' => get_post_meta($product->get_id(), '_klcnn_kaufland_category_title', true),
        'last_synced' => get_post_meta($product->get_id(), '_klcnn_last_synced', true),
        'ean' => get_post_meta($product->get_id(), '_klcnn_ean', true)
      ];

      // Only add image data if it exists
      if ($image_id && $image_url) {
        $data['main_image'] = [
          'id' => $image_id,
          'url' => $image_url
        ];
      }

      if (!empty($gallery_images)) {
        $data['gallery_images'] = array_filter($gallery_images, function ($img) {
          return !empty($img['url']);
        });
      }

      return $data;
    }, $results->products);

    return [
      'products' => $products,
      'total' => $results->total,
      'max_pages' => $results->max_num_pages
    ];
  }

  /**
   * Push a product to Kaufland
   *
   * @param array $product_data The product data to push
   * @return array The API response
   */
  public function push_product($product_data)
  {
    try {
      // Get the product EAN
      $product = wc_get_product($product_data['id']);
      if (!$product) {
        throw new Exception('Product not found');
      }

      $ean = $product->get_meta('_klcnn_ean');
      if (empty($ean)) {
        throw new Exception('Product EAN is not set. Please set an EAN before pushing to Kaufland.');
      }

      // Get the product SKU
      $sku = $product->get_sku();
      if (empty($sku)) {
        throw new Exception('Product SKU is not set. Please set a SKU before pushing to Kaufland.');
      }

      $endpoint = 'product-data';

      // Structure the request data EXACTLY as in documentation
      $request_data = [
        'ean' => [
          $ean
        ],
        'attributes' => [
          'title' => [
            $product_data['name']
          ],
          'description' => [
            wp_strip_all_tags($product_data['description'])
          ],
          'category' => [
            $product_data['category']
          ],
          'manufacturer' => [
            $product->get_meta('_klcnn_manufacturer') ?: 'Unknown'
          ],
          'sku' => [
            $sku
          ]
        ]
      ];

      // Get main image URL
      $main_image_id = $product->get_image_id();
      $main_image_url = null;
      if ($main_image_id) {
        // Check for processed version
        $processed_main_image_id = get_post_meta($main_image_id, '_klcnn_processed_image_id', true);
        if ($processed_main_image_id) {
          $main_image_url = wp_get_attachment_url($processed_main_image_id);
        } else {
          $main_image_url = wp_get_attachment_url($main_image_id);
        }
      }

      // Get gallery image URLs
      $gallery_image_ids = $product->get_gallery_image_ids();
      $gallery_image_urls = array_map(function ($id) {
        // Check for processed version
        $processed_image_id = get_post_meta($id, '_klcnn_processed_image_id', true);
        if ($processed_image_id) {
          return wp_get_attachment_url($processed_image_id);
        }
        return wp_get_attachment_url($id);
      }, $gallery_image_ids);

      // Filter out any null/false URLs
      $gallery_image_urls = array_filter($gallery_image_urls);

      // Combine main image and gallery images
      $all_image_urls = [];
      if ($main_image_url) {
        $all_image_urls[] = $main_image_url;
      }
      $all_image_urls = array_merge($all_image_urls, $gallery_image_urls);

      // Add images to request if we have any
      if (!empty($all_image_urls)) {
        $request_data['attributes']['picture'] = $all_image_urls;
      }

      // Make the API request
      $response = $this->request(
        'PUT',
        $endpoint,
        $request_data
      );
      // Handle WP_Error response
      if (is_wp_error($response)) {
        throw new Exception($response->get_error_message());
      }

      // Check for successful response
      if (isset($response['update_status'])) {
        // Handle legacy/documented response format
        switch ($response['update_status']) {
          case 'PENDING':
          case 'IN_PROGRESS':
            break;
          case 'SUCCESS':
            break;
          case 'FAIL':
            $fail_reason = isset($response['update_fail_reason']) ? $response['update_fail_reason'] : 'Unknown reason';
            throw new Exception('Product push failed: ' . $fail_reason);
        }
      } elseif (isset($response['data']) && $response['data'] === 'Content created or replaced') {
        // Product data pushed successfully, now push inventory
        try {
          $inventory_response = $this->push_inventory($ean, $sku);
          $response['inventory'] = $inventory_response;
        } catch (Exception $e) {
          $response['inventory_error'] = $e->getMessage();
        }
      } else {
        throw new Exception('Unexpected response format from Kaufland API');
      }

      return $response;
    } catch (Exception $e) {
      throw $e;
    }
  }

  /**
   * Push inventory data to Kaufland
   *
   * @return array
   */
  private function push_inventory($ean, $sku = null)
  {
    try {
      $endpoint = 'units';

      // Get product by EAN
      $args = array(
        'post_type' => 'product',
        'meta_key' => '_klcnn_ean',
        'meta_value' => $ean,
        'posts_per_page' => 1
      );

      $products = get_posts($args);
      if (empty($products)) {
        throw new Exception('Product not found for EAN: ' . $ean);
      }

      $product = wc_get_product($products[0]->ID);
      if (!$product) {
        throw new Exception('Failed to get WooCommerce product');
      }

      // Get SKU if not provided
      if ($sku === null) {
        $sku = $product->get_sku();
        if (empty($sku)) {
          throw new Exception('Product SKU is not set');
        }
      }

      // Get product price and convert to cents
      $price = (float) $product->get_price();
      $price_in_cents = round($price * 100);

      // Get stock quantity
      $stock_quantity = $product->get_stock_quantity();
      $amount = $stock_quantity !== null ? $stock_quantity : 0;

      // Inventory data with dynamic price and stock
      $inventory_data = [
        'ean' => $ean,
        'condition' => 'NEW',
        'listing_price' => $price_in_cents,
        'amount' => $amount,
        'id_offer' => $sku,  // Use SKU instead of EAN for id_offer
        'handling_time' => 2,
        'vat_indicator' => 'standard_rate'
      ];

      // Make the API request
      $response = $this->request(
        'POST',
        $endpoint,
        $inventory_data
      );
      if (is_wp_error($response)) {
        throw new Exception($response->get_error_message());
      }

      return $response;
    } catch (Exception $e) {
      throw new Exception('Failed to push inventory: ' . esc_html($e->getMessage()));
    }
  }
}
