<?php


class kavehpricehistory
{

  public function __construct()
  {
    if(!class_exists('woocommerce')){
      return;
    }
    add_action('add_meta_boxes', [$this, 'register_metabox']);
    add_action('save_post', [$this, 'save_price_history']);
    add_shortcode('price_chart_button', [$this, 'price_chart_button_shortcode']);

    if (function_exists('wc_get_product')) {
      add_action('wp_footer', [$this, 'render_frontend_chart'], 100);
    }
    add_action('rest_api_init', [$this, 'register_rest_api']);
  }

  public function price_chart_button_shortcode($atts)
  {
    // Shortcode attributes with defaults
    $atts = shortcode_atts(array(
      'product_id' => '',       // Allow passing product ID directly
      'style' => 'text',        // 'text', 'text_icon', or 'icon_only'
      'color' => '#333333',     // Default text/icon color
      'bg_color' => '#f5f5f5', // Default background color
      'hover_color' => '',      // Optional hover color
      'hover_bg_color' => '',   // Optional hover background color
      'icon' => 'chart-line',   // Default icon (using Dashicons or Font Awesome class)
      'text' => __('Show Price Chart', 'kavehTheme'), // Default button text
      'size' => 'medium',       // 'small', 'medium', or 'large'
    ), $atts, 'price_chart_button');

    // If product ID is not provided in shortcode, try to get current product
    if (empty($atts['product_id'])) {
      global $product;
      if (!is_a($product, 'WC_Product')) {
        return ''; // Return empty if not on a product page and no ID provided
      }
      $product_id = $product->get_id();
    } else {
      $product_id = intval($atts['product_id']);
    }

    // Sanitize attributes
    $style = in_array($atts['style'], ['text', 'text_icon', 'icon_only']) ? $atts['style'] : 'text';
    $size = in_array($atts['size'], ['small', 'medium', 'large']) ? $atts['size'] : 'medium';

    // Generate icon HTML if needed
    $icon_html = '';
    if ($style !== 'text') {
      $icon_html = '<i class="dashicons dashicons-' . esc_attr($atts['icon']) . '"></i>';
    }

    // Generate button text HTML
    $text_html = '';
    if ($style !== 'icon_only') {
      $text_html = '<span>' . esc_html($atts['text']) . '</span>';
    }

    // Generate inline styles
    $styles = array(
      'color: ' . esc_attr($atts['color']),
      'background-color: ' . esc_attr($atts['bg_color']),
    );

    // Add hover styles if specified
    $hover_styles = '';
    if (!empty($atts['hover_color']) || !empty($atts['hover_bg_color'])) {
      $hover_styles = ' onmouseover="this.style.color=\'' . esc_attr($atts['hover_color']) . '\';this.style.backgroundColor=\'' . esc_attr($atts['hover_bg_color']) . '\'"';
      $hover_styles .= ' onmouseout="this.style.color=\'' . esc_attr($atts['color']) . '\';this.style.backgroundColor=\'' . esc_attr($atts['bg_color']) . '\'"';
    }

    // Size classes
    $size_classes = array(
      'small' => 'small-price-chart-btn',
      'medium' => 'medium-price-chart-btn',
      'large' => 'large-price-chart-btn',
    );

    // Generate the button HTML
    return '<button type="button" class="show-price-chart ' . esc_attr($size_classes[$size]) . '" data-product-id="' . esc_attr($product_id) . '" style="' . implode('; ', $styles) . '"' . $hover_styles . '>' . $icon_html . $text_html . '</button>';
  }

  public function register_metabox()
  {
    add_meta_box('kaveh_price_history_box', __('Price History', 'kavehTheme'), [$this, 'render_metabox'], 'product', 'normal', 'high');
  }

  public function render_metabox($post)
  {
    $product = wc_get_product($post->ID);
    echo '<div class="kaveh-price-tabs">';

    if ($product->is_type('variable')) {
      $variations = $product->get_children();
      echo '<ul class="kaveh-tab-menu">';
      foreach ($variations as $vid) {
        $v_product = wc_get_product($vid);
        echo '<li><a href="#kaveh-tab-' . $vid . '">' . esc_html($v_product->get_name() . ' - ' . wc_get_formatted_variation($v_product, true, false, true)) . '</a></li>';
      }
      echo '</ul>';

      foreach ($variations as $vid) {
        $history = get_post_meta($vid, '_kaveh_price_history', true);
        $history = is_array($history) ? $history : [];
        echo '<div id="kaveh-tab-' . $vid . '" class="kaveh-tab-content" style="display:none">';
        echo '<div id="kaveh-price-history-wrapper-' . $vid . '">';
        foreach ($history as $index => $entry) {
          echo '<div style="margin-bottom:10px">';
          echo '<input type="text" name="kaveh_price_history[' . $vid . '][' . $index . '][date]" value="' . esc_attr($entry['date']) . '" />';
          echo '<input type="number" step="1000" name="kaveh_price_history[' . $vid . '][' . $index . '][price]" value="' . esc_attr($entry['price']) . '" />';
          echo '<button type="button" class="remove-price-row">❌</button>';
          echo '</div>';
        }
        echo '</div>';
        echo '<button type="button" class="add-price-row" data-target="' . $vid . '">' . __('Add New', 'kavehTheme') . '</button>';
        echo '</div>';
      }
    } else {
      $history = get_post_meta($post->ID, '_kaveh_price_history', true);
      $history = is_array($history) ? $history : [];
      echo '<div id="kaveh-price-history-wrapper">';
      foreach ($history as $index => $entry) {
        echo '<div style="margin-bottom:10px">';
        echo '<input type="text" name="kaveh_price_history[' . $index . '][date]" value="' . esc_attr($entry['date']) . '" />';
        echo '<input type="number" step="0.01" name="kaveh_price_history[' . $index . '][price]" value="' . esc_attr($entry['price']) . '" />';
        echo '<button type="button" class="remove-price-row">❌</button>';
        echo '</div>';
      }
      echo '</div>';
      echo '<button type="button" id="add-price-row">' . __('Add New', 'kavehTheme') . '</button>';
    }

    echo '</div>';
    echo '<style>.kaveh-tab-menu a.active { font-weight: bold; border-bottom: 2px solidrgb(9, 59, 99); }</style>';
    echo '<script>
      document.addEventListener("DOMContentLoaded", function () {
        document.querySelectorAll(".add-price-row").forEach(function(btn) {
          btn.addEventListener("click", function () {
            const target = btn.getAttribute("data-target");
            const wrapper = document.getElementById("kaveh-price-history-wrapper-" + target);
            const index = wrapper.children.length;
            const container = document.createElement("div");
            container.style.marginBottom = "10px";

            const dateInput = document.createElement("input");
            dateInput.type = "text";
            dateInput.name = `kaveh_price_history[${target}][${index}][date]`;

            const priceInput = document.createElement("input");
            priceInput.type = "number";
            priceInput.step = "0.01";
            priceInput.name = `kaveh_price_history[${target}][${index}][price]`;

            const removeBtn = document.createElement("button");
            removeBtn.type = "button";
            removeBtn.className = "remove-price-row";
            removeBtn.innerText = "❌";
            removeBtn.addEventListener("click", function () {
              container.remove();
            });

            container.appendChild(dateInput);
            container.appendChild(priceInput);
            container.appendChild(removeBtn);
            wrapper.appendChild(container);
          });
        });

        const addSingleBtn = document.getElementById("add-price-row");
        if (addSingleBtn) {
          addSingleBtn.addEventListener("click", function () {
            const wrapper = document.getElementById("kaveh-price-history-wrapper");
            const index = wrapper.children.length;
            const container = document.createElement("div");
            container.style.marginBottom = "10px";

            const dateInput = document.createElement("input");
            dateInput.type = "text";
            dateInput.name = `kaveh_price_history[${index}][date]`;

            const priceInput = document.createElement("input");
            priceInput.type = "number";
            priceInput.step = "0.01";
            priceInput.name = `kaveh_price_history[${index}][price]`;

            const removeBtn = document.createElement("button");
            removeBtn.type = "button";
            removeBtn.className = "remove-price-row";
            removeBtn.innerText = "❌";
            removeBtn.addEventListener("click", function () {
              container.remove();
            });

            container.appendChild(dateInput);
            container.appendChild(priceInput);
            container.appendChild(removeBtn);
            wrapper.appendChild(container);
          });
        }

        document.addEventListener("click", function(e) {
          if (e.target.classList.contains("remove-price-row")) {
            e.target.parentElement.remove();
          }
        });

        const tabs = document.querySelectorAll(".kaveh-tab-menu a");
        tabs.forEach(function(tab) {
          tab.addEventListener("click", function(e) {
            e.preventDefault();
            document.querySelectorAll(".kaveh-tab-content").forEach(el => el.style.display = "none");
            document.querySelectorAll(".kaveh-tab-menu a").forEach(el => el.classList.remove("active"));
            document.querySelector(tab.getAttribute("href")).style.display = "block";
            tab.classList.add("active");
          });
        });

        if (tabs.length > 0) tabs[0].click();
      });
    </script>';
  }

  public function save_price_history($post_id)
  {
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
    if (!isset($_POST['kaveh_price_history'])) $_POST['kaveh_price_history'] = [];

    $product = wc_get_product($post_id);
    $historyData = $_POST['kaveh_price_history'];
    if (!$product) return;
    if ($product->is_type('variable')) {
      foreach ($product->get_children() as $variation_id) {
        $variation = wc_get_product($variation_id);
        $entries = isset($historyData[$variation_id]) ? $historyData[$variation_id] : [];

        $clean = array_filter($entries, fn($e) => !empty($e['date']) && isset($e['price']));
        usort($clean, fn($a, $b) => strtotime($a['date']) <=> strtotime($b['date']));

        $current_price = $variation->get_price();
        $last = end($clean);
        if (!isset($last['price']) || $last['price'] != $current_price) {
          $clean[] = [
            'date' => date_i18n('Y-m-d', current_time('timestamp')),
            'price' => $current_price
          ];
        }

        update_post_meta($variation_id, '_kaveh_price_history', $clean);
      }
    } else {
      $clean = array_filter($historyData, fn($e) => !empty($e['date']) && isset($e['price']));
      usort($clean, fn($a, $b) => strtotime($a['date']) <=> strtotime($b['date']));

      $current_price = $product->get_price();
      $last = end($clean);
      if (!isset($last['price']) || $last['price'] != $current_price) {
        $clean[] = [
          'date' => date_i18n('Y-m-d', current_time('timestamp')),
          'price' => $current_price
        ];
      }

      update_post_meta($post_id, '_kaveh_price_history', $clean);
    }
  }





  public function render_frontend_chart()
  {
?>
    <div id="price-chart-overlay" style="display:none;position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.6);z-index:9998"></div>

    <div id="price-chart-modal" style="display:none;position:fixed;top:10%;left:50%;transform:translateX(-50%);background:#fff;padding:20px;border-radius:10px;z-index:9999;width:90%;max-width:600px;direction:rtl;">
      <button type="button" onclick="closePriceChart()" class="d-flex align-items-center justify-content-center" style="position:absolute;top:10px;left:10px;background:none;border:none;font-size:24px;cursor:pointer;">
        <i class="isax isax-close-square5"></i>
      </button>
      <div style="text-align:right;margin-top:0;margin-bottom:5px;"><?php _e('Product Price Chart', 'kavehTheme'); ?></div>
      <div class="product-chart-title" style="text-align:right;margin-top:3px;margin-bottom:15px;"></div>
      <ul id="chart-tabs" style="display:none;gap:10px;list-style:none;padding:0;margin:0 0 10px 0;"></ul>
      <div id="price-chart" style="height:300px;min-height:315px;position:relative;">
        <div id="price-chart-loader" style="display:none;position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);z-index:2;">
          <div style="width:30px;height:30px;border:4px solid #ccc;border-top:4px solid #2271b1;border-radius:50%;animation:spin 1s linear infinite;"></div>
        </div>
      </div>
    </div>

    <style>
      @keyframes spin {
        0% {
          transform: rotate(0deg);
        }

        100% {
          transform: rotate(360deg);
        }
      }

      .chart-tab-button {
        color: #000;
        padding: 3px 10px;
        background-color: #ededed;
        border-radius: 12px;
        cursor: pointer;
      }

      .chart-tab-button.active,
      .chart-tab-button:hover {
        background-color: #212341;
        color: #fff;
      }
    </style>

    <script>
      document.addEventListener("DOMContentLoaded", function() {
        const overlay = document.getElementById("price-chart-overlay");
        const modal = document.getElementById("price-chart-modal");
        const chartContainer = document.getElementById("price-chart");
        const loader = document.getElementById("price-chart-loader");
        const chartTabs = document.getElementById("chart-tabs");

        let chartInstance = null;

        function renderChart(data) {
          const prices = data.map(item => parseFloat(item.price));
          const minPrice = Math.floor(Math.min(...prices) / 1000) * 1000;
          const maxPrice = Math.ceil(Math.max(...prices) / 1000) * 1000;

          if (chartInstance) {
            chartInstance.destroy();
            chartInstance = null;
          }

          chartInstance = new ApexCharts(chartContainer, {
            chart: {
              type: 'line',
              height: 300,
              toolbar: {
                show: false
              }
            },
            series: [{
              name: '',
              data: prices
            }],
            xaxis: {
              categories: data.map(item => item.date),
              labels: {
                style: {
                  fontFamily: 'inherit'
                },
                rotate: -30
              }
            },
            yaxis: {
              min: minPrice,
              max: maxPrice,
              tickAmount: 5,
              labels: {
                formatter: val => `${val.toLocaleString('en-US')}`,
                style: {
                  fontFamily: 'inherit'
                }
              }
            },
            tooltip: {
              style: {
                fontFamily: 'inherit',
                direction: 'rtl'
              },
              y: {
                formatter: val => `${val.toLocaleString('en-US')}`,
              }
            },
            legend: {
              show: false
            }
          });

          chartInstance.render().then(() => loader.style.display = "none");
        }

        window.closePriceChart = function() {
          overlay.style.display = "none";
          modal.style.display = "none";
          chartTabs.innerHTML = "";
          chartTabs.style.display = "none";
          if (chartInstance) {
            chartInstance.destroy();
            chartInstance = null;
          }
        };

        overlay.addEventListener("click", closePriceChart);

        document.querySelectorAll(".show-price-chart").forEach(button => {
          button.addEventListener("click", function() {
            const productId = this.dataset.productId;

            overlay.style.display = "block";
            modal.style.display = "block";
            loader.style.display = "block";

            fetch(`/wp-json/kaveh/v1/product-name/${productId}`)
              .then(res => res.json())
              .then(data => {
                document.querySelectorAll(".product-chart-title").forEach(el => {
                  el.textContent = ` ${data.name}`;
                });
              });

            fetch(`/wp-json/kaveh/v1/price-history/${productId}`)
              .then(res => res.json())
              .then(response => {
                loader.style.display = "none";

                if (Array.isArray(response)) {
                  // Simple product
                  chartTabs.style.display = "none";
                  renderChart(response);
                } else {
                  // Variable product
                  chartTabs.innerHTML = "";
                  chartTabs.style.display = "flex";

                  Object.entries(response).forEach(([vid, item], idx) => {
                    const btn = document.createElement("button");
                    btn.className = "chart-tab-button" + (idx === 0 ? " active" : "");
                    btn.textContent = item.label;
                    btn.dataset.vid = vid;
                    chartTabs.appendChild(btn);

                    if (idx === 0) renderChart(item.history);
                  });
                }
              });
          });
        });


        document.addEventListener("click", function(e) {
          if (e.target.classList.contains("chart-tab-button")) {
            document.querySelectorAll(".chart-tab-button").forEach(btn => btn.classList.remove("active"));
            e.target.classList.add("active");

            const vid = e.target.dataset.vid;
            loader.style.display = "block";

            fetch(`/wp-json/kaveh/v1/price-history/${vid}`)
              .then(res => res.json())
              .then(data => renderChart(data));
          }
        });
      });
    </script>
<?php
  }



  public function register_rest_api()
  {
    register_rest_route('kaveh/v1', '/price-history/(?P<id>\d+)', [
      'methods' => 'GET',
      'callback' => [$this, 'get_price_data'],
      'permission_callback' => '__return_true',
    ]);
    register_rest_route('kaveh/v1', '/product-name/(?P<id>\d+)', [
      'methods' => 'GET',
      'callback' => [$this, 'get_product_name'],
      'permission_callback' => '__return_true',
    ]);
  }
  public function get_product_name($request)
  {
    $product_id = intval($request['id']);
    $product = wc_get_product($product_id);

    if (!$product) {
      return new WP_Error('no_product', __('Product not found', 'kavehTheme'), ['status' => 404]);
    }

    return rest_ensure_response([
      'name' => $product->get_name()
    ]);
  }


  public function get_price_data($request)
  {
    $product_id = intval($request['id']);
    $product = wc_get_product($product_id);

    if (!$product) {
      return new WP_Error('no_product', __('Product does not exist', 'kavehTheme'), ['status' => 404]);
    }

    // Variable: categorized output with attribute labels
    if ($product->is_type('variable')) {
      $variations = $product->get_children();
      $result = [];

      foreach ($variations as $vid) {
        $variation = wc_get_product($vid);
        if (!$variation) continue;

        $history = get_post_meta($vid, '_kaveh_price_history', true);
        if (!is_array($history)) continue;

        $clean = array_filter($history, fn($item) => !empty($item['date']) && isset($item['price']));

        // Combined attribute labels
        $attrs = $variation->get_attributes();
        $parts = [];
        foreach ($attrs as $taxonomy => $slug) {
          $term = get_term_by('slug', $slug, $taxonomy);
          $parts[] = $term ? $term->name : $slug;
        }

        $result[$vid] = [
          'label'   => implode(' - ', $parts),
          'history' => array_values($clean),
        ];
      }

      return rest_ensure_response($result);
    }

    // Simple: just date and price list
    $history = get_post_meta($product_id, '_kaveh_price_history', true);
    if (!is_array($history)) return rest_ensure_response([]);

    $clean = array_filter($history, fn($item) => !empty($item['date']) && isset($item['price']));
    return rest_ensure_response(array_values($clean));
  }
}
