<?php

namespace WCPT\Pro\VariationTableOverride;

class VariationTableOverride
{
  public function __construct()
  {
    add_action('woocommerce_before_single_product', [$this, 'maybe_insert_variation_table']);
  }

  public function maybe_insert_variation_table()
  {
    global $product;

    if ($product && is_object($product) && $product->is_type('variable')) {
      $settings = wcpt_get_settings_data();
      $variation_table_override = empty($settings['variation_table_override']) ? [] : $settings['variation_table_override'];

      foreach ($variation_table_override as $rule) {
        if ($this->is_rule_applicable($rule, $product)) {
          $this->handle_variation_table_insertion($rule);
          $this->handle_variation_table_tab($rule);
        }
      }
    }
  }

  private function is_rule_applicable($rule, $product)
  {
    $product_cats = wp_get_post_terms($product->get_id(), 'product_cat', ['fields' => 'ids']);
    return !empty(array_intersect($rule['termIds'], $product_cats));
  }

  private function handle_variation_table_insertion($rule)
  {
    if (empty($rule['enabled']) || empty($rule['variationTableId']))
      return;

    if (!empty($rule['hideDefaultVariationForm']) && $rule['hideDefaultVariationForm']) {
      remove_action('woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30);
    }

    switch ($rule['variationTablePosition']) {
      case 'above-short-descp':
        add_action('woocommerce_single_product_summary', function () use ($rule) {
          $this->render_variation_table($rule);
        }, 15);
        break;
      case 'below-short-descp':
        add_action('woocommerce_single_product_summary', function () use ($rule) {
          $this->render_variation_table($rule);
        }, 25);
        break;
      case 'below-variation-form':
        if (!empty($rule['hideDefaultVariationForm']) && $rule['hideDefaultVariationForm']) {
          add_action('woocommerce_single_product_summary', function () use ($rule) {
            $this->render_variation_table($rule);
          }, 25);
        } else {
          add_action('woocommerce_after_single_variation', function () use ($rule) {
            $this->render_variation_table($rule);
          }, 5);
        }
        break;
      case 'above-tabs':
        add_action('woocommerce_after_single_product_summary', function () use ($rule) {
          $this->render_variation_table($rule);
        }, 5);
        break;
      case 'starting-descp-tab':
        add_action('woocommerce_product_description_heading', function () use ($rule) {
          $this->render_variation_table($rule);
        }, 5);
        break;
      case 'ending-desc-tab':
        add_action('woocommerce_after_single_product_summary', function () use ($rule) {
          $this->render_variation_table($rule);
        }, 15);
        break;
      case 'via-shortcode':
        add_shortcode('wcpt_variation_table', function () use ($rule) {
          ob_start();
          $this->render_variation_table($rule);
          return ob_get_clean();
        });
        break;
    }
  }

  private function handle_variation_table_tab($rule)
  {
    if ($rule['variationTablePosition'] === 'new-tab' && !empty($rule['variationTabName'])) {
      add_filter('woocommerce_product_tabs', function ($tabs) use ($rule) {
        $priority = 50; // Default priority
        switch ($rule['variationTabPosition']) {
          case 'first':
            $priority = 5;
            break;
          case 'after-description':
            $priority = isset($tabs['description']) ? $tabs['description']['priority'] + 1 : 15;
            break;
          case 'after-additional-info':
            $priority = isset($tabs['additional_information']) ? $tabs['additional_information']['priority'] + 1 : 25;
            break;
          case 'after-reviews':
            $priority = isset($tabs['reviews']) ? $tabs['reviews']['priority'] + 1 : 35;
            break;
          case 'after-all-tabs':
            $max_priority = array_reduce($tabs, function ($max, $tab) {
              return $tab['priority'] > $max ? $tab['priority'] : $max;
            }, 0);
            $priority = $max_priority + 5;
            break;
          case 'custom':
            $priority = !empty($rule['variationTabPriority']) ? $rule['variationTabPriority'] : $priority;
            break;
        }

        $tabs['variation_table_tab'] = [
          'title' => $rule['variationTabName'],
          'priority' => $priority,
          'callback' => function () use ($rule) {
            echo '<style>.woocommerce-tabs .wcpt {margin: 10px 0 20px;}</style>';
            $this->render_variation_table($rule);
          }
        ];
        return $tabs;
      });
    }
  }

  private function render_variation_table($rule)
  {
    $variation_table_id = $rule['variationTableId'];
    if ($variation_table_id === '_custom_shortcode') {
      if (!empty($rule['customTableShortcode'])) {
        echo $rule['customTableShortcode'];
      }
    } else {
      $qty_to_cart_attr = defined('WCPT_ACQ') ? ' add_to_cart_from_quantity="true" ' : "";
      echo do_shortcode('[product_table id="' . $variation_table_id . '" product_variations="true"' . $qty_to_cart_attr . ']');
    }
  }
}

new VariationTableOverride();